I am using the below code to assign a random class (out of five) to each individual image on my page.
$(this).addClass('color-' + (Math.floor(Math.random() * 5) + 1));
It's working great but I want to make it so that there are never two of the same class in a row.
Even better would be if there were never two of the same in a row, and it also did not use any class more than once until all 5 had been used... As in, remove each used class from the array until all of them have been used, then start again, not allowing the last of the previous 5 and the first of the next 5 to be the same color.
Hope that makes sense, and thanks in advance for any help.
You can do something like this using an array and the splice method:
Just to explain my comment to jfriend00's excellent answer, you can have a function that returns the members of a set in random order until all have been returned, then starts again, e.g.:
If the list can be hard coded, you can keep the original in a closure, e.g.
You need to create an array of the possible values and each time you retrieve a random index from the array to use one of the values, you remove it from the array.
Here's a general purpose random function that will not repeat until all values have been used. You can call this and then just add this index onto the end of your class name.
Working demo: http://jsfiddle.net/jfriend00/H9bLH/
So, your code would just be this:
Here's an object oriented form that will allow more than one of these to be used in different places in your app:
Sample Usage:
Working demo: http://jsfiddle.net/jfriend00/q36Lk4hk/