1

How can I print numbers in given range. Example: 10 - 13 in randomized order (10 12 13 11)?

public class RandomizeNumbers {
    public static void main(String[] args) {
        Scanner getInput = new Scanner(System.in);
        int minimum = getInput.nextInt();
        int maximum = getInput.nextInt();
        Random t = new Random();

        for (int i = minimum; i <= maximum; i++) {
            System.out.println(t.nextInt(i));
        }
    }
}
mpromonet
  • 11,326
  • 43
  • 62
  • 91
  • 1
    possible duplicate of http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java – Sajan Chandran Oct 16 '15 at 14:24
  • @SajanChandran No, it is not a duplicate. The current question is about list permutations. Your link is about picking one random integer in a specific range. – Nayuki Oct 16 '15 at 14:34

3 Answers3

4

Fill up a list with necessary items and shuffle them using Collections.shuffle(), then print:

List<Integer> c = new ArrayList<>();
for (int i = start; i <= end; i++)
   c.add(i);
Collections.shuffle(c);
System.out.println(c);
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
0

Just for knowledge, you must not use this approach,

new Random().ints(start, endExclusive).distinct().limit(quantity).boxed().forEach(System.out::println);

Obs: you need java 8 to use it.

Johnny Willer
  • 3,717
  • 3
  • 27
  • 51
0

Using Java 8 IntStream, it is as simple as:

IntStream.rangeClosed(minimum, maximum).map(i -> t.nextInt(i))
                .forEach(System.out::println);

Usage:

import java.util.Random;
import java.util.Scanner;
import java.util.stream.IntStream;

public class RandomNumbers {
    public static void main(String[] args) {
        Scanner getInput = new Scanner(System.in);
        int minimum = getInput.nextInt();
        int maximum = getInput.nextInt();

        Random t = new Random();
        IntStream.rangeClosed(minimum, maximum).map(i -> t.nextInt(i))
                .forEach(System.out::println);

        getInput.close();
    }
}
Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108