Array of arrays with ints - objective-c

How would you go about storing a 2 dimensional array of ints as a class variable?
If you want an array of ints you go:
Class declaration
int * myInts;
Implementation
int ints[3] = {1,2,3};
myInts = ints;
But what if you want to store an array of arrays with ints?
Like this:
int ints[3][3] = {{1,2,3}, {1,2,3}, {1,2,3}};
I don't wanna limit the size of the arrays in the class declaration so I guess I have to go with pointers, but how?

For future reference, this is my conclusion:
Class declaration
int ** ints;
Implementation
int rows = 2;
int cols = 5;
ints = (int**)malloc(rows*sizeof(int*));
ints[0] = (int*)malloc(cols*sizeof(int));
ints[0][0] = 123;
ints[0][1] = 456;
ints[0][2] = 789;
// etc
This is my own interpretation of links provided in comments and my C skills are pretty low so take that into consideration ;) Maybe there are better ways to put in multiple numbers at a time with {123,456,789} or something, but that is beyond my requirements for now!

I've wrote sample for you:
int N = 10, M = 15;
NSMutableArray *ints = [NSMutableArray arrayWithCapacity:N]; // array[N][M]
for (int i=0; i<N; i++)
{
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:M];
for (int j=0; j<M; j++)
{
[arr addObject:[NSNumber numberWithInt:(i+1)*(j+1)]];
}
[ints addObject:arr];
}
// print
for (int i=0; i<[ints count]; i++)
{
NSString *line = #"";
NSMutableArray *arr = [ints objectAtIndex:i];
for (int j=0; j<[arr count]; j++)
line = [NSString stringWithFormat:#"%# %#", line, [arr objectAtIndex:j]];
NSLog(#"%#", line);
}

If you want to dynamically allocate memory, in other words define the size of the arrays at runtime, then you need to declare the array as a pointer, malloc it, and then add another array of ints to each index at runtime. You can't really declare and dynamically allocate at the class level. If you are using cocoa/iphone sdk you can use NSMutableArray.
You could also create your own class that constructs a two dimensional array and exposes methods to push and pop int objects like [IntegerArray push:x,y,n];
Here's and example of using a double reference as Daniel R Hicks pointed out.

Related

Objective C, maze generation and 2D arrays

I need to generate a random maze with given width and height. I could do this in Perl with Depth-first search algorithm, in which I use 2D arrays, something like this:
for my $i (0 .. $h - 1) {
for my $j (0 .. $w - 1) {
push #{ $cell[$i] }, '1';
}
push #{ $cell[$i] }, '0';
}
for my $i (0 .. $w) {
$cell[$h][$i] = '';
}
While in Objective C, there's no 2D array. I'm kind of lost now. What is the equivalent of 2D array in Objective C so that I pretty much can use the same data structure as in Perl?
Thanks.
One way is to use Objective-C style array:
NSMutableArray *cell = [NSMutableArray arrayWithCapacity:h];
for (int i=0; i<h; ++i) {
NSMutableArray *row = [NSMutableArray arrayWithCapacity:w];
for (int j=0; j<w; ++j) {
// use a random number
[row addObject:[NSNumber numberWithInt:rand()]];
}
// add one row
[cell addObject:row];
}
Another way is just to use C style array:
int **cell = malloc(h*sizeof(int *));
for (int i=0; i<h; ++i) {
cell[i] = malloc(w*sizeof(int));
for (int j=0; j<w; ++j) {
cell[i][j] = rand();
}
}
// after you used it remeber to free it
for (int i=0; i<h; ++i) {
free(cell[i]);
}
free(cell);
cell = NULL;
Use this github library to generate maze.
https://github.com/DoubleEqual/MazeGenerator-tool
The result looks like this for 24x24 maze:
A 2-Dimentional or N-Dimentional arrays are nothing but a way to store the data. If you want a 2-D array its fairly simple, but little bit tricky in obj-c, you have to creates 2nd level arrays, then insert it into first level.
See the code below :
NSMutableArray *twoDArray = [NSMutableArray new]; //this is first level
//below are second level arrays inserted in index 0 to 2.
[twoDArray insertObject:[NSMutableArray arrayWithObjects:#"00",#"01",#"02",nil] atIndex:0];
[twoDArray insertObject:[NSMutableArray arrayWithObjects:#"10",#"11",#"12",nil] atIndex:1];
[twoDArray insertObject:[NSMutableArray arrayWithObjects:#"20",#"21",#"22",nil] atIndex:2];

Shuffling an array of NSNumbers & converting back to ints

I have an NSMutableArray urlArray of size n, I want to randomly choose 4 of these URLs from the total number of elements in the array.
However I don't want to shuffle urlArray directly, I'd prefer to make an "indexArray" [0 ... (n-1)] & shuffle these, & then use the first 4 elements of the shuffled indexArray to decide which elements I choose from urlArray.
First off I created the indexArray as follows:
for (int i = 0; i < numberOfStems; i++) {
[indexArray addObject:[NSNumber numberWithInteger:i]];
}
This allowed me to shuffle my indexArray, so far so good. Because I used the
[NSNumber numberWithInteger:i] method, the elements in the shuffled indexArray are NSNumbers.
Is there a way to convert the NSNumber objects in indexArray into ints?
I attempted to use the intValue function but this didn't appear to be what I needed.
I also tried creating a c style array but that wasn't so successful either - I'd like to stick with objective-c syntax if possible.
Any ideas? any hints appreciated :)
Why don't you just create a normal c array, shuffle that and then use the first four integers in the array as the for random index?
something like
int* index = malloc(numberOfStems*sizeof(int));
for (int i = 0; i < numberOfStems; ++i)
{
index[i] = i;
}
for (int i = numberOfStems - 1; i > 0; --i)
{
int randomIndex = arc4random() % i;
int tmp = index[i];
index[i] = index[randomIndex];
index[randomIndex] = tmp;
}
now use index to access the URL's
EDITED: updated algorithm (although not really related to OP question)
For a temporary array that stores only integers and gets thrown away after a relatively short task I would definitely prefer a C-style array: this would avoid a great deal of overhead, and is also simple to read.
int *array = (int*)malloc(sizeof(int)*numberOfStems);
for (int i = 0 ; i != numberOfStems ; i++) {
array[i] = i;
}
// Do the shuffle
// Pick first four, and do whatever you need to do
// ...
// Now that you are done with the array, do not forget to free it:
free(array);

Passing NSArray to a cpp function

I need to call a cpp function like
void myFunc(float **array2D, int rows, int cols)
{
}
within an objective-c object. Basically, the array is created in my objective-c code as I create an NSArray object. Now, the problem is how to pass this array to my cpp function.
I am a bit new to these mixed c++/objective-c stuffs so any hint will be highly appreciated.
Thanks
I guess you have to convert the NSArray to a plain C array.
Something like:
NSArray *myNSArray; // your NSArray
int count = [myNSArray count];
float *array = new float[count];
for(int i=0; i<count; i++) {
array[i] = [[myNSArray objectAtIndex:i] floatValue];
}
or, as a commenter suggested (assuming your NSArray contains NSNumbers):
NSArray *myNSArray; // your NSArray
int count = [myNSArray count];
float *array = new float[count];
int i = 0;
for(NSNumber *number in myNSArray) {
array[i++] = [number floatValue];
}
Look at this post.
Check out the answer that mentions using [NSArray getObjects] to create a c-style array.
Here's the code that the poster put in there:
NSArray *someArray = /* .... */;
NSRange copyRange = NSMakeRange(0, [someArray count]);
id *cArray = malloc(sizeof(id *) * copyRange.length);
[someArray getObjects:cArray range:copyRange];
/* use cArray somewhere */
free(cArray);
Alternately, since CFArray is toll-free bridged to NSArray, could you call those C functions from your C++ function? I'd look around, wouldn't be surprised if there weren't a C++ wrapper to give similar semantics, or one could be written easily enough.

Declare Dynamic Array

How can I declare dynamic array? For example:
int k=5;
I want to have an array like below:
int myArray[k];
if i read the question right.. (unlikely at this point)
NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:k];
Sometimes true arrays (not NSArray) are really needed. See for example indexPathWithIndexes:length: in NSIndexPath, it take array of uintegers as parameter. For array allocation you should use the following approach:
NSUInteger *arr = (NSUInteger*)malloc(elementsCount * sizeof(NSUInteger) );
arr[0] = 100;
free(arr);
In Objective-C, the standard way to do this is to use the NSMutableArray class. This is a container that can hold any object (note that int is not an object! You'll have to wrap your integers in NSNumber.) Quick example:
NSMutableArray* someIntegers = [[NSMutableArray alloc] initWithCapacity:1];
[someIntegers addObject:[NSNumber numberWithInt:2]];
//I've added one thing to my array.
[someIntegers addObject:[NSNumber numberWithInt:4]];
//See how I can put more objects in than my capacity allows?
//The array will automatically expand if needed.
//The array now contains 2 (at index 0) and 4 (at index 1)
int secondInteger = [[someIntegers objectAtIndex:1] intValue];
//Retrieving an item. -intValue is needed because I stored it as NSNumber,
//which was necessary, because NSMutableArray holds objects, not primitives.
Well in my book it's ok to use VLAs in Objective-C.
So something like
int foo = 10;
int bar[foo];
is allowed. Of course this is not a dynamic array as in automatically adjusting its size. But if you only need a native array on the stack that's fine.
You can use Objetive-C++.
First rename your class like this: MyClass.mm the ".mm" extension tells Xcode that this clas is a Objetive-C++ class, not a Objetive-C class.
then you can use dynamics C++ arrays like this:
int *pixels = new int[self.view.size.width];
for (int offset = 0; offset = self.view.size.width; offset++) {
pixeles[offset] = rawData[offset];
}
then you can pass "pixels" in a method:
Scan *myScan = [[Scan alloc] initWhithArray:pixels];
the method "initWithScan" is declared like this:
-(id)initWithArray:int[]pixels;
the "initWithScan" implementation is like this:
-(id)initWithScan:int[]pixels {
if (self = [super init]) {
for (int i = 0; i < self.myView.size.width; i++) {
NSLog(#"Pixel: %i", pixels[i];
}
}
return self;
}
I hoppe this was useful.

Multidimensional arrays - what's the most convenient way to work with them in Objective-C?

I'm a beginner in Objective-C and I'm trying to find the most convenient way to work with multidimensional arrays in Objective-C. Either I am missing something or they are very ugly to work with.
Let's say we have a classic problem:
read input from file; on the first line, separated by space(" ") are the width and height of the matrix (eg: 3 4)
on the following lines there is the content described by the values above
Eg:
3 4
a b c d
e f g h
i j k l
The first solution I thought of was:
NSMutableArray *matrix = [[NSMutableArray alloc] initWithCapacity: x]; //x = 3 in this specific case
NSMutableArray *cell;
for(cell in matrix)
{
cell = [NSMutableArray initWithCapacity: y];
for(int i = 0; i < y; i++) // y = 4
{
//object is a NSString containing the char[i][j] read from the file
[cell insertObject:object atIndex: i];
}
}
This was the first thing I had in mind when thinking about how I should get my values read from file in a multidimensional array. I know you can use C arrays, but since I will store NSObjects in it, I don't think is such a great idea. Nonetheless, from my point of view is easy to work with C arrays rather the solution I got with Objective-C.
Is there another way you could build a multidimensional array in obj-c and easier than the one above?
How about looping them?
I know I can do something like
NSArray *myArray;
for(int i=0; i < [array count]; i++)
{
[myArray arrayWithArray: [array objectAtIndex: i]];
for(int j=0; j < [myArray count]; j++)
{
NSLog(#"array cell [%d,%d]: %s", i, i, [myArray objectAtIndex: j]);
}
}
But that is still more complicated than your average C multidimensional array loop.
Any thoughts on this?
Objective-C is a superset of C, if you want to work with multidimensional arrays like you would in C, do it that way. If you want to work with objects doing it the Cocoa way, then that's fine too, but you will write more code to do it.
Can you not simply make an array of id?
#import <Foundation/Foundation.h>
int main(int argc, char **argv) {
id ptr[3][4];
NSObject *p;
ptr[0][0] = p;
}
You can do nothing more with NSArray or NSMutableArray in this regard. That is there is nothing like objectAtIndex:i :j
You can always create one-dimensional arrays of the size width * height instead:
const int size = width*height;
NSMutableArray *array = [NSMutableArray arrayWithCapacity:size];
for (int i=0; i<size; ++i) {
NSString *string = [NSString stringWithFormat:#"col=%d, row=%d", i%width, i/width];
[array insertObject:string atIndex:i];
}
Nobody uses direct multi-dimensional arrays of any size in any computer language (except for homework). They simply use too much memory and are therefore too slow. Objective-C is an object-oriented language. Build a class that does what you need.