Home > Enterprise >  python shuffle a percentage of an array
python shuffle a percentage of an array

Time:05-10

Let us say that I have an array of len 50. All of the elements are binary (1 or 0). Now I want to shuffle this array such that shuffle happens only on 20% of elements i.e. only 10 elements get shuffled, and the rest of the elements maintain their index position.

is it possible to do that?

Thanks

CodePudding user response:

import random
size = 100
a = list(range(size))

def rng_swap(a,i):
    rng = random.randint(0,len(a)-1)
    a[i],a[rng] = a[rng],a[i]
def kindof_shuffle(a,swap_chance):
    for i in range(len(a)):
        if random.random()<0.1:
           rng_swap(a,i)

kindof_shuffle(a,swap_chance=0.2)

print(a)
print(sum([v==i for i,v in enumerate(a)])/size)

should leave about 80% ( /- some) of the array unchanged

or you could do something like to get closer to exactly 20%

twnty_pct = int(size*0.2)
indices = random.sample(list(range(size)),twnty_pct)
for i1,i2 in zip(indices,indices[1:]):
    a[i1],a[i2] = a[i2],a[i1]
print(a)

note that the second solution is suboptimal and includes some extra swaps that are not really adding much

CodePudding user response:

Here is one solution to this problem:

import math
import random


def shuffle(arr, percentage:int):
    """

    :param arr: The array of booleans to shuffle
    :param percentage: Out of 100
    :return: The new array
    """
    number_of_elemets_to_change = math.floor(percentage/len(arr)*100)
    array_indexes_to_change = []

    # Make a list of the indexes to change
    for i in range(number_of_elemets_to_change):
        array_indexes_to_change.append(random.randint(0, len(arr)-1))

    for index in array_indexes_to_change:
        element = arr[index]
        arr[index] = not element

    return arr


array = [True]*50

#Example
print("Array:")
print(array)
print("New array:")
print(shuffle(array, 20))


This will shuffle the percentage of the array that you send to the function.

  • Related