比较javascript数组中的值,并确保每个值之间至少相隔10

比较javascript数组中的值,并确保每个值之间至少相隔10,javascript,Javascript,以下数组包含子数组(每个子数组是HTML5画布上的一对坐标): 如何比较每对坐标并确保每个值之间至少相隔10 例如: 将数字272(从索引为1的数组)与数字273(从索引为4的数组)进行比较-因为只有1个相隔,所以将10添加到一个值 以下是我尝试过的: 在这里,我随机生成数字,但我可以只关联最后生成的一对 function crosses(){ var crossx, crossy, oldCrossx, oldCrossy, col; for(var i=0; i<=10

以下数组包含子数组(每个子数组是HTML5画布上的一对坐标):

如何比较每对坐标并确保每个值之间至少相隔10

例如: 将数字272(从索引为1的数组)与数字273(从索引为4的数组)进行比较-因为只有1个相隔,所以将10添加到一个值

以下是我尝试过的:

在这里,我随机生成数字,但我可以只关联最后生成的一对

function crosses(){
    var crossx, crossy, oldCrossx, oldCrossy, col;
    for(var i=0; i<=10; i++){

    crossx = randomFromInterval(100, xw-100);
    crossy = randomFromInterval(100, xh-100);


    if(crossesPos.length > 0){
        oldCrossx = crossesPos[i-1][0];
        oldCrossy = crossesPos[i-1][1];
        if(crossx - oldCrossx < 20){
            crossx += 10;
        }
        if(crossx - oldCrossx < -20 ){
            crossx -= 10;
        }
        if(crossy - oldCrossy < 20){
            crossy += 10;
        }
        if(crossy - oldCrossy < -20 ){
            crossy -= 10;
        }
    }
}


当然,一秒钟就可以编辑问题了。比较一下。如果差异不大于10,请修改。将正确的[ed]值复制到新数组或替换原始数组中的值。此检查需要执行多少次?它可能会持续很长时间,这取决于
myArray
的大小。x和y对中的每一对都有最大数量吗?你确定通过适当的方法达到了你想要的目的吗?myArray将只有10个子数组。我编写的代码检查最后生成的每一对,并将其与前一对进行比较。但我意识到这不好,因为数字是随机生成的。所以我想在生成数组后对其进行排序,并尝试一个类似于Dave Newton建议的想法。请注意。。。外部数组中有11个元素,而不是10个。这不是OP所说的情况,也是最后一组数字不正确的原因。删除最后一组坐标,这将非常有效。
function crosses(){
    var crossx, crossy, oldCrossx, oldCrossy, col;
    for(var i=0; i<=10; i++){

    crossx = randomFromInterval(100, xw-100);
    crossy = randomFromInterval(100, xh-100);


    if(crossesPos.length > 0){
        oldCrossx = crossesPos[i-1][0];
        oldCrossy = crossesPos[i-1][1];
        if(crossx - oldCrossx < 20){
            crossx += 10;
        }
        if(crossx - oldCrossx < -20 ){
            crossx -= 10;
        }
        if(crossy - oldCrossy < 20){
            crossy += 10;
        }
        if(crossy - oldCrossy < -20 ){
            crossy -= 10;
        }
    }
}
function randomFromInterval(from,to){
        return Math.floor(Math.random()*(to-from+1)+from);
    }
var myArray = [
    [364, 124],
    [192, 272],
    [209, 217],
    [332, 227],
    [241, 273],
    [356, 387],
    [104, 185],
    [361, 380],
    [297, 390],
    [371, 311],
    [191, 293]
];

function distTen(element, index, array) {
    for (x = 0; x < 10; x++) {
        if (Math.abs(element[0] - array[x][0]) < 10) array[x][0] += 10;
        if (Math.abs(element[1] - array[x][1]) < 10) array[x][1] += 10;
    }
}

function logIt(element, index, array) {
    console.log("a[" + index + "] = " + element);
}
myArray.forEach(distTen);
myArray.forEach(logIt);
a[0] = 394,134
a[1] = 202,302
a[2] = 229,227
a[3] = 342,247
a[4] = 251,303
a[5] = 376,407
a[6] = 114,195
a[7] = 381,390
a[8] = 307,410
a[9] = 401,321
a[10] = 191,293