0

i was trying to generate random numbers to pick random items from array to update collage of pictures, i noticed that sometimes generated number is same to a previously generated number causing one picture to update 2-3 times so to check this i thought it would be great if i store last generated random number into an variable and make a function that checks if last generated value is equal to current generated value, it continue to generate numbers till a non-equal value is generated.

it is working fine until i wanted multiple instances ... as variable that stores last value is same, i am getting same numbers.

var bgs = document.getElementById('collage').getElementsByClassName('bg');
var images = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var lv = null;
function get_random(length) {
    arr = [];
    while (arr.length < 1) {
        var cv = Math.floor(Math.random() * length);
        if (lv === cv) {
            arr = [];
            continue;
        }
        else if (lv !== cv) {
            arr.push(cv);
            break;
        }
    }
    lv = arr[0];
    return arr[0];
}

function update_collage() {
    var img = images[get_random(images.length)];
    var target = bgs[get_random(bgs.length)];
    target.style.background = "url('assets/img/thumbs/" + img + ".jpg') no-repeat center";
    target.style.backgroundSize = "cover";
}
window.setInterval(function(){
    update_collage();
}, 1200);

how can i correct this, how can i create multiple instances of function or variable

  • You seem to want something slightly different then this... look at RobG's answer here: http://stackoverflow.com/questions/6625551/math-random-number-without-repeating-a-previous-number. Note, he isn't the top answer, but I think he is answering what you want. – Brian Apr 30 '17 at 10:30
  • What do you mean by multiple instances? You want have multiple collages on a page? – yezzz Apr 30 '17 at 10:32
  • http://stackoverflow.com/a/43687389/6647153 – ibrahim mahrir Apr 30 '17 at 10:41

1 Answers1

0

I suggest using a generator function and instantiating it as often as you need:

// Generate pairwise unique random numbers < max:  
function* generate_random(max) {
  let prev;
  while (true) {
    let next = Math.floor(Math.random() * max);
    if (prev === next) continue;
    yield prev = next;
  }
}

// Example:
let generators = [generate_random(3), generate_random(3)];

for (let i = 0; i < 10; ++i) {
  // Both generators run independently:
  console.log(generators[0].next().value, generators[1].next().value);
}

In your code, you could e.g. replace

var img = images[get_random(images.length)];
var target = bgs[get_random(bgs.length)];

with

var img = images[generators[0].next().value];
var target = bgs[generators[1].next().value];

where

var generators = [generate_random(images.length), generate_random(bgs.length)];
le_m
  • 19,302
  • 9
  • 64
  • 74