Finding maximum numeric value in NSArray - iphone

I have an NSArray of NSNumbers and want to find the maximum value in the array. Is there any built in functionality for doing so? I am using iOS4 GM if that makes any difference.

The KVC approach looks like this:
int max = [[numbers valueForKeyPath:#"#max.intValue"] intValue];
or
NSNumber * max = [numbers valueForKeyPath:#"#max.intValue"];
with numbers as an NSArray

NSArray * test= #[#3, #67, #23, #67, #67];
int maximumValue = [[test valueForKeyPath: #"#max.self"] intValue];
NSLog(#" MaximumValue = %d", maximumValue);
// Maximum = 67

Here is the swift version
let maxValue = (numbers.value(forKeyPath: "#max.self") as! Double)

Hope will helpful to you.
NSArray * arrayOfBarGraphValues = #[#65, #45, #47 ,#87 , #46, #66 ,#77 ,#47 ,#79 ,#78 ,#87 ,#78 ,#87 ];
int maxOfBarGraphValues = [[arrayOfBarGraphValues valueForKeyPath: #"#max.self"] intValue];
NSLog(#" MaximumValue Of BarGraph = %d", maxOfBarGraphValues);

Related

Min and Max Value of an NSMutableArray

I have a simple looking piece of code that has me completely flummoxed.
NSInteger ymax;
NSInteger ymin;
NSInteger numberIndex1;
NSInteger numberIndex2;
for (NSNumber *theNumber in array2)
{
if ([theNumber integerValue] > ymax) {
ymax = [theNumber integerValue];
numberIndex1 = [array2 indexOfObject:theNumber];
}
}
for (NSNumber *theNumber in array2)
{
if ([theNumber integerValue] < ymin) {
ymin = [theNumber integerValue];
numberIndex2 = [array2 indexOfObject:theNumber];
}
}
NSLog(#"Highest number: %d at index: %d", ymax, numberIndex1);
NSLog(#"Lowest number: %d at index: %d", ymin, numberIndex2);
The NSLog is outputted as:
Highest number: 129171656 at index: -1073752392 (Huh??)
Lowest number: 57 at index: 5 (Correct)
How do you explain this odd behaviour? Both the functions look the same. One is working and one isn't? I've played around a lot with this, but I still can't put my finger on it. Any help would be appreciated/
You can get maximum and minimum number as below code. It may help you
NSNumber * max = [array2 valueForKeyPath:#"#max.intValue"];
NSNumber * min = [array2 valueForKeyPath:#"#min.intValue"];
NSUInteger numberIndex1 = [array indexOfObject:min];
NSUInteger numberIndex2 = [array indexOfObject:max];
NSLog(#"Max Value = %d and index = %d",[max intValue],numberIndex1);
NSLog(#"Min Value = %d and index = %d",[min intValue],numberIndex2);
If I am not wrong you are considering the default value of NSInteger is 0, No, it isn't guaranteed to be zero, since it's a local automatic variable. Without initialization, its value is indeterminate.
so you need to set default values for your var, start with ymax = -1;
Please initialize NSInteger ymax = 0;
NSInteger ymin = 0 ;
NSInteger numberIndex1 = 0;
NSInteger numberIndex2 = 0;
It will fix your issue.
Otherwise it is checking with a garbage value and giving wrong result.
enjoy with my answer.......happy coding
NSArray *arr1=[[NSArray alloc]initWithObjects:#"0.987",#"0.951",#"0.881",#"0.784",#"0.662",#"0.522",#"0.381",#"-0.265",#"-0.197",
#"0.189",#"-0.233",#"0.310",#"0.402",#"0.402",#"0.988",#"0.633",#"0.661",#"0.656",#"0.617",#"0.634",#"0.690",#"0.767",#"0.836",nil];
NSNumber * max = [arr1 valueForKeyPath:#"#max.floatValue"];
NSString *str=[NSString stringWithFormat:#"%#",max];
NSInteger path=[arr1 indexOfObject:str];
NSIndexPath *indepath=[NSIndexPath indexPathForItem:path inSection:0];
NSNumber * min = [arr1 valueForKeyPath:#"#min.floatValue"];
NSString *str1=[NSString stringWithFormat:#"%#",min];
NSInteger path1=[arr1 indexOfObject:str1];
NSIndexPath *indepath1=[NSIndexPath indexPathForItem:path1 inSection:0];
NSLog(#"Max Value = %f and index = %ld",[max floatValue],(long)indepath.row);
NSLog(#"Min Value = %f and index = %ld",[min floatValue],(long)indepath1.row);
A more legitimate solution would be:
NSArray *originalArray = #[[NSNumber numberWithInt:91],
[NSNumber numberWithInt:12],
[NSNumber numberWithInt:99123],
[NSNumber numberWithInt:9],
[NSNumber numberWithInt:43234]];
NSArray *sortedArray = [originalArray sortedArrayUsingSelector:#selector(compare:)];
NSNumber *minNumber = [sortedArray objectAtIndex:0];
NSNumber *maxNumber = [sortedArray lastObject];
NSInteger minIndex = [originalArray indexOfObject:minNumber];
NSInteger maxIndex = [originalArray indexOfObject:maxNumber];

Can we assign exact string value to an int value in iphone sdk

In my application I have a value like "25:30" in NSString and I want to assign this value to int value.
If I do like:
int j = [stringval intValue];
hence I got the value "25" to my int value but I want the full value.
Is it possible?
If you mean 25.30 then you need floats, use CGFloat j = [stringval floatValue];
If that is supposed to be minutes & seconds, use NSDateFormatter's dateFromString:.
You can try this
NSString *new = #"25:30";
NSArry *data = [new componentsSeparatedByString:#":"];
int first = [[data objectAtIndex:0] intValue]; \\\ 25
int second = [[data objectAtIndex:1] intValue]; \\\ 30

Retrieve UITextfField values and convert to inches with decimal?

If I have formatting for a textfield like:
//Formats the textfield based on the pickers.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
NSString *result = [feetArray objectAtIndex:[feetPicker selectedRowInComponent:0]];
result = [result stringByAppendingFormat:#"%#ft", [feetArray objectAtIndex:[feetPicker selectedRowInComponent:1]]];
result = [result stringByAppendingFormat:#" %#", [inchArray objectAtIndex:[inchesPicker selectedRowInComponent:0]]];
result = [result stringByAppendingFormat:#"%#", [inchArray objectAtIndex:[inchesPicker selectedRowInComponent:1]]];
result = [result stringByAppendingFormat:#" %#in", [fractionArray objectAtIndex:[fractionPicker selectedRowInComponent:0]]];
myTextField.text = result;
}
Which display's in the textfield like 00ft 00 0/16in How can I change that all to inches with decimal? I'll need to take the ft, and multiply by 12 = variable.Then add that to inches, as well as take my fraction 1/16 and divide that by 16 to get my decimal value and then add that to the inches so it shows like 1234.0625 in order to make my calculation. Can someone help me accomplish this? Thank you in advance!
NSString * theString = RiseTextField.text;
NSString * feetString = [theString substringWithRange:NSMakeRange(0, 2)];
NSString * inchesString = [theString substringWithRange:NSMakeRange(5, 2)];
NSUInteger rangeLength = ([theString length] == 14) ? 1 : 2;
NSString * fractionString = [theString substringWithRange:NSMakeRange(8, rangeLength)];
double totalInInches = [feetString doubleValue] * 12 + [inchesString doubleValue] + [fractionString doubleValue] / 16;
You can easily get the number that you want by doing the calculations with the numbers you have there. Once you've got the actual number, you should use a NSNumberFormatter to present it with the desired amount of decimals and format.
This should solve your problem. Or did you need help converting the strings to numbers so that you can add them together?

How to add an integer value into NSMutableArray?

NSMutableArray * val;
val = [[NSMutableArray alloc] initWithCapacity:15];
/*int outlineWidth = barOutlineWidth;
int outlineHalfWidth = (outlineWidth > 1) ? outlineWidth * 0.5f : 0;
*/
for ( Bar * obj in values )
{
// calcualte the bar size
float value = [obj value];
float scale = ( value / maxValue );
// shift the bar to the top or bottom of the render line
int pointY = lineHeight + ( (lineWidth * 0.5f) * ( ( value >= 0.0f ) ? -1 : 1 ) );
int barHeight = height * scale;
NSLog(#"%d", barHeight);
CGRect barRect = CGRectMake(pointX, pointY, width, -barHeight);
[val addObject:[NSNumber numberWithInt:barHeight]];
NSLog(#"%d", val);
I want to add the barheight (int) into array val.
Is this possible?
while running the code,
session started at 2010-09-16 13:21:50 +0530.]
2010-09-16 13:21:53.791 BarGraphSample[3168:20b] 78
2010-09-16 13:21:53.797 BarGraphSample[3168:20b] 69398112
2010-09-16 13:21:53.807 BarGraphSample[3168:20b] 235
2010-09-16 13:21:53.812 BarGraphSample[3168:20b] 69398112
2010-09-16 13:21:53.813 BarGraphSample[3168:20b] 156
2010-09-16 13:21:53.814 BarGraphSample[3168:20b] 69398112
this is the output.
Here the actual barheights are 78,235,156,
while printing the array val.
Im getting like values like "69398112"
What should I do?
You can only add pointers to objects to an NSMutableArray. If you use the NSNumber class though to wrap your integer, you should then be able to add that to the array.
int x = 10;
NSNumber* xWrapped = [NSNumber numberWithInt:x];
NSMutableArray* array = [[NSMutableArray alloc] initWithCapacity:15];
[array addObject:xWrapped];
int xOut = [[array lastObject] intValue]; //xOut == x;
Hope this helps.
Add a number instead.
NSNumber* foo = [NSNumber numberWithInteger:42];
or using boxed literals:
NSNumber* foo = #(42);
then add foo.
The issue is with your NSLog string namely
NSLog(#"%d", val);
%d is in fact the format specifier for an integer (int). You are passing it a NSMutableArray object.
Change the NSLog to
NSLog(#"%#", val);
The %# expects an object, and this will typically print out [myObject description], in this case a description of your val array.
Convert Int to NSNumber then add to your array
This is a simple way: #(yourInt)
int value = 5;
NSMutableArray * anArray = [[NSMutableArray alloc] init];
[anArray addObject: #(value)];
more information about at-compiler-directives

NSString stringWithFormat question

I am trying to build a small table using NSString. I cannot seem to format the strings properly.
Here is what I have
[NSString stringWithFormat:#"%8#: %.6f",e,v]
where e is an NSString from somewhere else, and v is a float.
What I want is output something like this:
Grapes: 20.3
Pomegranates: 2.5
Oranges: 15.1
What I get is
Grapes:20.3
Pomegranates:2.5
Oranges:15.1
How can I fix my format to do something like this?
you could try using - stringByPaddingToLength:withString:startingAtIndex:
NSDictionary* fruits = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:20.3], #"Grapes",
[NSNumber numberWithFloat:2.5], #"Pomegranates",
[NSNumber numberWithFloat:15.1], #"Oranges",
nil];
NSUInteger longestNameLength = 0;
for (NSString* key in [fruits allKeys])
{
NSUInteger keyLength = [key length];
if (keyLength > longestNameLength)
{
longestNameLength = keyLength;
}
}
for (NSString* key in [fruits allKeys])
{
NSUInteger keyLength = [key length];
NSNumber* object = [fruits objectForKey:key];
NSUInteger padding = longestNameLength - keyLength + 1;
NSLog(#"%#", [NSString stringWithFormat:#"%#:%*s%5.2f", key, padding, " ", [object floatValue]]);
}
Output:
Oranges: 15.10
Pomegranates: 2.50
Grapes: 20.30
The NSNumberFormatter class is the way to go!
Example:
NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
[numFormatter setPaddingCharacter:#"0"];
[numFormatter setFormatWidth:2];
NSString *paddedString = [numFormatter stringFromNumber:[NSNumber numberWithInteger:integer]];
[numFormatter release];
I think you want something like
[NSString stringWithFormat:#"%-9# %6.1f",[e stringByAppendingString:#":"],v]
since you want padding in front of the float to make it fit the column, though if the NSString is longer than 8, it will break the columns.
%-8f left-aligns the string in a 9-character-wide column (9-wide since the : is appended to the string beforehand, which is done so the : is at the end of the string, not after padding spaces); %6.1f right-aligns the float in a 6-char field with 1 decimal place.
edit: also, if you're viewing the output as if it were HTML (through some sort of web view, for instance), that may be reducing any instances of more than one space to a single space.