I have a 2D matrix, here's an example data = [["a", "b", "c", "d"], ["e", "g"], ["i", "j", "k"]]
I need to get N random (x, y) indexes without duplicates.
I already asked a different question same context and this is the solution to pick 2 x, y combos
const data = [["a", "b", "c", "d"], ["e", "g"], ["i", "j", "k"]];
function combinations(data) {
const i11 = Math.floor(Math.random() * data.length);
const i12 = Math.floor(Math.random() * data[i11].length);
const dataLength = data[i11].length > 1 ? data.length : data.length - 1;
let i21 = Math.floor(Math.random() * dataLength);
if (i21 >= i11 && data[i11].length === 1) ++i21;
const innerDataLength = i21 === i11 ? data[i21].length - 1 : data[i21].length;
let i22 = Math.floor(Math.random() * innerDataLength);
if (i21 === i11 && i22 >= i12) ++i22;
return [[i11, i12], [i21, i22]];
}
console.log(combinations(data));
for (let i = 0; i < 10000; ++i) {
const [[i11, i12], [i21, i22]] = combinations(data);
if (i11 === i21 && i12 == i22) console.log('Test failed!');
}
Aucun commentaire:
Enregistrer un commentaire