0

I have an Array which I am randomizing:

var imgArray = [1, 2, 3, 4, 5],
    i = imgArray[Math.floor(Math.random()*imgArray.length)];

However, due to the fact there are only 5 numbers, I'm getting a lot of duplicates.

For example: my outputs are often similar to 1, 4, 5, 5, 5, 3, 2, 2... And so on...

How can I prevent the "random" number from being the same as the previous number?

Any help is massively appreciated, thanks!!

Nick
  • 3
  • 1
  • 1) store the previous number in a variable 2) check if the new number is the same as the previous number 3) if it is, choose another number and goto 2 – JJJ May 28 '15 at 07:36
  • do you want to get the five initial numbers randomized, – maioman May 28 '15 at 07:39
  • or 5 picks of the array (posted once if it gets duplicate) ; so you might end up with an array with less than 5 elements? – maioman May 28 '15 at 07:40
  • I'm a little out of my depth here - This is what I'm trying to achieve: http://jsfiddle.net/bzoyc64m/4/ - Once the image has flipped, I don't want it to be able to flip back straight away. In this example there are only 3 things in the array – Nick May 28 '15 at 07:42
  • Maybe you can just shuffle the array? See for example http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – ebo May 28 '15 at 07:44

2 Answers2

1

Just like @Juhana said, below is the code:

var arr = [1, 2, 3, 4, 5];
var limit = 10;
var last_value = 0;
var rand = 0;
for(i=0; i < limit; i++) {
  while(rand === last_value) {
    rand = arr[Math.floor(Math.random()*arr.length)];
  }
  last_value = rand;
  $("div").append(rand);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>Result: </div>
Yuri Predborski
  • 186
  • 1
  • 1
  • 12
Bla...
  • 7,228
  • 7
  • 27
  • 46
0
var imgArray = [1, 2, 3, 4, 5]
while(imgArray .length < 10){
  var randomnumber=Math.floor(Math.random()*imgArray .length)
  var found=false;
  for(var i=0;i<imgArray .length;i++){
    if(imgArray [i]==randomnumber){found=true;break}
  }
  if(!found)imgArray [imgArray .length]=randomnumber;
}
document.write(imgArray);
Vaibs_Cool
  • 6,126
  • 5
  • 28
  • 61