Reputation: 3405
I am creating a graph. I get 5 values at run time so how should I know which is greater so that I may set max limit?
I have following 5 varibale of values;
int value3=(int)roundf(appDelegate.itemOneValue);
int value4=(int)roundf(appDelegate.itemTwoValue);
int value5=(int)roundf(appDelegate.itemThreeValue);
int value6=(int)roundf(appDelegate.itemFourValue);
int value7=(int)roundf(appDelegate.itemFiveValue);
How to check which of the above variables has the larger value?
Upvotes: 0
Views: 143
Reputation: 8131
You can read a great article on wikipedia: http://en.wikipedia.org/wiki/Selection_algorithm
Here the pseudo-code to get min/max from an array:
function select(list[1..n], k)
for i from 1 to k
minIndex = i
minValue = list[i]
for j from i+1 to n
if list[j] < minValue
minIndex = j
minValue = list[j]
swap list[i] and list[minIndex]
return list[k]
In objc, the pseudo code became something like this:
int value3=(int)roundf(appDelegate.itemOneValue);
int value4=(int)roundf(appDelegate.itemTwoValue);
int value5=(int)roundf(appDelegate.itemThreeValue);
int value6=(int)roundf(appDelegate.itemFourValue);
int value7=(int)roundf(appDelegate.itemFiveValue);
NSArray *values = @[[NSNumber numberWithInt:value3],
[NSNumber numberWithInt:value4],
[NSNumber numberWithInt:value5],
[NSNumber numberWithInt:value6],
[NSNumber numberWithInt:value7]];
NSNumber min=0;
NSNumber max=0;
for ( int i=0; i<[values count]; i++ ) {
min = [values objectAtIndex:i];
//etc...
for (int j=0; j<i+1; j++ ) {
if ( [values[j] > min] ) {
// etc..
}
}
}
hope this helps.
Upvotes: 0
Reputation: 14068
NSArray *allValues = @[[NSNumber numberWithInt:(int)roundf(appDelegate.itemOneValue)],
[NSNumber numberWithInt:(int)roundf(appDelegate.itemTwoValue)],
[NSNumber numberWithInt:(int)roundf(appDelegate.itemThreeValue)],
[NSNumber numberWithInt:(int)roundf(appDelegate.itemFourValue)],
[NSNumber numberWithInt:(int)roundf(appDelegate.itemFiveValue)]];
int max = [[allValues valueForKeyPath:@"@max.intValue"] intValue];
or
NSNumber * max = [allValues valueForKeyPath:@"@max.intValue"];
An alternative that is less flexible but may be easier to understand:
int max = (value2 < value1) value2 : value1;
max = (value3 < max) value3 : max;
max = (value4 < max) value4 : max;
max = (value5 < max) value5 : max;
max = (value6 < max) value6 : max;
max = (value7 < max) value7 : max;
// now max contains the highest of all values.
Upvotes: 2