Reputation: 9221
I have 3 images. 1.jpg, 2.jpg, 3.jpg. I want to distribute them into three img
elements randomly (on window refresh, the three images' positions will change).
How do I use Math.random()
here? Thanks.
<img src='' id='img1' />
<img src='' id='img2' />
<img src='' id='img3' />
Upvotes: 0
Views: 1619
Reputation: 12156
Math.floor(Math.random()*3)+1;
But distribution won't be uniform.
Upvotes: 1
Reputation: 700562
There are six different ways that the images can be put in the tags. Pick one of them using random:
var index = Math.floor(Math.random()*6);
var ids = [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]][index];
document.getElementById('img'+ids[0]).src = '1.jpg';
document.getElementById('img'+ids[1]).src = '2.jpg';
document.getElementById('img'+ids[2]).src = '3.jpg';
Upvotes: 2
Reputation: 12140
You can shuffle an array you create:
var arr = ["1.jpg", "2.jpg", "3.jpg"];
arr.sort(function() {return 0.5 - Math.random()});
Some people prefer other ways of shuffling, but a shuffling method would work to ensure you get all of the elements only once in your resulting array.
Upvotes: 3