JAVA打印N个不同的随机数

来源:百度知道 编辑:UC知道 时间:2024/06/05 20:43:40
String input = JOptionPane.showInputDialog
("How many numbers do you need to draw?");
int k = Integer.parseInt(input);

input = JOptionPane.showInputDialog
("What is the highest number you can draw?");
int n = Integer.parseInt(input);

// 定义数组并复制1-n
int[] numbers = new int[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++)
{
// make a random index between 0 and n - 1
int r = (int)(Math.random() * n);

// pick the element at the random location
result[i] = numbers[r];

// move the last element into the random location
numbers[r] = numbers[n - 1];
n--;

新的random就是是0-3之间的数,这个0-3是指numbers数组的下标,下标一样不要紧,指向的元素不同就行了
模拟下:
numbers[0][1][2][3][4][5]
0 1 2 3 4 5(无重复)
result[0] = 1
numbers[0][1][2][3][4]
0 5 2 3 4 (无重复)
result[2] = 3
numbers[0][1][2][3]
0 5 2 4 (无重复)
...