简体   繁体   中英

finding the smallest element in an array that is greater than a set limit: java

Im trying to write a function that loops through a list one time and prints out the index of the smallest element that is greater than a set limit.

using == informally this is the expected output:

0 == posOfSmallestElementGtOeT(3, new double[] { 7 })

3 == posOfSmallestElementGtOeT(3, new double[] { 11, -4, -7, 4, 8, 1 })

-1 == posOfSmallestElementGtOeT(17, new double[] { 1, -4, -5, 7, 8, 11 })

I have this so far. I can find elements that are greater than the set limit, but cannot figure out how to compare them properly.

public static int posOfSmallestElementGtOeT( double limit, double[] list) {
    double greater = 0;
    int pos = 0;
    for(int i=0; i < list.length; i++) {
        if(list[i] >= limit) {
            System.out.println(list[i]);
            //for testing
        }
    }
    return pos;
}

currently my function returns the last value that is greater than the set limit. Can someone please guide me on how to find the smallest of those vals.

This will solve your problem.

public static int posOfSmallestElementGtOeT( double limit, double[] list) {
    double greater = 0;
    int pos = -1;
    for(int i=0; i < list.length; i++) {
        if(list[i] >= limit) {
            if(pos == -1) // check whether its the first value above the limit in the list
                pos = i;
            else if(list[pos] > list[i]) //compare the current value with the previous smallest value
                pos = i;
        }
    }
    return pos;
}

For the first element greater than threshold you save directly it's position. For the next ones you compare the current best candidate ( list[pos] ) with the current element ( list[i] ): if the first is greater then the second, there is a better candidate than the former, so the position that will be returned by the method will be updated.

Example: threshold : 1.5
myArray : 2, 1.6, 1.4, -5.2

  1. The first element is greater than the threshold, so set the variable pos = 0
  2. The second element is greater than the threshold, but pos != -1, so you evaluate the second condition: list[0] > list[1] , or 2 > 1.6.
  3. The condition is true, so you update the value of pos = 1

In this way you will cycle only one time to find the expected result, with a cost which is O(N), where N is the number of item of the array (linear cost).


Be aware that the smallest element greater or equal to the threshould could not exist, as in the following example:

threshold : 1.5
myArray : 0.3, 0.6, 1.4, -5.2

In this case the method will return -1 and the call should manage that result properly, for example:

if(posOfSmallestElementGtOeT( threshold, myArray) == -1) {
    System.out.println("No element greater or equal to the threshold");
}

On the Web page How do I ask a good question? , it is written that one of the criteria for a good question is research. Your question gives me the impression that you did not. An Internet search for the terms smallest array element greater than minimum turned up an implementation in Python as follows:

min_val = 10000000
for i in test_list : 
    if min_val > i and i > k : 
        min_val = i

I had no trouble translating that code to java – even though I don't know Python at all. The difference being that you requested the location of the element whereas the above code returns the actual element value. Again, doesn't seem too difficult to modify the above code (after translating it to java) so that it returns the element index and not the element value.

public static int posOfSmallestElementGtOeT(double limit, double[] list) {
    double min = Double.MAX_VALUE;
    int ndx = -1;
    for (int i = 0; i < list.length; i++) { 
        if (min >= list[i] && list[i] >= limit) { 
            min = list[i];
            ndx = i;
        }
    }
    return ndx;
}

Note that the above code will also work for an empty array.
(But a null array will throw a NullPointerException :-)

Assuming list contains at least one element:

public static int posOfSmallestElementGtOeT(double limit, double[] list) {
    double greater = list[0];

    int pos = greater >= limit ? 0 : -1;

    for(int i = 1; i < list.length; i++) {
        if(list[i] >= limit && list[i] < greater) {
            pos = i;
            greater = list[i];
        }
    }
    return pos;
}

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