简体   繁体   中英

Trying to find strict range of a symbol table between two boundary keys

I'm having trouble trying to figure out how to strictly count the number of keys in a table, excluding the boundary keys. My code seems to count the keys including the boundary keys. I would appreciate some help trying to figure this out.

Code:

public int countRangeStrict(Key key1, Key key2) {
       if (key1.compareTo(key2) == 0) return 0;
       if (contains(key2)) return rank(key2) - rank(key1) + 1;
       else return (rank(key2) - rank(key1));
   }

public int rank(Key key) {

if (key == null) throw new IllegalArgumentException();
       int lo = 0;
       int hi = N-1;
       while (lo<=hi){
           int mid = lo + (hi - lo) / 2;
           int temp = key.compareTo(this.key[mid]);
           if (temp < 0) hi = mid - 1;
           else if (temp > 0 ) lo = mid + 1;
           else return mid;
       }
       return lo;
       }

Output:

countRangeStrictTest: Correct Keys: BEIOU, key1: A key2: Z actual: 5 expected: 5
countRangeStrictTest: *Error* Keys: BEIOU, key1: Z key2: A actual: -5 expected: 5
countRangeStrictTest: Correct Keys: BEIOU, key1: J key2: N actual: 0 expected: 0
countRangeStrictTest: *Error* Keys: BEIOU, key1: C key2: O actual: 3 expected: 2
countRangeStrictTest: *Error* Keys: BEIOU, key1: B key2: P actual: 4 expected: 3

Another point, key1 and key2 may not be in order, but my code only considers key1 as the lower boundary and the key2 as the upper boundary. How do I do it so the code will count the keys strictly between the boundaries, and that the boundaries do not need to be in order?

Thanks in advance!

Test #2: The keys are inverted, and your code is not detecting that. You need to check key1.compareTo(key2) > 0 and swap the keys.

Test #4 and #5: You said " excluding the boundary keys", but your countRangeStrict() method is explicitly coded to include both boundary keys.

Which means your code should be something like this:

public int countRangeStrict(Key key1, Key key2) {
    int cmp = key1.compareTo(key2);
    if (cmp == 0)
        return 0;
    if (cmp > 0) {
        Key temp = key1;
        key1 = key2;
        key2 = temp;
    }
    int count = rank(key2) - rank(key1);
    if (contains(key1))
        count--;
    return count;
}

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