1

配列 a に 1 ~ 10 の数字を入力し、その配列から乱数を取得して配列 b に追加し、配列 a からその要素を削除しようとしています。これを行う最も効率的な方法を知りたいです。EDIT:(この演習では、配列に値が繰り返されておらず、メソッドが呼び出されるたびに順列がランダムである必要があります。)これまでの私の方法は次のとおりです。

public int[] nextPermutation() {
    int capOne = 10;
    int capTwo = 10;
    int aSize = 0;
    int bSize = 0;


    int[] a = new int[capOne];
    int[] b = new int[capTwo];

    int upperBound = 11;
    Random generator = new Random();

    //fill initial array with 1 - 10
    for (int i = aSize; i < 10; i++) {
        a[i] = i + 1;
        //companion variable for sizing array
        aSize++;
    }

    //Create a random integer and add it to array b
    //Remove same integer from array a
    //Repeat and remove another random integer from the remaining integers in array a and    add it to b


        permuted = b;
        return permuted;
        }

完全に間違った方法ではないにしても、私はこれに非効率的にアプローチしている可能性があります。もしそうなら、私はあなたが私に言うことを躊躇しないと確信しています. これに関するヘルプは大歓迎です。

4

2 に答える 2

1

あなたはできる:

//randomly choose element
int index = (int) (Math.random() * aSize);
int dataFromA = a[index];

//"remove" it from A
aSize--;
for(int i = index; i<aSize; i++) {
    a[i] = a[i+1];
}

//"add" it to b
b[bSize] = dataFromA;
bSize++;

興味深い部分だけが A から削除されます。ここでは、サイクルの前にサイズを縮小する必要があります (または、サイズを減らすことができますi < aSize-1)。

これは演習なので、配列使用する必要があると思いますが、これを使用Listする方が良いでしょう。

于 2013-07-02T05:59:12.737 に答える
0

これは、スワップを使用してランダムな順列を生成するプログラムです。どちらがより良い結果をもたらすかはわかりませんが、スワップは配列への追加/配列からの削除よりも高速である必要があります。

public int[] nextPermutation() {
    int cap = 10;
    int[] a = new int[cap];
    Random generator = new Random();

    //fill initial array with 1 - 10
    for (int i = 0; i < cap; i++) {
        a[i] = i + 1;
    }

    for (int i = 0; i < cap; i++) {
        int j = generator.nextInt(cap);
        int x = a[j];
        a[j] = a[i];
        a[i] = x;
    }

    // You can reduce the size of the output array:
    // int output[] = new int[5];
    // System.arraycopy(a, 0, output, 0, 5);
    // return output;

    return a;
}
于 2013-07-02T05:48:48.327 に答える