Answer the question
In order to leave comments, you need to log in
JS(jQuery) How to get a random element of an array without repeating?
We need a function that returns the value of a random array element, but not a repeating one.
For example, there is an array
var RGBColorsArr = ['rgb(255,255,0)', 'rgb(255,0,0)', 'rgb(51,0,0)', 'rgb(255,0,102)', 'rgb(0,0,51)', 'rgb(0,0,255)', 'rgb(102,0,255)', 'rgb(0,255,255)', 'rgb(51,51,0)', 'rgb(0,0,0)', 'rgb(0,255,0)', 'rgb(0,51,0)'];
var getRandomArrIndex = Math.floor( (Math.random() * RGBColorsArr.length) + 0);
var getColor = RGBColorsArr[getRandomArrIndex];
Answer the question
In order to leave comments, you need to log in
In general, you can generate a random permutation for a set of N elements (12 in your case):
let getRandomPermutation = (n) => {
let arr = Array.from(Array(n).keys());
for (let i = (n - 1); i > 0; i--) {
let j = Math.floor(Math.random() * i);
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
let permutation = getRandomPermutation(colors.length);
let temp = colors.slice();
for (let i = 0; i < colors.length; i++) {
colors[i] = temp[permutation[i]];
}
var randomColor = {
list: [
'rgb(255,255,0)',
'rgb(255,0,0)',
'rgb(0,255,0)',
'rgb(0,51,0)'
],
already: [],
random: function () {
return this.list[Math.floor(Math.random() * this.list.length)];
},
get: function () {
var color = this.random();
if (this.already.length >= this.list.length) {
this.already = [];
return color;
}
if (this.already.indexOf(color) !== -1) {
return this.get();
} else {
this.already.push(color);
return color;
}
}
};
A peculiar solution, of course, to make the main blocks even relative without the need) And in the adaptive, change everything pixel by pixel?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question