Random Images
StackOverflow question http://stackoverflow.com/questions/10905287/a-script-that-loads-an-image-at-random-from-an-array-without-repeating-any-until/10905896#comment14361827_10905896
by Hans PUFAL
HTML
<html>
<head>
</head>
<body>
<table cellpadding="0" cellspacing="0" border="0" height="100%" width="100%">
<tr valign="middle">
<td align="center">
StackOverflow question :
<a href="http://stackoverflow.com/questions/10905287">
A script that loads an image at random from an array without repeating any
</a>
<br>For further help contact me at [email protected]
</td>
</tr>
<tr valign="middle">
<td align="center">
<a id="imglink" href="set-prototype.html"></a>
</td>
</tr>
</table>
</body>
<script>
var xoxo = [
"images/01.jpg",
"images/02.jpg",
"images/03.jpg",
"images/04.jpg",
"images/05.jpg",
"images/06.jpg",
"images/07.jpg",
"images/08.jpg",
"images/09.jpg",
"images/10.jpg"],
choice = (new Set(xoxo.length, 'imgset')).or (),
link = document.getElementById ('imglink'),
img = document.createElement ('img');
img.alt = img.src = xoxo[choice];
link.appendChild (img);
//* Debug :
{
var seq = (new Set (xoxo.length, 'imgset')).count () === 1 ? [] :
(document.cookie.match (/sequence=([^;]+)/) || ['', ''])[1].split (',');
seq.push (choice);
document.cookie = 'sequence=' + seq.join (',') + '; path=/';
link.parentNode.innerHTML += '<br>' + seq.join (',') + ' ' + xoxo[choice];
} // End debug */
</script>
</html>
JavaScript
/* <!--
Note when inserting this into the HTML, add it in <script> tags in the head.
-->*/
"use strict";
function Set(len, init) {
if (typeof init === 'string') { // fetch cookie
this.cookie = init;
if (init = (document.cookie.match(RegExp(init + '=([^;]+)')) || ['', ''])[1]) {
init = init.split(',');
}
}
// Establish an array of sufficient 50 bit numbers to hold len bits
this.bits = new Array(Math.floor((len + 49) / 50));
this.len = len;
// Clear all numbers
for (var i = this.bits.length; i--;) {
this.bits[i] = init ? +(init[i] || 0) : 0;
}
}
Set.prototype.count = function () { // Return count of bits set
for (var count = 0, n = this.len; n--;)
count += +this.check (n);
return count;
}
Set.prototype.check = function(n) {
// Return value (0 or 1) of bit n of the set
if (n >= 0 && n < this.len) {
var m = n % 50;
return Math.floor(this.bits[(n - m) / 50] / Math.pow(2, m)) & 1;
}
return 0;
}
Set.prototype.or = function(n) {
if (arguments.length === 0) { // set a random bit
if (this.count () === this.len) {
for (var i = this.bits.length; i--;) {
this.bits[i] = 0;
}
}
while (this.check(n = Math.floor(Math.random() * this.len)));
}
// Set bit n of the set to 1 (unless it is already 1)
if (n >= 0 && n < this.len && !this.check(n)) {
var m = n % 50;
this.bits[(n - m) / 50] += Math.pow(2, m);
if (this.cookie) {
document.cookie = this.cookie + '=' + this.bits.join(',') + '; path=/';
}
return n;
}
return -1;
}