I want to make a two dimensional array in objective-c and initialize all the indexes as zero. whenever my data (2D Coordinate) matches with any row/column then I want to upgrade the respective index by value one. So that later on I can scan for my highly probable coordinate on the basis of maximum number of index at any point. For eg: If my algorithm generates coordinate (0,1), then the index at first row and second column must increase by one. Thanks a lot.
3 Answers
Here is how you create your array.
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSMutableArray arrayWithObjects:@"0",@"0",nil]];
[array addObject:[NSMutableArray arrayWithObjects:@"0",@"0",nil]];
NSLog(@"%@",array);
Update value
Say you want to update index(0,1) with value 3, you do
[[array objectAtIndex:0] replaceObjectAtIndex:1 withObject:@"3"];
NSLog(@"%@",array);
Update index(1,1) with value 4 do
[[array objectAtIndex:1] replaceObjectAtIndex:1 withObject:@"4"];
NSLog(@"%@",array);
Hope it helps.
Cheers.
Comments
Just a suggestion:
Objective-C is a super set of C. So you can make use of the C array concept also.
int array2D[5][5] = {0};//The compiler will automatically intialize all indces to 0.
or use
memset(&a[0][0], 0, sizeof(int) * 5 * 5);
then use the simple C assignment like as follows,
array2D[0][1] = 3;
which is much faster and simple.
Sample Code:
#include<stdio.h>
#include<string.h>
int main(int argc, char * argv[])
{
int a[5][5];
memset(&a[0][0], 0, sizeof(int) * 5 * 5);
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}