简体   繁体   English

JavaScript数组随机播放不应彼此相邻输出两个

[英]Javascript array shuffle shouldn't output two next to eachother

I got an array which is filled with some letters. 我得到了一个充满一些字母的数组。 See example below. 请参见下面的示例。 First I want the array is getting shuffled. 首先,我想让阵列变得混乱。 Well I found the most famous shuffle for it called the Fisher-Yates shuffle. 好吧,我发现了最著名的混排,称为Fisher-Yates混排。

Now I want that when it outputs, eg the F2 shouldn't be next to F nor F' . 现在,我希望在输出时,例如F2不应紧邻FF' Same goes for the other. 其他也一样。 D shouldn't be near to D2 or D' . D不应靠近D2D'

It should output eg: R B2 UFLF D2 .... and so on. 它应该输出例如:R B2 UFLF D2 ....依此类推。

and not: R B2 B' LF D2 ... 而不是:R B2 B'LF D2 ...

Any help, suggestions? 任何帮助,建议吗? I know I should check the first chars with charAt() but I'm not an expert in that function. 我知道我应该使用charAt()检查第一个字符,但我不是该函数的专家。

Javascript Java脚本

function shuffle(sides) {
    var elementsRemaining = sides.length, temp, randomIndex, last;
    while (elementsRemaining > 1) {
        randomIndex = Math.floor(Math.random() * elementsRemaining--);
        if (randomIndex != elementsRemaining) {
        temp = sides[elementsRemaining];
        sides[elementsRemaining] = sides[randomIndex];
        sides[randomIndex] = temp;
        }
    };
}

  return sides;
}

var sides = ["F ", "R ", "U ", "L ", "D ", "F2 ", "R2 ", "U2 ", "L2 ", "D2 ", "F' ", "R' ", "U' ", "L' ", "D' "];
shuffle(sides);
$('#scramble').html(sides);

You can shuffle, check your constraint and repeat if constraint not met. 您可以随机播放,检查约束,如果不满足约束,则重复。 Your method for checking constraint can be 您检查约束的方法可以是

var passesConstraint = function(sides) {
    for(var i = 0; i < sides.length - 1; i++) { 
        if (sides[i][0] === sides[i+1][0]) { 
            return false;
        }
     } 
    return true;
}

You need not do charAt(), strings can be accessed by [] notation too. 您无需执行charAt(),字符串也可以通过[]表示法进行访问。

shuffle(sides)
while (!passesConstraint(sides)) {
   shuffle(sides)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM