0

I'm doing a website project for college and I want to display three pictures on website. There are 10 pictures stored in my folder (all named "slika 1 to 10" and the script has three variables, all of them randomly generate a number between 1 and 10 and then shows a picture "slika"+randomNumber.

How can I check if all three variables are different so that those three pictures are always different whenever I refresh the website.

JS code:

window.onload=odaberiSliku;

var broj1=Math.floor(Math.random() * 10) +1;
var broj2=Math.floor(Math.random() * 10) +1;
var broj3=Math.floor(Math.random() * 10) +1;

    function odaberiSliku() {
        document.getElementById("slika1").src = "slike/randomslike/slika"+broj1+".jpg";
        document.getElementById("slika2").src = "slike/randomslike/slika"+broj2+".jpg";
        document.getElementById("slika3").src = "slike/randomslike/slika"+broj3+".jpg";
    }

In case anyone wonders, the variable names are in croatian.

Bernard Polman
  • 795
  • 2
  • 14
  • 31

2 Answers2

2

While Lux's answer is perfectly fine, it is not scalable if you are (1) generating a dynamic list of n length and/or (2) if the list gets really big.

There is a simpler method to achieve what you're intending to do. You're basically trying to generate random numbers that are unique—this is akin to generating a unique array of incremental numbers and shuffling them.

Instead of going through the trial-and-error method of testing each randomly generated numbers against a pre-existing list, I believe this approach will serve you better.

All you need is to:

  1. generate a simple array, say from 1–10 (the upper limit should correspond to the number of images you have),
  2. shuffle it,
  3. take the first 3 elements in shuffled array
  4. iterate through the sliced array
  5. concatenate each number to a URL template
  6. assign it to your element of choice

A proof-of-concept code is as follow:

var imageCount = 10,
    arr = new Array(imageCount).join().split(',').map(function(item, index) {
        return ++index;
    }),
    shuffle = function(a) {
        var j, x, i;
        for (i = a.length; i; i -= 1) {
            j = Math.floor(Math.random() * i);
            x = a[i - 1];
            a[i - 1] = a[j];
            a[j] = x;
        }
    };

// Shuffle the array
shuffle(arr);

// Get first 3 elements
var sliced = arr.slice(0, 3);

// Iterate through first 3 elements, and assign image source
for (var i = 0; i < sliced.length; i++) {
  document.getElementById("slika" + i).src = "slike/randomslike/slika" + sliced[i] + ".jpg";
}
Community
  • 1
  • 1
Terry
  • 63,248
  • 15
  • 96
  • 118
1

Well just check it after you generated your variables:

while(broj2 == broj1) {
  broj2=Math.floor(Math.random() * 10) +1;)
}

while(broj3 == broj2 || broj3 == broj1) {
  broj3=Math.floor(Math.random() * 10) +1;)
}
Lux
  • 17,835
  • 5
  • 43
  • 73