How to multiply respective objects of NSArray and get the sum? - objective-c

I have one array with data A=[a,b,c] and another with data B=[d,e,f]. I need to perform this type of operation a.d+ b.e+c.f (Note=Here (.) denotes multplication)and get the result. How can i do that using Objective-C?
Thanks in advance.

Define the function that does the multiplication and addition like this:
- (double)multiply:(NSArray <NSNumber *> *)vector1 withVector:(NSArray <NSNumber *> *)vector2 {
NSAssert(vector1.count == vector2.count, #"Both arrays should contain the same number of elements");
__block double result = 0;
[vector1 enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
double first = obj.doubleValue;
double second = vector2[idx].doubleValue;
result += first * second;
}];
return result;
}
This uses a block enumeration method on NSArray which gives me in index and a value, which I can use to get the value at the same index in the second array. Note also that I am using a typed array, so I don't have to cast the values to NSNumbers when using them.
Now you can just use the function:
NSArray *a = #[#1, #2, #3];
NSArray *b = #[#4, #5, #6];
NSArray *c = #[#1, #1, #1];
double res1 = [self multiply:a withVector:b]; // => 32.000000
double res2 = [self multiply:b withVector:c]; // => 15.000000
double res3 = [self multiply:c withVector:a]; // => 6.000000

