基本的に、私はグリッドを作成し、その上にポイントをプロットしています.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 を使用しているため、この方法は使用できません。