0

基本的に、私はグリッドを作成し、その上にポイントをプロットしています.2つのポイントがまったく同じ場所にあることはありません[(3,4)は(4,3)とは異なります]。y 座標は 2 と 7 の範囲内 (つまり 2、3、4、5、6、7) である必要があり、x 座標は 1 と 7 の範囲内である必要があります。最小範囲と最大範囲の間の乱数。これが私がこれまでに持っているものです。

var xposition = [];
var yposition = [];
var yShouldBeDifferentThan = []

function placeRandom() {
    for (s=0; s<xposition.length ; s++ ) {
        if (xposition[s] == x) { // loops through all numbers in xposition and sees if the generated x is similar to an existing x
             yShouldBeDifferentThan.push(yposition[s]); //puts the corresponding y coordinate into an array.
             for (r=0; r<yShouldBeDifferentThan.length; r++) {
                 while (y == yShouldBeDifferentThan[r]) {
                     y = getRandom(2,7);
                 }
             }
        }
    }
    xposition.push(x);
    yposition.push(y);
}

これに関する問題は、

xposition = [1, 5, 5, 7, 5, 5]
yposition = [1, 3, 7, 2, 3, 6]
yShouldBeDifferentThan = [3, 7, 3, 6]

最初に、3 とは異なる乱数、たとえば 6 を生成します6 == 7。そうではありません。6 == 3? そうではありません。6 == 6 ? そうなので、6 以外の乱数を生成します。ここで問題が発生します。数値 3 が生成される可能性があります。私のgetRandom関数は次のとおりです。

function getRandom(min, max) {
    return min + Math.floor(Math.random() * (max - min + 1));
}

必要に応じて数値も除外できるように機能を作成することを考えていましたgetRandomが、これを行う方法がわかりません。関数の最後の while ループよりも数値を除外することができればplaceRandom、おそらく次のようなことができます。

y = getRandom(2,7) // excluding all numbers which already exist in the ShouldBeDifferentThan array

また、indexOf私は Internet Explorer 8 を使用しているため、この方法は使用できません。

4

2 に答える 2

1
var numbers = [ 1, 2, 3, 4, 5 ];
var exclude = [ 3, 4 ];
var filtered = [];
for (var i = 0; i < numbers.length; i += 1) {
    if (exclude.indexOf(numbers[i]) === -1) {
        filtered.push(numbers[i]);
    }
}
var rand = Math.floor(Math.random() * filtered.length);
var num = filtered[rand]; // 1, 2 or 5

許可された番号のリストを作成し、それらの 1 つをランダムに選択します。for ループは、次のように数値と除外の間の単なる差分です。var filtered = numbers.diff(exclude);

于 2013-10-18T14:02:48.467 に答える