I have an array of arrays and I need to pick 2 random and different combinaisions of (index1, index2)
Let me give an example
data = [["a", "b", "c", "d"], ["e", "g"], ["i", "j", "k"]]
I need to have (index1: 0 , index2: 2) and (index1: 2 , index2: 1)
How can I achieve that efficiently ?
First you can create one combination:
const i11 = Math.floor(Math.random() * data.length);
const i12 = Math.floor(Math.random() * data[i11].length);
Then you can check if the inner array has only one element. If it has only one element and it's the first combination, you should ignore it in the following steps:
const dataLength = data[i11].length > 1 ? data.length : data.length - 1;
Now you can generate the outer index for the second combination and adjust it:
let i21 = Math.floor(Math.random() * dataLength);
if (i21 >= i11 && data[i11].length === 1) ++i21;
Next you can check if the outer index of the first combination and the outer index of the second combination are the same and do the same adjustment to avoid duplicates:
const innerDataLength = i21 === i11 ? data[i21].length - 1 : data[i21].length;
Finally you can generate the second inner index and adjust it
let i22 = Math.floor(Math.random() * innerDataLength);
if (i21 === i11 && i22 >= i12) ++i22;
The whole code as a function with a test:
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!');
}