Reputation: 103
I am trying to generate a unique random number from 0-11 and use it an index to assign TextBox some unique characters. Here is the code
int[] previous_random = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};//initialized with invalid values
int current_random;
Random r_int = new Random();
boolean match = false;
for (int n=0;n<=11;n++)
{
gb[n] = (TextView)findViewById(IDs[n]);//assigning IDs from XML to java text boxes
}
int i = 0;
while (i<=11)
{
current_random = r_int.nextInt(11);//generating a random int from 0-11
int j =0;
while (j<=11)
{
if (current_random == previous_random[j])
{
match = true;break;//match = true shows that this random was used before to skip the loop
}
j++;
}
if(match == false)
{
gb[i].setText(randomized_final.charAt(current_random) + "\0");//randomized_final is a string not visible in current code
previous_random[i] = current_random;//*******PROBLEM HERE************
}
else
continue;
i++;
}
}
Now problem is the part that is labelled with **PROBLEM HERE** causes the program to stop responding and causes CPU usage for that app to go over 50% but app doesn't crash, it just shows blank screen with top bar.That part is supposed to store the new unique random and store is for later comparisons and If I remove this part then code works fine except that I get repeated randoms(which is not what I want).
Kindly tell me what I am doing wrong. Or tell any alternative method to do it. I have tried it with for loops too. Have tried many alternative methods for hours!
Upvotes: 1
Views: 448
Reputation: 4252
I've seen this kind of problem used as an interview question. a possible solution is as follows:
1) create a Collection (List maybe?) of ints containing the numbers 0-11
2) shuffle that list.
3) each time you want a new unique number, return the next element in the list.
in code it would look something like:
ArrayList<Integer> list = new ArrayList();
for(int i=0;i<=11;i++){
list.add(i);
}
Collections.shuffle(list);
Upvotes: 2