I'm trying to create a function that accomplish the following purpose:
In plain words, I want a function that takes n arguments, each argument (three arguments in the above example, each array has a different colour) being an array with the same length = m. I want the function to return an array with a length = n, and each item would be an array with a length = m.
The problem for now is that I splice
the array I take randomly an item from, so it messes up the length of the array and only returns half the data expected. I could potentially replace the value I splice with "-1" for example and verify each random item I choose but that seems like a dirty way of getting things done.
//Generates an array of n items randomly taken from m arrays given as arguments where arrays length equal n.
function arrayDistributor(...args) {
try {
//Copying the array of arguments
let arg = args.slice();
//Verification to see if an argument is an array of different length than the others
for (let i = 0; i < arg.length; ++i) {
//Appliying the verification if it's not the last array item
if (i !== (arg.length - 1)) {
//Actual verification
if (arg[i].length !== arg[i + 1].length) {
throw "An argument doesn't have the same length as others.";
}
}
}
let r = [];
//Looping through the first argument
for (let i = 0; i < (arg[0].length); ++i) {
let arr = [];
//Looping through all the arguments
for (let j = 0; j < arg.length; ++j) {
//Selecting a random index in the j argument
let k = getRandomInt(0, (arg[j].length - 1));
//Pushing the item inside the new array
arr.push(arg[j][k]);
//Removing the item from the initial array !problem here
arg[j].splice(k, 1);
}
//Pushing the array to the result array
r.push(arr);
}
return r;
} catch (e) {
console.log(e);
}
};
//Return a random integer between an inclusive interval
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}