jeudi 20 décembre 2018

My if condition is returning as true, despite double checking my logic

I've been tasked with creating a binary search program for homework (irrelevant to the question, sort of). It was suggested to set the values of the integer array myself, but I decided to take it a little further for my own development. However, it seems there is a logic error, because the condition is passing as true when it seemingly should not be. I am trying to check that a value is not present in an integer array and is not 0, and if that is the case, add it to the array.

I've checked my syntax, changed my logic, and tried to use different loops. Other ways of avoiding 0 and duplicates seem far more complicated, unless there is a fundamental error in my understanding.

Here's what I've got:

int numbers[] = new int[50]; 

        for(int i = 0; i < numbers.length; i++) {
            int addVal = (int)(Math.random()*400+1); //assign addVal to a random int
            boolean duplicate = IntStream.of(numbers).anyMatch(x -> x == addVal); //check if array contains the random value generated and assigned to addVal
            if(addVal != 0 && duplicate == false) { //when the number is not 0 and is not in the list
                numbers[i] = addVal; //add it to the list
            }
        }
Arrays.sort(numbers); //sort the numbers

Here's an example output upon printing the array values:

[0, 0, 11, 21, 34, 40, 51, 53, 54, 61, 76, 91, 114, 120, 166, 173, 199, 209, 249, 266, 277, 295, 301, 312, 340, 349, 355, 365, 366, 392]

I expected it to work as follows: I create an array to store 50 values. For each index, assign addVal a random integer between 0-400 (added 1 to see if it reduces the frequency 0 appears, it seems to have, going larger did not help). Then, check if my numbers array contains the value randomly assigned to addVal. If it does not and the value is also not 0, add it to the array. After all the values have been added, I sort the array (for the binary search).

I would greatly appreciate any help in finding my error.

Also, two side questions: how would I modify this to work with a single enhanced for loop, and why is that sorting the array in the for loop results in significantly more 0s?




Aucun commentaire:

Enregistrer un commentaire