Average of a NSArray and store value in a new NSArray - objective-c

i would like to have the average of my NSArray element and store them in a new array in the following way.
NSArray* number;
NSMutableArray* Average;
[Average objectAtIndex:0]=[number objectAtIndex:0];
[Average objectAtIndex:1]=([number objectAtIndex:0] + [number objectAtIndex:1])/2;
[Average objectAtIndex:2]=([number objectAtIndex:0] + [number objectAtIndex:1] + [number objectAtIndex:2])/3;
i was thinking of doing it using 2 for loops
for (int i =0; i<[number count]; i++){
for (int j=0; j<i; j++){
temp+=[number objectAtIndex:j];
}
[Average addObject: temp/(i+1)];
}
can anyone help me with a more efficient way
thank you

You only need one loop:
NSArray *numbers = #[#(2.4), #(2.7), #(4.0)];
NSMutableArray *averages = [NSMutableArray array];
double total = 0.0;
for (int i = 0; i < [numbers count]; i++) {
total += [[numbers objectAtIndex:i] doubleValue];
[averages addObject:#(total / (i + 1))];
}
or, using fast enumeration:
__block double total = 0.0;
[numbers enumerateObjectsUsingBlock:^(NSNumber *number, NSUInteger idx, BOOL *stop) {
total += [number doubleValue];
[averages addObject:#(total / (idx + 1))];
}];
By the way, unrelated to your question, but if you simply wanted to average all the numbers in the numbers array, you could use KVC collection operator:
NSNumber *average = [numbers valueForKeyPath:#"#avg.self"];
Clearly that's only useful if you wanted to average all the numbers in the array, but it's a convenient shorthand in those situations.

Related

Iterating backwards over an array throwing exception

I am trying to make an add method that works like long addition, so I want to start the addition from the end and work my way backwards so I can get the carrys right and etc. So I am currently trying to start working backwards over the array.
For example what im trying to do.
two arrays with the character 123456789
and i want to add them starting at 9 + 9 then move to 8+8
So I'm pretty sure I'm using the right way to iterate backwards over an array, but everytime I try I get just the runtime error, index out of bounds, and I can't figure out why. Any help would be great, I just cant figure out why it keeps throwing the exception.
-(MPInteger *) add: (MPInteger *) x
{
NSMutableArray *a = self->intString;
NSMutableArray *b = x->intString;
NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];
//for (int i = 0; i < [a count]; i++) {
for (NSInteger i = [a count] - 1; i > 0; i--) {
int num = 10;
NSNumber *ourNum = [NSNumber numberWithInt:num];
NSNumber *total = [NSNumber numberWithInt:[[a objectAtIndex:i] intValue] + [[b objectAtIndex:i] intValue]];
if ([total intValue] >= [ourNum intValue]) {
total = [NSNumber numberWithInt:([total intValue] - [ourNum intValue])];
[c addObject:[NSNumber numberWithInt:([total intValue])]];
} else {
[c addObject:[NSNumber numberWithInt:[[a objectAtIndex:i] intValue]+[[b objectAtIndex:i] intValue]]];
}
NSLog(#"%#", c[i]);
}
return x;
}
First, let's clean up this code.
- (MPInteger *)add:(MPInteger *)x {
NSMutableArray *a = self->intString;
NSMutableArray *b = x->intString;
NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];
for (NSInteger i = [a count] - 1; i > 0; i--) {
int num = 10;
NSNumber *ourNum = #(num);
NSNumber *total = #([a[i] intValue] + [b[i] intValue]);
if ([total intValue] >= [ourNum intValue]) {
total = #([total intValue] - [ourNum intValue]);
[c addObject:#([total intValue])];
} else {
[c addObject:#([a[i] intValue] + [b[i] intValue])];
}
NSLog(#"%#", c[i]);
}
return x;
}
Next, let's remove redundant/duplicate code.
- (MPInteger *)add:(MPInteger *)x {
NSMutableArray *a = self->intString;
NSMutableArray *b = x->intString;
NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];
for (NSInteger i = [a count] - 1; i > 0; i--) {
int num = 10;
NSNumber *total = #([a[i] intValue] + [b[i] intValue]);
if ([total intValue] >= num) {
total = #([total intValue] - num);
}
[c addObject:total];
NSLog(#"%#", c[i]);
}
return x;
}
Now we can clearly see all of the issues.
You're going from [a count] - 1 to 1. You should be going all the way to 0.
a and b might have different sizes, so if you only do [a count] - 1 to 0, then if for example [b count] < [a count], you'll get an index out of bounds error when you try to access b[i].
You're adding stuff to the end of c, but you should be adding it to the beginning of c since you're iterating backwards.
You don't store the carry anywhere.
You are accessing c[i], which doesn't exist.
You are starting with an empty array 'c', and you NSLog c[i] which is obviously out of bounds on the first iteration.

Show object in NSMutableArray of matrix

Following this code:
In ViewController.m
double kk[2][2] = {{1,2},{5,6}};
if (!matrix1Col) {
matrix1Col = [NSMutableArray array];
}
for (int i=0; i<2; i++) {
[matrix1Row removeAllObjects];
if (!matrix1Row) {
matrix1Row = [NSMutableArray array];
}
for (int j=0 ; j<2; j++) {
[matrix1Row insertObject:[NSNumber numberWithDouble:kk[i][j]] atIndex:j];
}
[matrix1Col insertObject:matrix1Row atIndex:i];
}
self.label100.text = [NSString stringWithFormat:#"%f",[[[matrix1Col objectAtIndex:0] objectAtIndex:0] doubleValue]];
self.label110.text = [NSString stringWithFormat:#"%f",[[[matrix1Col objectAtIndex:1] objectAtIndex:0] doubleValue]];
self.label101.text = [NSString stringWithFormat:#"%f",[[[matrix1Col objectAtIndex:0] objectAtIndex:1] doubleValue]];
self.label111.text = [NSString stringWithFormat:#"%f",[[[matrix1Col objectAtIndex:1] objectAtIndex:1] doubleValue]];`
I wanna show object in NSMutableArray of matrix which receive value from matrix of double in label.
And my all label must show as following ->label100 show 1 ->label110 show 5 ->label101 show 2 and ->label111 show 6
but It shows ->label100 show 5 ->label110 show 5 ->label101 show 6 and ->label111 show 6
How can I do?
The problem is that you're always overwriting already inserted objects, as you insert the row many times in the same loop. That's how I would write it:
double kk[2][2] = {{1,2},{5,6}};
NSMutableArray* matrix= [NSMutableArray new];
for(unsigned int i=0; i<2; i++)
{
NSMutableArray* row= [NSMutableArray new];
for(unsigned int j=0; j<2; j++)
{
[row addObject: #(kk[i][j]) ];
}
[matrix addObject: row];
}

Populating array with integers

Let's say I want to populate NSarray with 50 integers. We know that NSarray accept only objects. So I have to do 50 times
NSNumber *num1 = [NSNumber numberWithInit:10];
NSNumber *num2 = [NSNumber numberWithInit:212];
......
NSNumber *num50 = [NSNumber numberWithInit:12];
Is there more elegant way to achieve that, beacause looks stupid 50 lines of code only for create number objects ?
try this...
NSMutableArray *array=[[NSMutableArray alloc]initWithCapacity:50 ];
for (int i=0; i<0; i++) {
NSNumber *number=[[NSNumber alloc] initWithInt:i];
[array addObject:number];
[number release];
}
//do anything with arrray and release the array later.
is this OK or you are seeking anything else.?
How about using NSMutableArray?
NSMutableArray* arr = [[NSMutableArray alloc] init];
int i = 0;
for(i=0; i<50; i++) {
NSNumber* num = [NSNumber numberWithInt:i]; // use i or random numbers
[arr addObject:num];
}
Your numbers do not seem to follow any particular pattern, so you might be better doing this by creating a C array first:
int myValues[] = { 10, 212, ..., 12 };
NSUInteger count = sizeof(myValues)/sizeof(int); // number of integers in myValues
// abstract the following into a function/method/category if doing more than once
NSMutableArray *objcValues = [NSMutableArray arrayWithCapacity:count];
for(NSUInteger ix = 0; ix < count; ix++)
[objcValues addObject:[NSNumber numberWithInt:myValues[ix]];

Retrieve integers by looping through a NSMutableArray

Can someone show me how to retrieve values by looping through a NSMutableArray? My code, which basically adds integer numbers to the array, is below :
NSMutableArray *ptr = [[NSMutableArray alloc] init];
[ptr addObject:[NSNumber numberWithInt:1]];
[ptr addObject:[NSNumber numberWithInt:2]];
[ptr addObject:[NSNumber numberWithInt:3]];
// How to retrieve them as integers?
I'm trying to retrieve each number from the array and sum them up to a total value.
Its actually pretty simple:
int totalValue = 0;
for(NSNumber *number in myArray) // Use fast enumeration to iterate through the array
{
totalValue += [number intValue];
}
I'm also a newbie so my answer may be wrong, but try this:
int sum = 0;
for (int i = 0, i < [ptr count], i++){
int value = [[ptr objectAtIndex:i] intValue] //you get the int, integerValue is applicable for NSInteger
sum = sum + value;//you adding values
}

How to simplify my code... 2D NSArray in Objective C...?

self.myArray = [NSArray arrayWithObjects: [NSArray arrayWithObjects: [self generateMySecretObject], [self generateMySecretObject],nil], [NSArray arrayWithObjects: [self generateMySecretObject], [self generateMySecretObject],nil],nil];
for (int k=0; k<[self.myArray count]; k++) {
for(int s = 0; s<[[self.myArray objectAtIndex:k] count]; s++){
[[[self.myArray objectAtIndex:k] objectAtIndex:s] setAttribute:[self generateSecertAttribute]];
}
}
As you can see this is a simple 2*2 array, but it takes me lots of code to assign the NSArray in very first place, because I found that the NSArray can't assign the size at very beginning. Also, I want to set attribute one by one. I can't think of if my array change to 10*10. How long it could be. So, I hope you guys can give me some suggestions on shorten the code, and more readable. thz
(Some Assumptions: myArray will have a fixed size. It won't grown up or become smaller in the run time.)
Generate the array by -addObject:.
NSMutableArray* myArray = [NSMutableArray array];
for (int k = 0; k < 10; ++ k) {
NSMutableArray* subArr = [NSMutableArray array];
for (int s = 0; s < 10; ++ s) {
id item = (s == 0 && k == 0) ? [self d] : [self generateMySecretObject];
[item setAttribute:[self generateSecertAttribute]];
[subArr addObject:item];
}
[myArray addObject:subArr];
// use [myArray addObject:[[subArr copy] autorelease]] for deep immutability.
}
return [[myArray copy] autorelease];
(Don't query self.myArray many times. Each corresponds to an ObjC call and while someone calls an ObjC call is cheap, it's still not free.)
If the array is a fixed size and each row is the same length then you could uses a 1D array and an offset, EG:
int rowLength = 5;
int rowNumber = 0;
int columnNumber = 3;
[myArray objectAtIndex: (rowLength * rowNumber) + columnNumber];