简体   繁体   中英

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.

Now I want that when it outputs, eg the F2 shouldn't be next to F nor F' . Same goes for the other. D shouldn't be near to D2 or D' .

It should output eg: R B2 UFLF D2 .... and so on.

and not: 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.

Javascript

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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