In this coding challenge, I am attempting to populate a 2D array using a while loop. However, I want the loop to stop pushing values into the array when the first column contains three different unique values.
The initial code looks like this:
var maxunique;
var i = 0;
while (countunique(arr) != maxunique) {
// code that adds data to the array
arr[i].push(RandomNumber(1,8));
arr[i].push(i+1);
i++;
}
function countunique(arr)
{
// function implementation here
}
function RandomNumber(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
This code currently returns the following array:
arr: [ [ 4, 1 ],
[ 7, 2 ],
[ 5, 3 ],
[ 5, 4 ],
[ 3, 5 ],
[ 1, 6 ],
[ 7, 7 ],
[ 8, 8 ],
[ 5, 9 ],
[ 5, 10 ] ]
The desired result should be:
arr: [ [ 4, 1 ],
[ 7, 2 ],
[ 5, 3 ] ]
In this case, the process stops after the third pair is added to the array, as it already contains three unique values in the first column.
I am unsure of how to modify the code to achieve this and whether a while or for loop would be more appropriate. Any suggestions?