Can't seem to find an answer to this, say I have this:
setInterval(function() {
m = Math.floor(Math.random()*7);
$('.foo:nth-of-type('+m+')').fadeIn(300);
}, 300);
How do I make it so that random number doesn't repeat itself. For example if the random number is 2, I don't want 2 to come out again.
could you try that,
There are a number of ways you could achieve this.
Solution A: If the range of numbers isn't large (let's say less than 10), you could just keep track of the numbers you've already generated. Then if you generate a duplicate, discard it and generate another number.
Solution B: Pre-generate the random numbers, store them into an array and then go through the array. You could accomplish this by taking the numbers
1,2,...,n
and then shuffle them.Solution C: Keep track of the numbers available in an array. Randomly pick a number. Remove number from said array.
you can do this. Have a public array of keys that you have used and check against them with this function:
(function from: javascript function inArray)
So what you can do is:
This code will get stuck after getting all seven numbers so you need to make sure it exists after it fins them all.
I like Neal's answer although this is begging for some recursion. Here it is in java, you'll still get the general idea. Note that you'll hit an infinite loop if you pull out more numbers than MAX, I could have fixed that but left it as is for clarity.
edit: saw neal added a while loop so that works great.
not sure if its too late, but would still like to add--
this basically uses timestamp (every millisecond) to always generate a unique number.
Here's a simple fix, if a little rudimentary:
If the next number is the same as the last simply minus 1 unless the number is 0 (zero) and set it to any other number within your set (I chose 7, the highest index).
I used this method within the cycle function because the only stipulation on selecting a number was that is musn't be the same as the last one.
Not the most elegant or technically gifted solution, but it works :)