在索引处添加NSMutableArray的元素以及其他NSMutableArrays的相应元素

时间:2022-07-06 23:11:12

If I have 3 NSMutableArray's, how can I get an array where the element at each index is the sum of the elements at that same index in each of the original arrays?

如果我有3个NSMutableArray,我怎样才能得到一个数组,其中每个索引处的元素是每个原始数组中相同索引处元素的总和?

Example:

MutableArrayOne  = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

MutableArrayTwo  = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

MutableArrayThree  = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];

How do I sum them to an array like:

我如何将它们总结为如下数组:

MutableArrayThree  = [NSMutableArray arrayWithObjects:@"3",@"6",@"9",@"12",@"15", nil];

1 个解决方案

#1


3  

Assuming all arrays are of the same size...

假设所有阵列都具有相同的大小......

NSMutableArray *sums = [NSMutableArray arrayWithCapacity:MutableArrayOne.count];
for(NSInteger i = 0; i < MutableArrayOne.count; i++)
{
    NSInteger element1 = [[MutableArrayOne objectAtIndex:i] integerValue];
    NSInteger element2 = [[MutableArrayTwo objectAtIndex:i] integerValue];
    NSInteger element3 = [[MutableArrayThree objectAtIndex:i] integerValue];
    NSInteger sum = element1 + element2 + element3;
    [sums addObject:[NSString stringWithFormat:@"%lu", sum]];
}

#1


3  

Assuming all arrays are of the same size...

假设所有阵列都具有相同的大小......

NSMutableArray *sums = [NSMutableArray arrayWithCapacity:MutableArrayOne.count];
for(NSInteger i = 0; i < MutableArrayOne.count; i++)
{
    NSInteger element1 = [[MutableArrayOne objectAtIndex:i] integerValue];
    NSInteger element2 = [[MutableArrayTwo objectAtIndex:i] integerValue];
    NSInteger element3 = [[MutableArrayThree objectAtIndex:i] integerValue];
    NSInteger sum = element1 + element2 + element3;
    [sums addObject:[NSString stringWithFormat:@"%lu", sum]];
}