NSNumber *myNum1 = [NSNumber numberWithInt:1];
NSNumber *myNum2 = [NSNumber numberWithInt:2];
NSNumber *myNum3 = [NSNumber numberWithInt:3];
NSArray *a = [NSArray arrayWithObjects: myNum1, myNum2, myNum3, nil];
NSArray *b = [NSArray arrayWithObjects: myNum1, myNum2, myNum3, nil];
int sum=0;
for (int i=0; i<[a count]; i++) {
NSLog(#"%#", (NSNumber*)[a objectAtIndex:i]);
sum =sum +[(NSNumber*)[a objectAtIndex:i] intValue]*[(NSNumber*)[b objectAtIndex:i] intValue];
}
NSLog(#"Sum is %d", sum);
Hope this helps

Related

Compare NSArray elements to NSNumber

I'm new to objective c. I am getting my data from an NSArray and want to return value according to some condition. My code is:
NSArray *myData;
NSNumber *day = 5;
myData = [NSArray arrayWithObjects: #"5", nil];
for (int i = 0; i < [myData count]; i++) {
if(day == myData[0]){
NSLog(#"date in valueForDay %# ", da );
return 3;
}
}
Above code doesn't execute my statements (NSLog and return one).
But if i statically compare day with any number it got executed. Like:
NSArray *myData;
NSNumber *day = 5;
myData = [NSArray arrayWithObjects: #"5", nil];
for (int i = 0; i < [myData count]; i++) {
if(day == 5){
NSLog(#"date in valueForDay %# ", da );
return 3;
}
}
can anyone please tell me where i'm doing wrong?
You have created array with string value not with number value. That's why object from your array is "5" which is not equal to integer 5. Make your array as number array.
myData = [NSArray arrayWithObjects: #5, nil];
Also instead of for loop you can simply use indexOfObject to check array having object or not.
NSInteger index = [myData indexOfObject: day];
if(index != NSNotFound) {
return 3;
}
You stored NSString in NSArray. And comparing with NSNumber. You have to add one line above if condition and change your condition.
NSString *myString = [day stringValue];
if([myString isEqualToString:myData[0]])

NSTableColumn sorts numbers wrongly

This is a NSTableView with IB bindings to a NSArrayController, it displays all values correctly.
However it sorts the numbers only by their first char value e.g. it will put 115.31 below 2.5, and 23.9 below 4.71, etc.
It takes values from a retained NSMutableArray with Strings in it, I also tried by converting all strings to NSNumber/NSDecimalNumber, still no luck:
NSMutableArray *array1 = [[string1 componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy];
NSMutableArray *array1alt = [NSMutableArray array];
for(NSString *strNum in array1)
{
NSNumber *number = strNum;
[array1alt addObject:number];
}
Please help, thanks.
EDIT: This is how NSMutableArray(s) of my NSTableColumn(s) get filled:
NSMutableArray *rows = [NSMutableArray array];
for (NSUInteger i = 0; i < array1alt.count && i < array2.count && i < array3.count && i < array4.count; i++)
{
NSMutableDictionary *row = [NSMutableDictionary dictionary];
[row setObject:[array1alt objectAtIndex:i] forKey:#"Apples"];
[row setObject:[array2 objectAtIndex:i] forKey:#"Oranges"];
[row setObject:[array3 objectAtIndex:i] forKey:#"Peaches"];
[row setObject:[array4 objectAtIndex:i] forKey:#"Plums"];
[rows addObject:row];
}
[myArrayController2 setContent:rows2];
[aTableView reloadData];
I'm surprised that you aren't getting a compiler warning at:
NSNumber *number = strNum;
You probably want:
NSNumber *number = [NSNumber numberWithDouble:[strNum doubleValue]];
Or, more simply:
NSNumber *number = #([strNum doubleValue]);
If you don't want to deal with number conversions on the output, you could sort your original array of strings like so:
NSArray *array2 = [array1 sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
double num1 = [obj1 doubleValue];
double num2 = [obj2 doubleValue];
if (num1 < num2)
return NSOrderedAscending;
else if (num1 > num2)
return NSOrderedDescending;
else
return NSOrderedSame;
}];
If you want to use decimal numbers, you could probably do something like:
NSMutableArray *array2 = [NSMutableArray array];
for (NSString *strNum in array1)
{
[array2 addObject:[NSDecimalNumber decimalNumberWithString:strNum]];
}
[array2 sortUsingComparator:^NSComparisonResult(NSDecimalNumber *obj1, NSDecimalNumber *obj2) {
return [obj1 compare:obj2];
}];
Without seeing more code this is what i think:
If i understood correctly, you have your NSArrayController as data source.
You need to sort your data before attaching it to your table.
You have NSArrayController methods:
- (void)setSortDescriptors:(NSArray *)sortDescriptors
and
- (NSArray *)arrangeObjects:(NSArray *)objects
With this you will get sorted array to use for your table.
Maybe you will need to call reloadData of your NSTableView.
I cant test these right now because i'm at my laptop right now which doesn't have MacOS :)

How to exclude previously randomly selected NSArrays in loop

I'm new to Objective-C and I'm trying to create a simple dictionary style app for personal use. Right now I'm attempting to make a loop that prints randomly selected NSArrays that have been added to an NSDictionary. I'd like to print each array only once. Here is the code I'm working with:
NSArray *catList = [NSArray arrayWithObjects:#"Lion", #"Snow Leopard", #"Cheetah", nil];
NSArray *dogList = [NSArray arrayWithObjects:#"Dachshund", #"Pitt Bull", #"Pug", nil];
...
NSMutableDictionary *wordDictionary = [[NSMutableDictionary alloc] init];
[wordDictionary setObject: catList forKey:#"Cats"];
[wordDictionary setObject: dogList forKey:#"Dogs"];
...
NSInteger keyCount = [[wordDictionary allKeys] count];
NSInteger randomKeyIndex = arc4random() % keyCount;
int i = keyCount;
for (i=i; i>0; i--) {
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey];
NSLog(#"%#", randomlySelectedArray);
}
This code prints the same array "i" times. Any pointers on how to exclude previously printed arrays from being printed again?
I'm wondering if removeObjectForKey: could be of any use.
You just need to re-calculate the random key index every time you go through the loop, and then, as you suggest, use removeObjectForKey:.
Something like this:
NSArray *catList = [NSArray arrayWithObjects:#"Lion", #"Snow Leopard", #"Cheetah", nil];
NSArray *dogList = [NSArray arrayWithObjects:#"Dachshund", #"Pitt Bull", #"Pug", nil];
//...
NSMutableDictionary *wordDictionary = [[NSMutableDictionary alloc] init];
[wordDictionary setObject: catList forKey:#"Cats"];
[wordDictionary setObject: dogList forKey:#"Dogs"];
//...
while ([wordDictionary count] > 0) {
NSInteger keyCount = [wordDictionary count];
NSInteger randomKeyIndex = arc4random() % keyCount;
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey];
NSLog(#"%#", randomlySelectedArray);
[wordDictionary removeObjectForKey: randomKey];
}
In your code, you generate a random randomKeyIndex, then use it without changing its value i times in the loop. So you get i times the same array.
NSInteger randomKeyIndex = arc4random() % keyCount;
// ...
for (i=i; i>0; i--) {
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
// ...
}
As you say removeObjectForKey is an option for you, you can change your code into something like this:
NSInteger keyCount = [[wordDictionary allKeys] count];
for (i=keyCount; i>0; i--) {
NSInteger randomKeyIndex = arc4random() % keyCount;
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey];
[wordDictionary removeObjectForKey:randomKey];
keyCount--;
NSLog(#"%#", randomlySelectedArray);
}

Obj-C: Calculate the standard deviation of an NSArray of NSNumber objects?

If I have an NSArray of NSNumber objects, how do I calculate the standard deviation of the numbers in the array?
Assuming it's safe to process all NSNumbers as double length floats (so you'll lose some precision if you've got some 64 bit integers at extreme ends of the range in there) and I've remembered the formula correctly a first implementation could be:
- (NSNumber *)meanOf:(NSArray *)array
{
double runningTotal = 0.0;
for(NSNumber *number in array)
{
runningTotal += [number doubleValue];
}
return [NSNumber numberWithDouble:(runningTotal / [array count])];
}
- (NSNumber *)standardDeviationOf:(NSArray *)array
{
if(![array count]) return nil;
double mean = [[self meanOf:array] doubleValue];
double sumOfSquaredDifferences = 0.0;
for(NSNumber *number in array)
{
double valueOfNumber = [number doubleValue];
double difference = valueOfNumber - mean;
sumOfSquaredDifferences += difference * difference;
}
return [NSNumber numberWithDouble:sqrt(sumOfSquaredDifferences / [array count])];
}
You can use NSExpression built-in functions.
NSArray *numbers = #[#1, #2, #3, #4, #5, #6, #7, #8];
NSExpression *expression = [NSExpression expressionForFunction:#"stddev:" arguments:#[[NSExpression expressionForConstantValue:numbers]]];
NSNumber *value = [expression expressionValueWithObject:nil context:nil];
NSLog(#"%#,", value); // => 2.29128...
For more information check the official documentation and this NSHipster article.
Here a category for NSArray to facilitate similar tasks, using NSExpression, similar to Tiago's method. You can pass it any NSExpression that you wish to calculate as string (colon is added in the function).
#interface NSArray (Stats)
- (NSNumber *)calculateStat:(NSString *)stat;
#end
#implementation NSArray (Stats)
- (NSNumber *)calculateStat:(NSString *)stat
{
NSArray *args = #[[NSExpression expressionForConstantValue:self]];
NSString *statFormatted = [stat stringByAppendingString:#":"];
NSExpression *expression = [NSExpression expressionForFunction:statFormatted arguments:args];
return [expression expressionValueWithObject:nil context:nil];
}
#end
Use like so:
NSNumber *result = [myArray calculateStat:#"stddev"];
Here's a link to an algorithm you could use. I don't know of any built-in Objective C statistics libraries, so I would just implement the algorithm myself. The link does it in Java, but it should be easy to convert.
There is some good code on Rosetta Code for this. To go through your NSArray (instead of C array like they have in their example), just use this code along with their implementation of SDAccum:
- (double)computeStandardDeviationWithArray:(NSArray *)numberArray
{
double sd;
SDAccum *sdacc = [[SDAccum alloc] init];
for(NSNumber *aNumber in numberArray)
{
sd = [sdacc value: [aNumber doubleValue]];
}
[sdacc release];
return sd;
}
Here is another version I've used some time ago.
NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:...],
[NSNumber numberWithInt:...],
[NSNumber numberWithInt:...], nil];
// Compute array average
int total = 0;
int count = [numbers count];
for (NSNumber *item in numbers) {
total += [item intValue];
}
double average = 1.0 * total / count;
// Sum difference squares
double diff, diffTotal = 0;
for (NSNumber *item in numbers) {
diff = [item doubleValue] - average;
diffTotal += diff * diff;
}
// Set variance (average from total differences)
double variance = diffTotal / count; // -1 if sample std deviation
// Standard Deviation, the square root of variance
double stdDeviation = sqrt(variance);

How can I reverse a NSArray in Objective-C?

I need to reverse my NSArray.
As an example:
[1,2,3,4,5] must become: [5,4,3,2,1]
What is the best way to achieve this?
There is a much easier solution, if you take advantage of the built-in reverseObjectEnumerator method on NSArray, and the allObjects method of NSEnumerator:
NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];
allObjects is documented as returning an array with the objects that have not yet been traversed with nextObject, in order:
This array contains all the remaining objects of the enumerator in enumerated order.
For obtaining a reversed copy of an array, look at danielpunkass' solution using reverseObjectEnumerator.
For reversing a mutable array, you can add the following category to your code:
#implementation NSMutableArray (Reverse)
- (void)reverse {
if ([self count] <= 1)
return;
NSUInteger i = 0;
NSUInteger j = [self count] - 1;
while (i < j) {
[self exchangeObjectAtIndex:i
withObjectAtIndex:j];
i++;
j--;
}
}
#end
Some benchmarks
1. reverseObjectEnumerator allObjects
This is the fastest method:
NSArray *anArray = #[#"aa", #"ab", #"ac", #"ad", #"ae", #"af", #"ag",
#"ah", #"ai", #"aj", #"ak", #"al", #"am", #"an", #"ao", #"ap", #"aq", #"ar", #"as", #"at",
#"au", #"av", #"aw", #"ax", #"ay", #"az", #"ba", #"bb", #"bc", #"bd", #"bf", #"bg", #"bh",
#"bi", #"bj", #"bk", #"bl", #"bm", #"bn", #"bo", #"bp", #"bq", #"br", #"bs", #"bt", #"bu",
#"bv", #"bw", #"bx", #"by", #"bz", #"ca", #"cb", #"cc", #"cd", #"ce", #"cf", #"cg", #"ch",
#"ci", #"cj", #"ck", #"cl", #"cm", #"cn", #"co", #"cp", #"cq", #"cr", #"cs", #"ct", #"cu",
#"cv", #"cw", #"cx", #"cy", #"cz"];
NSDate *methodStart = [NSDate date];
NSArray *reversed = [[anArray reverseObjectEnumerator] allObjects];
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(#"executionTime = %f", executionTime);
Result: executionTime = 0.000026
2. Iterating over an reverseObjectEnumerator
This is between 1.5x and 2.5x slower:
NSDate *methodStart = [NSDate date];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[anArray count]];
NSEnumerator *enumerator = [anArray reverseObjectEnumerator];
for (id element in enumerator) {
[array addObject:element];
}
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(#"executionTime = %f", executionTime);
Result: executionTime = 0.000071
3. sortedArrayUsingComparator
This is between 30x and 40x slower (no surprises here):
NSDate *methodStart = [NSDate date];
NSArray *reversed = [anArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
return [anArray indexOfObject:obj1] < [anArray indexOfObject:obj2] ? NSOrderedDescending : NSOrderedAscending;
}];
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(#"executionTime = %f", executionTime);
Result: executionTime = 0.001100
So [[anArray reverseObjectEnumerator] allObjects] is the clear winner when it comes to speed and ease.
DasBoot has the right approach, but there are a few mistakes in his code. Here's a completely generic code snippet that will reverse any NSMutableArray in place:
/* Algorithm: swap the object N elements from the top with the object N
* elements from the bottom. Integer division will wrap down, leaving
* the middle element untouched if count is odd.
*/
for(int i = 0; i < [array count] / 2; i++) {
int j = [array count] - i - 1;
[array exchangeObjectAtIndex:i withObjectAtIndex:j];
}
You can wrap that in a C function, or for bonus points, use categories to add it to NSMutableArray. (In that case, 'array' would become 'self'.) You can also optimize it by assigning [array count] to a variable before the loop and using that variable, if you desire.
If you only have a regular NSArray, there's no way to reverse it in place, because NSArrays cannot be modified. But you can make a reversed copy:
NSMutableArray * copy = [NSMutableArray arrayWithCapacity:[array count]];
for(int i = 0; i < [array count]; i++) {
[copy addObject:[array objectAtIndex:[array count] - i - 1]];
}
Or use this little trick to do it in one line:
NSArray * copy = [[array reverseObjectEnumerator] allObjects];
If you just want to loop over an array backwards, you can use a for/in loop with [array reverseObjectEnumerator], but it's likely a bit more efficient to use -enumerateObjectsWithOptions:usingBlock::
[array enumerateObjectsWithOptions:NSEnumerationReverse
usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
// This is your loop body. Use the object in obj here.
// If you need the index, it's in idx.
// (This is the best feature of this method, IMHO.)
// Instead of using 'continue', use 'return'.
// Instead of using 'break', set '*stop = YES' and then 'return'.
// Making the surrounding method/block return is tricky and probably
// requires a '__block' variable.
// (This is the worst feature of this method, IMHO.)
}];
(Note: Substantially updated in 2014 with five more years of Foundation experience, a new Objective-C feature or two, and a couple tips from the comments.)
After reviewing the other's answers above and finding Matt Gallagher's discussion here
I propose this:
NSMutableArray * reverseArray = [NSMutableArray arrayWithCapacity:[myArray count]];
for (id element in [myArray reverseObjectEnumerator]) {
[reverseArray addObject:element];
}
As Matt observes:
In the above case, you may wonder if -[NSArray reverseObjectEnumerator] would be run on every iteration of the loop — potentially slowing down the code. <...>
Shortly thereafter, he answers thus:
<...> The "collection" expression is only evaluated once, when the for loop begins. This is the best case, since you can safely put an expensive function in the "collection" expression without impacting upon the per-iteration performance of the loop.
Georg Schölly's categories are very nice. However, for NSMutableArray, using NSUIntegers for the indices results in a crash when the array is empty. The correct code is:
#implementation NSMutableArray (Reverse)
- (void)reverse {
NSInteger i = 0;
NSInteger j = [self count] - 1;
while (i < j) {
[self exchangeObjectAtIndex:i
withObjectAtIndex:j];
i++;
j--;
}
}
#end
The most efficient way to enumerate an array in reverse:
Use enumerateObjectsWithOptions:NSEnumerationReverse usingBlock. Using #JohannesFahrenkrug's benchmark above, this completed 8x quicker than [[array reverseObjectEnumerator] allObjects];:
NSDate *methodStart = [NSDate date];
[anArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//
}];
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(#"executionTime = %f", executionTime);
NSMutableArray *objMyObject = [NSMutableArray arrayWithArray:[self reverseArray:objArrayToBeReversed]];
// Function reverseArray
-(NSArray *) reverseArray : (NSArray *) myArray {
return [[myArray reverseObjectEnumerator] allObjects];
}
Reverse array and looping through it:
[[[startArray reverseObjectEnumerator] allObjects] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
...
}];
To update this, in Swift it can be done easily with:
array.reverse()
As for me, have you considered how the array was populated in the first place? I was in the process of adding MANY objects to an array, and decided to insert each one at the beginning, pushing any existing objects up by one. Requires a mutable array, in this case.
NSMutableArray *myMutableArray = [[NSMutableArray alloc] initWithCapacity:1];
[myMutableArray insertObject:aNewObject atIndex:0];
Or the Scala-way:
-(NSArray *)reverse
{
if ( self.count < 2 )
return self;
else
return [[self.tail reverse] concat:[NSArray arrayWithObject:self.head]];
}
-(id)head
{
return self.firstObject;
}
-(NSArray *)tail
{
if ( self.count > 1 )
return [self subarrayWithRange:NSMakeRange(1, self.count - 1)];
else
return #[];
}
There is a easy way to do it.
NSArray *myArray = #[#"5",#"4",#"3",#"2",#"1"];
NSMutableArray *myNewArray = [[NSMutableArray alloc] init]; //this object is going to be your new array with inverse order.
for(int i=0; i<[myNewArray count]; i++){
[myNewArray insertObject:[myNewArray objectAtIndex:i] atIndex:0];
}
//other way to do it
for(NSString *eachValue in myArray){
[myNewArray insertObject:eachValue atIndex:0];
}
//in both cases your new array will look like this
NSLog(#"myNewArray: %#", myNewArray);
//[#"1",#"2",#"3",#"4",#"5"]
I hope this helps.
I don't know of any built in method.
But, coding by hand is not too difficult. Assuming the elements of the array you are dealing with are NSNumber objects of integer type, and 'arr' is the NSMutableArray that you want to reverse.
int n = [arr count];
for (int i=0; i<n/2; ++i) {
id c = [[arr objectAtIndex:i] retain];
[arr replaceObjectAtIndex:i withObject:[arr objectAtIndex:n-i-1]];
[arr replaceObjectAtIndex:n-i-1 withObject:c];
}
Since you start with a NSArray then you have to create the mutable array first with the contents of the original NSArray ('origArray').
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr setArray:origArray];
Edit: Fixed n -> n/2 in the loop count and changed NSNumber to the more generic id due to the suggestions in Brent's answer.
If all you want to do is iterate in reverse, try this:
// iterate backwards
nextIndex = (currentIndex == 0) ? [myArray count] - 1 : (currentIndex - 1) % [myArray count];
You can do the [myArrayCount] once and save it to a local variable (I think its expensive), but I’m also guessing that the compiler will pretty much do the same thing with the code as written above.
Swift 3 syntax :
let reversedArray = array.reversed()
Try this:
for (int i = 0; i < [arr count]; i++)
{
NSString *str1 = [arr objectAtIndex:[arr count]-1];
[arr insertObject:str1 atIndex:i];
[arr removeObjectAtIndex:[arr count]-1];
}
Here is a nice macro that will work for either NSMutableArray OR NSArray:
#define reverseArray(__theArray) {\
if ([__theArray isKindOfClass:[NSMutableArray class]]) {\
if ([(NSMutableArray *)__theArray count] > 1) {\
NSUInteger i = 0;\
NSUInteger j = [(NSMutableArray *)__theArray count]-1;\
while (i < j) {\
[(NSMutableArray *)__theArray exchangeObjectAtIndex:i\
withObjectAtIndex:j];\
i++;\
j--;\
}\
}\
} else if ([__theArray isKindOfClass:[NSArray class]]) {\
__theArray = [[NSArray alloc] initWithArray:[[(NSArray *)__theArray reverseObjectEnumerator] allObjects]];\
}\
}
To use just call: reverseArray(myArray);