java 無重複取隨機數

TheNowWjj發表於2016-04-21
Scanner in = new Scanner(System.in);
System.out.println("How many numbers do you need to draw?");
int k = in.nextInt();
System.out.println("What is the highest number you can draw?");
int n = in.nextInt();
int numbers[] = new int[n];
// n=5,k=6
// fill an array with numers 1,2,3...n
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
}
// draw k numbers and put them into a second array
int[] result = new int[k];


for (int i = 0; i < result.length; i++) {
int r = (int) (Math.random() * n);
result[i] = numbers[r];


numbers[r] = numbers[n - 1];
n--;
}


// print the sorted array
Arrays.sort(result);
System.out
.println("Bet the following combinaation.It'll make you rich!");
for (int r : result)
System.out.println(r);

相關文章