1
$\begingroup$

I have a list, then I want to pick 2 elements (RandomSample[list,2]) put them in a new list (those two element will be one element in the new list, like list of lists) and delete them from the my inicial list and follow the process until my first list turn empty. I need that my out be a list of lists of the random sample elements. What can I do?

$\endgroup$
2
  • $\begingroup$ It's hard to understand what your desired input and output are. Can you give an example? $\endgroup$
    – bill s
    Mar 14, 2018 at 13:53
  • 2
    $\begingroup$ Why not just do Partition[RandomSample[list], 2]? Basically, you prescramble the starting list, and just take two elements at a time. $\endgroup$ Mar 14, 2018 at 13:54

1 Answer 1

1
$\begingroup$

Let's say you have a list

list = Range[20]
(* {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20} *)

The better approach, as JM already said is to scramble your original list

RandomSample[list]
(* {3, 20, 6, 7, 15, 13, 10, 11, 16, 4, 9, 14, 8, 12, 1, 17, 18, 2, 19, 5} *)

Now, you only need to partition this list and you are done

Partition[%, 2]
(* {{3, 20}, {6, 7}, {15, 13}, {10, 11}, {16, 4}, {9, 14}, 
   {8, 12}, {1, 17}, {18, 2}, {19, 5}} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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