0

色が 0 から 9 までの数字で表される単純なマスターマインド ゲームを作成しています。プログラムは 3 桁から 9 桁の長さのランダム コードを生成する必要があります。配列を使用して 0 ~ 9 の数値を保持することにしましたが、この配列からランダムな長さの乱数を生成する方法がわかりません。誰か助けてくれませんか?

4

4 に答える 4

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]

PS

近くに印刷するには:

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 に答える
1

乱数ジェネレーターを使用します。

Random rnd=new Random()
int x=rnd.nextInt(10)
于 2013-01-23T19:03:06.240 に答える
0

あなたが望むのは、配列内の要素のランダムな順列の一部だと思います。これは 2 つのステップで行うことができます。

  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 に答える