August 13th, 2013, 10:42 PM
Hello everyone! I'm new to the forum and pleased to be here.
I'm going through Big Java and scanning the little programming exercises etc. and came across a problem that raised a question. I'd love to hear your thoughts.
The problem is to "write a class DataSet that computes the largest and smallest values in a sequence of numbers" It goes on to give a hint as to utilize Integer.MAX_VALUE and Integer.MIN_VALUE.
Pretty straight forward but I was wondering if there was a way to achieve this without using the above hint and obviously, without utilizing decision statements etc.
This is not homework. I'm just going through past chapters and seeing if I can tackle problems in different ways given the tools learned up to that point of instruction.
Thanks in advance!
August 14th, 2013, 02:43 AM
Yea, it is possible. Firstly, create an variable for smallest and biggest. Assign the value of the first number to both of them. Then in your loop, compare the numbers, if it's bigger / smaller, replace the appropriate one.
August 14th, 2013, 12:46 PM
Thanks Xerixe for the response! I guess I should have been more clear in that I'm trying to avoid decision statements or loops.
I know there's really no point but it's more of a puzzle for me as decisions and loops are not discussed until the next chapter. I'm trying to work with what the book as discussed as of that point and without using their hint of Integer.MAX and Integer.MIN values.
Thanks again for the response.
August 14th, 2013, 12:55 PM
Hm, if you want to use Integer.MAX_VALUE and Integer.MIN_VALUE,
you could do this.
Then you could compare from there. Because, since the current value of "highest" is the lowest possible number. Any number would be considered bigger than it.
int highest = Integer.MIN_VALUE, lowest = Integer.MAX_VALUE;
So from there, you can compare the value of input against "highest" and "lowest".
August 14th, 2013, 01:51 PM
Out of curiosity, what is the hint?
Originally Posted by stillInBeta
August 14th, 2013, 01:55 PM
The books hint is using Integer.MAX_VALUE and Integer.MIN_VALUE.
I'm trying to see if there is a way to do it without using the above hint as well as loops and decisions. Pretty much, swimming with no legs or arms.
August 15th, 2013, 08:34 PM
That's impossible. You have to use loops and if statements for accomplishing that task. At most, you could use recursion to replace the loop, but you would still need an if statement.
You might want to read this to get a better idea.
However, Java does come with libraries to do things for you. So if you really don't want a loop or an if statement in your code, you could call Collections.max or Collections.min, but all this would be doing is hiding the implementation behind a method (which is good and possibly more efficient).