0

I'm trying to generate a random number with 4 different digits.

The catch is that it needs to be a one-liner, the solution doesn't need to be pretty.

I already tried using Collections.shuffle(Mylist) but I couldn't make it in one line.

My code so far:

List<Integer> digits = IntStream.range(0,10).boxed().collect(Collectors.toList());
Collections.shuffle(digits);
System.out.println(digits.subList(0,4));
Eilonlif
  • 346
  • 2
  • 7
  • `int i = 1234; // chosen by random dice roll`. Done. But why exactly do you want to solve this as a one-liner? Code should be a simple to read as possible. You can easily strip out newlines in Java, the result is a one-liner but completely unmaintainable and unreadable. Lines and statements aren't the same thing. – Polygnome Sep 08 '20 at 12:54
  • 1
    Is a number like `0962` considered valid (one that starts with a `0`)? – deHaar Sep 08 '20 at 13:01
  • 3
    Delete the line breaks. Boom - one-liner. – Michael Sep 08 '20 at 13:01
  • It's for a school project and I'm bored lol – Eilonlif Sep 08 '20 at 13:18

1 Answers1

3

I'm not sure do I want to know why you need this to be a one-liner (:)) but it may be e.g.

Stream.of(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9))
    .peek(Collections::shuffle)
    .map(list -> list.subList(0, 4))
    .findFirst()
    .get()

EDIT

If you need to make sure that the number will not start with 0 you can change the map fragment to e.g.

.map(list -> (list.get(0).equals(0)) ? list.subList(1, 5) : list.subList(0, 4))
m.antkowicz
  • 13,268
  • 18
  • 37
  • 2
    Upvoted, but beware that 4-digit numbers starting with 0 may not be considered validly "4-digit" – tucuxi Sep 08 '20 at 12:57
  • 1
    ugh you are right - OP is writing about 'number' not the string/list – m.antkowicz Sep 08 '20 at 12:58
  • one more thing, how can I convert the list into an int? @m.antkowicz – Eilonlif Sep 08 '20 at 13:24
  • basically you should iterate from the end to the beginning and add to the sum multiplying by the consecutive powers of `10`, but if you need to keep it as a one-liner you can just add `.map(list -> Integer.valueOf(list.stream().map(String::valueOf).collect(Collectors.joining())))` before the `findFirst` to cast randomed integers to strings, join them togetger and get the integer value of such string :) @Eilonlif – m.antkowicz Sep 08 '20 at 13:42
  • Thank you so much! – Eilonlif Sep 08 '20 at 15:09