3
$\begingroup$

I have a collection of lists containing random elements of a sequence, say integers from 0 to 3.

sequence={0., 1., 2., 3.};
Table[RandomSample[sequence, RandomInteger[{1, 4}]], {5}]

{{3., 0., 1.}, {3., 1., 0., 2.}, {1., 3.}, {1., 3., 0., 2.}, {0., 2., 3.}}

How do I populate the lists so that the missing sequence members are filled?

{{3., 0., 1., 2.}, {3., 1., 0., 2.}, {1., 3., 0., 2.}, {1., 3., 0., 2.}, {0., 2., 3., 1.}}

Note: answers where elements are Integers are fine but I'm also looking for answers which work for Real elements.

$\endgroup$

1 Answer 1

7
$\begingroup$

This should work for any kind of list, not just numeric ones :)

sequence = {0., 1., 2., 3.};
list = Table[RandomSample[sequence, RandomInteger[{1, 4}]], {5}]

{{2., 0.}, {0., 3.}, {2.}, {0., 3., 1.}, {1., 0., 2., 3.}}

#~Join~Complement[sequence, #] & /@ list

{{2., 0., 1., 3.}, {0., 3., 1., 2.}, {2., 0., 1., 3.}, {0., 3., 1., 2.}, {1., 0., 2., 3.}}

$\endgroup$
1
  • 1
    $\begingroup$ I could have sworn I looked for that Complement function in the docs... Nice one-liner! $\endgroup$
    – Musang
    Aug 23, 2018 at 19:26

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.