Random pictures on JS?

There is a code which generates random images:

sha = Math.floor(Math.random() * 2); 
imagez = ('<img src="img/'+sha+'.png" border="0" />');
document.getElementById("imaaaga").innerHTML = imagez;3
document.getElementById("imaaaga2").innerHTML = imagez;


How to make so that in html:

the <div>
 <div id="imaaaga"></div>
 <div id="imaaaga2"></div>
</div>


They were varied in each div'e in different ways, and it turns out that the same pictures again.

RfdAE.png
March 23rd 20 at 18:51
3 answers
March 23rd 20 at 18:53
Solution
sha = function(){
return Math.floor(Math.random() * 2); 
}


well and, accordingly,
document.getElementById("imaaaga").innerHTML = '<img src="img/'+sha()+'.png" border="0" />';
document.getElementById("imaaaga2").innerHTML = '<img src="img/'+sha()+'.png" border="0" />';
March 23rd 20 at 18:55
Solution
function getImage() {
 const random = Math.floor(Math.random() * 2); 
 return '<img src="img/'+random+'.png" border="0" />';
}

document.getElementById("imaaaga").innerHTML = getImage();
document.getElementById("imaaaga2").innerHTML = getImage();
has not eliminated conflict is that both times fall out of one and the same. The probability is 1/3 - Roberta.Schowalter commented on March 23rd 20 at 18:58
Well, I guess it does not matter if there are a couple of times, pictures will eventually be more. - emili commented on March 23rd 20 at 19:01
March 23rd 20 at 18:57
Solution
In this task, it would be nice to generate random numbers without repetition as long as possible. To exhaust the sequence 0..n, randomly pulling out this "deck" a card. When the deck is empty, open a new one.

Can be something like make a function that will pull from the deck a card at random, and another function to generate it for the picture:
// Iterator is random, unique - Random Unique
getRUIterator function(max) {
 let buffer = [];

 const ruIterator = {
 next: function() {
 if (buffer.length === 0) { // if the deck is empty
 for (let i = 0; i < max; i++) buffer.push(i); // open new 0..max
}

 const index = Math.floor(Math.random() * buffer.length);
 return buffer.splice(index, 1)[0]; // remove from the deck a card at random
}
}

 return ruIterator;
}

/**
 * generum in each div a random picture
 * as long as possible without repeats
 * @param int iTotal number of available pictures
 * @param Array an array of strings - idiski div's where to insert
*/
placeRandomImages function(iTotal, aDivs) { 
 function placeImage(n, id) {
 const img = new Image();
 img.src = `img/${n}.png`;
 img.border = '0';
document.getElementById(id).appendChild(img);
}

 // will generate random non-repeating
 const RUI = getRUIterator(iTotal);

 for (let i = 0; i < aDivs.length) {
 placeImage( RUI(), aDivs[i]);
}
}

placeRandomImages(2, ["imaaaga", "imaaaga2"]);

Find more questions by tags HTMLJavaScript