JSFiddle - React, Tailwind, and code Playground
draw random array element, but not from last x picked elements
by CBroe
JavaScript
var colors = ['red', 'blue', 'yellow', 'green', 'black', 'orange', 'lime', 'gray', 'purple'];
Array.prototype.randNotFromLastX = function (x) {
var l = this.length-1,
m = Math.min(++this.randNotFromLastX_runcount, x),
pick = rand(0,l-m),
r = this[pick];
// switch picked with element from near end of array
this[pick] = this.splice(-m, 1)[0];
// added picked element to end of array
this.push(r);
//console.log(m, this.randNotFromLastX_runcount, pick, r, this[pick], this.join());
// return last element, which is this rounds random pick
return this[l];
}
Array.prototype.randNotFromLastX_runcount = 0; // Array.prototype.randNotFromLastX.runcount does not work, when used on multiple arrays
for(var i=0; i<1000; ++i) {
var d = document.createElement('div');
d.style.height = '1em';
d.style.background = colors.randNotFromLastX(3);
document.body.appendChild(d);
}
var x = [1,2,3,4,5]
x.randNotFromLastX(5);
x.randNotFromLastX(5);
x.randNotFromLastX(5);
x.randNotFromLastX(5);
x.randNotFromLastX(5);
x.randNotFromLastX(5);
x.randNotFromLastX(5);
x.randNotFromLastX(5);
x.randNotFromLastX(5);
x.randNotFromLastX(5);
function rand (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}