简体   繁体   中英

Java - Returning the smallest element of the given non-empty array

I am studying Java and trying to find the bug in my code.

It is suppose to return the smallest element of the given non-empty array.

It works with B = [-3, 4, -2, -2]

Can you tell me what I am doing wrong here?

class Test {
    int test(int[] B, int[] C) {
        int ans = 0;
        for (int i = 1; i < B.length; i++) {
            if (ans > B[I]) {
                ans = B[i];
            }
        }
        return ans;
    }
}

Arrays are 0th based index in Java so start your for loop with i=0

class Test {
    int test(int[] B) {
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < B.length; i++) {
            if (ans > B[i]) {
                ans = B[i];
            }
        }
        return ans;
    }
}

Here is an example that your above code will fail

Input: B = [1,2,3,4,5]
Expected Output: 1
Your Output: 0

The root cause is that the initial value of ans is 0. Set it to 1001 (or any other int value that is greater than the maximum value of the range) AND traverse from the first element of the array instead of the second one would do the trick.

There are two problems in your code: One is that you set ans to 0 in initialization. The second is that you start from index 1 rather than index 0, so you may be missing values that way.

Happily, these two problems can be solved with one solution:

class Test {
    int test(int[] B) {
        int ans = B[0]; // use the first element of the array as the start value for ans. 
        //Doing that, you don't need to change your loop
        for (int i = 1; i < B.length; i++) {
            if (ans > B[i]) {
                ans = B[i];
            }
        }
        return ans;
    }
}

You are not considering the first element of the array. Either set ans to that or start looping from index 0 and set ans to Integer.MAX_VALUE (which will also work for an empty array).

int test(int[] B) {
    int ans = Integer.MAX_VALUE;
    for (int i = 0; i < B.length; i++) {
        if (ans > B[I]) {
            ans = B[i];
        }
    }
    return ans;
}

For a shorter solution, you can use IntStream.min .

int test(int[] B){
    return Arrays.stream(B).min().orElse(Integer.MAX_VALUE);
    //return minimum or Integer.MAX_VALUE if the array is empty
}

The cause of your bug is because you're setting the ans variable to 0, instead of setting it to the maximum integer value ( MAX_VALUE ) as indicated by most solutions above:

int test(int[] B) {
    int ans = Integer.MAX_VALUE;
    for (int i = 0; i < B.length; i++) {
        if (ans > B[I]) {
            ans = B[i];
        }
    }
    return ans;
}

Your solution will only work if the given array consists of at-least 1 non-positive element. Once you have an Array with all positive elements, you solution will always return a 0 because no element in an array will ever be less than your initially assumed minimum which is zero in your case.

Alternatively to using streams: you can sort the Array first and get the first element, assuming it will be sorted in ascending order:

int test(int[] B) {
    Arrays.sort(B); // Sorts the array in ascending order
    return B[0];
}

Test Question

I was searching a solution to my problem on the Internet, and I saw your question. I think the problem here is changing only one line, at least my question was like that.

I solved it in Python but I will share also the Java Solution.

This is the starting code given in Python ,

def solution(A):
    ans = 0
    for i in range(1, len(A)):
        if A[i] < ans:
            ans = A[i]
    return ans

And this is my solution to it with only one line change!

def solution(A):
    ans = A[0]
    for i in range(1, len(A)):
        if A[i] < ans:
            ans = A[i]
    return ans

If we think the same think for the Java code which you shared (I corrected some part of your codes already),

class Test {
    int test(int[] B) {
        int ans = B[0];
        for (int i = 1; i < B.length; i++) {
            if (ans > B[i]) {
                ans = B[i];
            }
        }
        return ans;
    }
}

I know this is a specific solution for the question and there are some rules like array cannot be empty.. But I hope it will helps the others. Other solutions are also correct. The only difference that I made it only one line change.

Happy Coding..

Of course there is a bug, even more than one. There will always be bugs if you try to do things in a complex way, this is a perfect example of accidental complexity. What you are trying to do here is not obvious from this code at first glance, I have to look into it, analyze it and think on it for a while.

Look at something like this:

int findMinimum(int[] array) {
    return IntStream.of(array).min().getAsInt();
}
  1. I can immediately see what this method does - the min() just jumps at me

  2. if it compiles then there is a big chance it works, hard to make a mistake here

  3. I can easy handle the case of array being empty - I added getAsInt at the end, but without it I would have an OptionalInt - it's just a good practice to handle such edge cases, trying to find something in an empty array is not that uncommon

  4. easy to handle similiar cases - finding maximum ( max() ) or average ( average() ) and many more

Note: this is a 'good practice' answer, since there already are answers that answer the problem here - maybe someone will benefit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM