-1

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

Fahadakbar
  • 488
  • 1
  • 8
  • 26
  • 1
    sure - call your shuffle method on the first 10 elements. can you give us the code you're working with, what you've tried, what's not working? see the guide to [ask] – Michael Delgado May 10 '22 at 01:47
  • Does this answer your question? [Python - shuffle only some elements of a list](https://stackoverflow.com/questions/9557182/python-shuffle-only-some-elements-of-a-list) – Cresht May 10 '22 at 01:47
  • 1
    Does this answer your question? [how to shuffle a binary array a specific amount](https://stackoverflow.com/questions/57632008/how-to-shuffle-a-binary-array-a-specific-amount) – im_vutu May 10 '22 at 01:48

2 Answers2

2

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.

0
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

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179