I have an array which contains number from 0 to 20 .
var array1 = [0,1,2,.....18,19,20];
I want to make three arrays and each array will contain seven random and unique numbers from array1
How can I do this with JavaScript ?
Example:
[2,9,6,13,5,17,20]
[3,18,7,12,15,1,4]
[8,10,14,16,11,0,19]
CodePudding user response:
var array1 = [0,1,2,.....18,19,20];
var array2 = [];
var array3 = [];
var array4 = [];
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) min);
};
for (let i = 0; i < 7; i ) {
array3.push(getRandomInt(array1[0], array1[array1.length])
array4.push(getRandomInt(array1[0], array1[array1.length])
array5.push(getRandomInt(array1[0], array1[array1.length])
};
CodePudding user response:
Created an array method array.random
in which if you want to limit the length by pass an intger value as a parameter.
If parameter is not passed by default complete length is returned
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Array.prototype.random = function(t) {
if (!t) {
t = this.length;
}
let copy = this.slice()
copy.sort(() => 0.5 - Math.random());
return copy.slice(0, t)
}
console.log(array.random(10))
console.log(array.random())
CodePudding user response:
Define a getRandomNumbers
function that gets len
random number from the array and remove them from the array. Use that as many times as you want to split your array into multiple pieces of random numbers!
function getRandomNumbers(array, len) {
let output = [];
for (let i = 0; i < len; i ) {
let rnd = Math.floor(Math.random() * array.length)
output.push(array.splice(rnd, 1))
}
return output;
}
let myArray = [];
for(let i = 0; i < 21; i ) myArray.push(i 1)
console.log(
getRandomNumbers(myArray, 7)
)
console.log(
getRandomNumbers(myArray, 7)
)
console.log(
getRandomNumbers(myArray, 7)
)
CodePudding user response:
var data = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
let usedIndexes = [];
const arr1 = [];
const arr2 = [];
const arr3 = [];
for(let i=0; i<7;i ){
arr1.push(data[getRamdomIndex(data)]);
arr2.push(data[getRamdomIndex(data)]);
arr3.push(data[getRamdomIndex(data)]);
}
console.log(arr1);
console.log(arr2);
console.log(arr3);
function getRamdomIndex(arr) {
let index = 0;
// while generated index is already used
do{
index = Math.floor(Math.random() * arr.length);
}while(usedIndexes.includes(index));
usedIndexes.push(index);
return index;
}