0

What is the correct code for getting a realy random sublist (with size X) of a List with Integers? {1,2,5,7,12,18,71,72,73} -> get a sublist e.g with 4 items ->Result: {1,5,71,73}

I was trying to solve it with Random.nextInt, but as my first list is not in a row, it's not possible. What would be the correct solution?

João Dias
  • 16,277
  • 6
  • 33
  • 45
Fabian K
  • 71
  • 7
  • 1
    Is it allowed to repeat elements from the source list or not? – broot Nov 15 '21 at 23:40
  • both solutions would be interesting. – Fabian K Nov 15 '21 at 23:43
  • 1
    `Collections#shuffle`, where you can then sublist/"slice" the start of the list away. Repeat as necessary until the collection is depleted – Rogue Nov 15 '21 at 23:45
  • Your question got closed because you tagged it Java and there was an existing Java answer. The Kotlin-preferred way of doing it is different than how you'd do it in Java. – Tenfour04 Nov 15 '21 at 23:57

1 Answers1

5

If we can take the same element repeatedly:

List(x) { list.random() }

If we cannot:

list.asSequence()
    .shuffled()
    .take(x)
    .toList()
broot
  • 21,588
  • 3
  • 30
  • 35