Question
Need help understanding why my countRange function in a java symbol table isn't working. rank() returns the number of keys less than the given key.
Need help understanding why my countRange function in a java symbol table isn't working. rank() returns the number of keys less than the given key. So I did the absolute value of each given keys ranks and then subtracted hi - lo. I'm stuck trying to figure out how to redo this so I get the correct answer when one key is less than all the keys in the symbol table or greater than all the keys in the symbol table.
/** * countRange * * countRange returns the number of keys in the table within the range [key1, key2] (inclusive) * note that keys may not be in order (key1 may be larger than key2): your code should still consider * this a valid range and report the result. * must run in logarithmic time for full credit. hint: rank */ public int countRange(Key key1, Key key2) { // rank returns the number of keys in this symbol table that is less than the given key. // so if the key is not in the table because it is too large it returns max size, if not in because its smaller, it returns 0 StdOut.println(rank(key1) + " " + rank(key2)); int hi = 0, lo = 0; if(java.lang.Math.abs(rank(key2)) > java.lang.Math.abs(rank(key1))) { hi = rank(key2); lo = rank(key1); } else { hi = rank(key1); lo = rank(key2); }
StdOut.println(lo + " " + hi); return (java.lang.Math.abs(hi) - java.lang.Math.abs(lo));
}
Test cases:
0 4 countRangeTest: *Error* Keys: BEIOU, key1: B key2: U actual: 4 expected: 5 0 4 countRangeTest: *Error* Keys: BEIOU, key1: U key2: B actual: 4 expected: 5 0 5 countRangeTest: Correct Keys: BEIOU, key1: A key2: Z actual: 5 expected: 5 1 4 countRangeTest: Correct Keys: BEIOU, key1: C key2: P actual: 3 expected: 3
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started