0

Now, let it be known I've looked all over and I've been unable to find an answer to the specific problem I've got. I'm very new with JS and I've been trying to teach myself, so I'm probably making a very basic, "noob" mistake.

So apologies in advance.

I'm trying to make a "random generator" of sorts, basically pulling two words from a given list and I'm not quite sure how to avoid duplicate results from appearing.

I suppose I'm doing something wrong in the following code:

var randomDiv = document.getElementById("myRandomDiv");

document.getElementById("myButton").addEventListener("click", function() {
      randomIndex = Math.ceil((Math.random()*randomStrings.length-1));
      randomIndex2 = Math.ceil((Math.random()*randomStrings.length-1));
      newText = randomStrings[randomIndex]+" + ";
      newText2 = randomStrings[randomIndex2];
      randomDiv.innerHTML = newText+newText2;
Roy
  • 1
  • 1
  • 3
  • 1
    How about a `while` loop untill `unique` is found! – Rayon Apr 25 '16 at 05:11
  • Another option is to shuffle the array, then just take the first 2 items: http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – Evan Trimboli Apr 25 '16 at 05:29

2 Answers2

0

You need to keep fetching randomIndex2 till you get a different value

Replace

randomIndex2 = Math.ceil((Math.random()*randomStrings.length-1));

with

randomIndex2 = Math.ceil((Math.random()*randomStrings.length-1));
while( randomIndex == randomIndex2 )
{
   randomIndex2 = Math.ceil((Math.random()*randomStrings.length-1));
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

You can add something like this to your code to avoid duplication:

while(randomIndex === randomIndex2 && randomStrings.length > 1) {
   randomIndex2 = Math.ceil((Math.random()*randomStrings.length-1));
}

right after your assignment for randomIndex and randomIndex2.

In the event you only have one string, the randomStrings.length > 1 will make sure that you won't get stuck in an infinite loop.

timolawl
  • 5,434
  • 13
  • 29