Reputation: 277
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));
}
}
}
Upvotes: 1
Views: 360
Reputation: 29276
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();
}
}
Upvotes: 0
Reputation: 3917
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.
Upvotes: 0
Reputation: 14338
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);
Upvotes: 4