0

the list imgsource is for generating 6 random image sources(num1 and fsnum1 are random integer and string respectively). I need these 6 image sources to be different from each other everytime.But sometimes same image source are produced. I can't figure it out!

var imgsource = ["images/"+num1+" "+fsnum1+".png",
                 "images/"+num2+" "+fsnum2+".png",
                 "images/"+num3+" "+fsnum3+".png",
                 "images/"+num4+" "+fsnum4+".png",
                 "images/"+num5+" "+fsnum5+".png",
                 "images/"+num6+" "+fsnum6+".png"]


document.querySelectorAll("img")[0].setAttribute("src",imgsource[0]);
document.querySelectorAll("img")[1].setAttribute("src",imgsource[1]);
document.querySelectorAll("img")[2].setAttribute("src",imgsource[2]);
document.querySelectorAll("img")[3].setAttribute("src",imgsource[3]);
document.querySelectorAll("img")[4].setAttribute("src",imgsource[4]);
document.querySelectorAll("img")[5].setAttribute("src",imgsource[5]);
Samip Poudel
  • 16
  • 1
  • 2
  • How are you generating `num*` & `fsnum*` here? – palaѕн Apr 18 '20 at 14:36
  • is there any error? – Fahad Mahmood Apr 18 '20 at 14:38
  • try to generate a random number like this. (for example number between 0,9, max would be 9, and min would be 0) Math.floor(Math.random() * (max - min + 1)) + min; – Fahad Mahmood Apr 18 '20 at 14:40
  • make sure the actual image exists for that name. – Fahad Mahmood Apr 18 '20 at 14:40
  • It depends on how truly random they need to be. – Aluan Haddad Apr 18 '20 at 14:44
  • We really need a lot more detail from the original poster. See questions above. One useful algorithm that seems to match what you are reporting: start with array of n elements; generate random number in the range 0-n-1, use that item however you're going to use it; remove that item from the array, and repeat till done. OR - you could sort it in random order [aka 'shuffle' the array] (as shown in this answer https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) and then use the results as is. –  Apr 18 '20 at 15:15

1 Answers1

0

the simplest solution would be to check for duplicates after generating num and fsnum ,but that means you have a weak random number generator for whatever reasons !!

ezio
  • 359
  • 2
  • 13