0

我正在创建一个简单的 Mastermind 游戏,其中我的颜色由 0 到 9 的数字表示。程序应该生成一个长度为 3 到 9 位的随机代码。我决定使用一个数组来保存我的数字 0 到 9,但我不知道如何从这个数组中生成一个随机长度的随机数。有人可以帮我吗?

4

4 回答 4

1

使用随机数生成器

Random rnd=new Random()
int x=rnd.nextInt(10)
于 2013-01-23T19:03:06.240 回答
1

这是示例代码:

package testing.Tests_SO;

import java.util.Arrays;
import java.util.Random;

public class App14487237 {

    // creating random number generator object
    public static final Random rnd = new Random();

    public static int[] getNumber() {

        // generating array length as rundom from 3 to 9 inclusive
        int length = rnd.nextInt(7) + 3;

        // creating an array
        int[] number = new int[length];

        // filling an array with random numbers from 0 to 9 inclusive
        for(int i=0; i<number.length; ++i) {
            number[i] = rnd.nextInt(10);
        }

        // returning and array
        return number;

    }


    public static void main(String[] args) {

        // generating number 10 times and prin result
        for(int i=0; i<10; ++i) {
            System.out.println( "attempt #" + i + ": " + Arrays.toString( getNumber()  ) );
        }
    }
}

这是它的输出:

attempt #0: [0, 2, 6, 2, 5, 7, 5, 3]
attempt #1: [6, 2, 6, 6, 6, 2]
attempt #2: [8, 9, 6]
attempt #3: [6, 4, 7, 2, 1, 5, 7, 0]
attempt #4: [8, 2, 6, 7, 3, 8, 2, 9, 1]
attempt #5: [8, 6, 5, 9, 8, 8, 3, 9]
attempt #6: [6, 2, 3, 8, 6]
attempt #7: [3, 4, 6, 2]
attempt #8: [0, 5, 0, 0, 5, 8, 9, 4, 6]
attempt #9: [2, 2, 3, 3, 4, 9, 0]

附言

打印关闭:

int[] number;
for(int i=0; i<10; ++i) {
    number = getNumber();
    System.out.print( "attempt #" + i + ": " );
    for(int j=0; j<number.length; ++j ) {
        System.out.print(number[j]);
    }
    System.out.println();
}
于 2013-01-23T19:31:10.037 回答
0

我相信您想要的是数组中元素随机排列的一部分。这可以分两步完成。

  1. 使用随机生成器重复交换数组中的元素。

    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
    }
    
  2. 选择一个随机长度ln并将元素从0ln

于 2013-01-23T20:06:41.593 回答
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());
于 2013-01-23T19:17:48.733 回答