我正在创建一个简单的Mastermind游戏,我的颜色用0到9之间的数字表示。程序应该生成一个长度为3到9位的随机代码。我决定使用一个数组来保存我的数字0到9,但我不知道如何从这个数组生成一个随机长度的随机数。有人可以帮帮我吗?
答案 0 :(得分:0)
使用随机数生成器来确定字符串的长度。
然后在for循环中使用随机数生成器来选择数组中的每个数字。
这样的事情:
// the array of valid numbers
int[] numbers = // intialize this however you want
Random rand = new Random();
// determine random length between 3 and 9
int numLength = rand.nextInt(7) + 3;
StringBuilder output = new StringBuilder();
for (int i = 0; i < numLength; i++) {
// use a random index to choose a number from array
int thisNum = rand.nextInt(numbers.length);
// append random number from array to output
output.append(thisNum);
}
System.out.println(output.toString());
答案 1 :(得分:0)
我相信你想要的是数组中random permutation个元素的一部分。这可以分两步完成。
使用随机生成器重复交换数组中的元素。
int n = arr.length;
for (int i = 0; i < n-1; i++) {
int j = i + rnd.nextInt(n-i); // select element between i and n
// swap elements i and j in the array
}
选择随机长度ln
并将0
中的元素转换为ln