random - How do I randomly select 'k' positions in a list and shuffle their respective elements without effecting the other elements?
Imagine I have some list:
listA = {"a","b","c","d","e","f","g","h","i","j"};
I'd like to randomly select k positions in the list, for example k = 3 and we select positions {1,9,10}, then randomly shuffle the elements at these positions e.g. giving us ONE of the following five possible outcomes:
listApartialscramble1 = {"a","b","c","d","e","f","g","h","i","j"};
listApartialscramble1 = {"a","b","c","d","e","f","g","h","j","i"};
listApartialscramble2 = {"i","b","c","d","e","f","g","h","j","a"};
listApartialscramble3 = {"i","b","c","d","e","f","g","h","a","j"};
listApartialscramble4 = {"j","b","c","d","e","f","g","h","i","a"};
listApartialscramble5 = {"j","b","c","d","e","f","g","h","a","i"};
Is there a simple way to do this, perhaps with RandomSample?
Answer
listA=CharacterRange["a","j"];
k = 5;
set = RandomSample[Range@Length@listA, k]
listA[[ set]] = listA[[ RandomSample@set]];
listA
{8, 3, 10, 1, 4}
{"g", "b", "c", "d", "j", "f", "e", "h", "i", "a"}
Comments
Post a Comment