|
Hi
I have created an array of random numbers but I need to stop duplicate numbers being added to the array so I have added the boolean 'fresh'. however, I somehow need to tell my 'fresh' to only check the number of elements added to the array so far and I am embarrassed to say i can't figure this out as I am sure it is easy.
I have been searching books and the internet but just cannot figure it out.
Any help in the right direction would be really appreciated
my code is:
int amount = 7; // number of integers needed to generate
int[] nums = new int[amount];
int i;
// method for searching the array for duplicate numbers
boolean fresh (int [] nums, int val){
for (int i = 0; i < amount; i++){
if (nums == val) return true;
}
{
return false;
}
}// end fresh method
//method to generate random numbers to insert into the tree
public void randomNumber()
{
do
{
for (int i=0; i<amount; i++) {
nums = (int) Math.floor(Math.random() * 100);
nums = nums -50;
System.out.println("random is " + nums);
}
}
while(!(fresh(nums,i)));
}// end of randomNumber method
|
|
|
|
|
have altered my code now and it works a lot better. Posted here in case it helps others
// method for searching the array for duplicate numbers
boolean fresh(int[] nums, int val, int index) {
for (int i = 0; i < index; i++) {
if (nums == val) return false;
}
return true;
}// end fresh method
//method to generate random numbers to insert into the tree
public void randomNumber() {
int i;
//do {
for (i = 0; i < amount; i++) {
int aux = (int) Math.floor(Math.random() * 100);
aux = aux - 50;
if (fresh(nums, aux, i)) {
System.out.println("random is " + aux);
nums = aux;
} else {
i--;
//break;
}
}
//} while (i < amount && !(fresh(nums, nums, i)));
}// end of randomNumber method
|
|
|
|
|
|
|
|
|
|