4
$\begingroup$

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?

$\endgroup$
6
$\begingroup$
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"}
$\endgroup$
  • $\begingroup$ Funny, I've always written this operation listA[[set]] = RandomSample @ listA[[set]] -- it never occurred to me to shuffle the indices though the effect is equivalent. $\endgroup$ – Mr.Wizard Apr 15 '14 at 20:06
  • $\begingroup$ @Mr.Wizard :) I'm probably biased by the question wording where positions/indices are stressed. That being said, I don't know now if I'd use your approach but yes, I haven't thought about it :) $\endgroup$ – Kuba Apr 15 '14 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.