Search code examples
javascriptarraysshufflecharat

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, e.g. 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 e.g.: R B2 U F L F D2 .... and so on.

and not: R B2 B' L F 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);

Solution

  • 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)
    }