How do I create a multidimensional array? - objective-c

I need to keep 90x90 array data for iphone app. how can i keep this data? making an multi-dimensional array is a solution for this big table. or is there an other solution.

If the matrix is always 90x90, then you should just use C arrays.
Unless you have a special need for passing the matrix around, searching using predicates, or need some other feature of NSArray, then keep it simple.

You can:
Use a single Obj-C array containing 8100 elements and map your rows and columns onto the single index yourself: index = (row * 90) + column;
Create an Obj-C array containing 90 Obj-C arrays of 90 elements each.
Hash the row and column together into a single key that you can use with a dictionary. This could be a good solution especially if the array is sparse.
Use a single- or multi-dimensional C array, especially if the elements of the array are plain old C types, like int. If you're storing objects, it's better to go with an Obj-C container.

Iphone's have a built in database SQL-Lite. I'd look into that to see if it meets you needs

Related

Getting the size of each dimension of multidimensional array

Let's say I want to write a function to "unpack" (store or log, perhaps) a multidimensional array using nested loops. The concept is simple enough, provided I'm able to determine, in the case of a 3D array, the length, width and height of the array.
In Objective-C, is there some way to, after being passed a multidimensional array of unknown size as a method argument, determine what those dimension sizes are? Then it'd be a simple matter of using, as stated, nested for loops.
NSArray is inherently one dimensional, a vector if you like, and as noted by John it has a count property. To simulate a multidimensional array you could of course have a NSArray *rows that contains a number of NSAarray *columnElement and so forth. This is not really a multi diensional array and more like a tree type structure but you could sort of call it an array. But I do not think that is what you are asking.
I think you are thinking of a C style buffer of memory traversed by pointer references. This is also inherently a one dimensional structure as memeory adressing is one dimensional. In many cases such a buffer can be viewed as 2 or more dimensional in such way that you say every 50 bytes is a row, so position 0 is row 1 col 1, position 49 is row 1 col 50 and position 50 is row 2 col 1 etc.
In this case as it is you as the designer who have defined this interpretation of the buffer as a two-dimensional array there cannot be a way to derive the structure from the buffer alone. Either you have to store the arrangement of the buffer as metadata in other variables or impose some form of delimeter characters in the buffer, e.g. newline for new row. and comma for new column element or similar (but then it is no longer an array in my opinion it is a file format, here a csv file).

Why do we use multiple dimensional arrays?

I have an understanding about how multiple dimensional arrays work and how to use them except for one thing, In what situation would we need to use them and why?
Basically multi dimension arrays are used if you want to put arrays inside an array.
Say you got 10 students and each writes 3 tests. You can create an array like: arr_name[10][3]
So, calling arr_name[0][0] gives you the result of student 1 on lesson 1.
Calling arr_name[5][2] gives you the result of student 6 on test 3.
You can do this with a 30 position array, but the multi dimension is:
1) easier to understand
2) easier to debug.
Here are a couple examples of arrays in familiar situations.
You might imagine a 2 dimensional array is as a grid. So naturally it is useful when you're dealing with graphics. You might get a pixel from the screen by saying
pixel = screen[20][5] // get the pixel at the 20th row, 5th column
That could also be done with a 3 dimensional array to represent 3d space.
An array could act like a spreadsheet. Here the rows are customers, and the columns are name, email, and date of birth.
name = customers[0][0]
email = customers[0][1]
dateofbirth = customers[0][2]
Really there is a more fundamental pattern underlying this. Things have things have things... and so on. And in a sense you're right to wonder whether you need multidimensional arrays, because there are other ways to represent that same pattern. It's just there for convenience. You could alternatively
Have a single dimensional array and do some math to make it act multidimensional. If you indexed pixels one by one left to right top to bottom you would end up with a million or so elements. Divide by the width of the screen to get the row. The remainder is the column.
Use objects. Instead of using a multidimensional array in example 2 you could have a single dimensional array of Customer objects. Each Customer object would have the attributes name, email and dob.
So there's rarely one way to do something. Just choose the most clear way. With arrays you're accessing by number, with objects you're accessing by name.
Such solution comes as intuitive when you are faced with accessing a data element identified by a multidimensional vector. So if "which element" is defined by more than two "dimensions".
Good uses for 2D or Two D arrays might be:
Matrix Math i.e. rotation things in space on a plane and more.
Maps like game maps, top or side views for either actual graphics or descriptive data.
Spread Sheet like storage.
Multi Columns of display table data.
Kinds of Graphics work.
I know there could be much more, so maybe someone else can add to this list in their answers.

Is there any built in method for sorting in Objective-c?

I have two sorted NSMutableArrays (or I can use any other collection, not critical), I need to insert objects from the first array to the second and preserve sort order in the second array. What is the optimal (fastest) method to do that? I can implement all the known good algorithms, but my question is, if there is already some built-in method? If not, what is the best algorithm in my case?
The real answer would be: it depends, since you are asking: what is the fastest way of inserting objects from one array into another while preserving sort order.
There is no built in way of inserting in the right place of a sorted array. You can achieve the same effect by just adding the two arrays together but it won't be "the fastest way".
What is actually faster depends on many things like: how much data does the arrays contain, what is the ratio of data in array1 vs array2 (does one array contain much more data than the other)?, etc.
NOTE: You should probably begin with the simple solution and only optimize once you experience performance problems. Do measurements with a large data set though, to see that your solution works with whatever data your users may have.
Inserting items from one sorted array into another sorted array
If you want to merge the two arrays by inserting objects in the right place then normal algorithms apply. You should insert the smaller array into the bigger array and try to insert entire sorted sequences where possible instead of every item one by one.
For best performance you should try to make a batch insert using insertObjects:atIndexes: instead of inserting the object one by one.
You can use indexOfObject:inSortedRange:options:usingComparator: to find the index that each item should be inserted in the other array if you specify NSBinarySearchingInsertionIndex for the options. Also, the comparator you are using must be the same as the comparator that sorted the array, otherwise the result is "undefined".
With this in mind you would do something like this
Create mutable index
For every ITEM in SMALLER ARRAY
Find the index where to insert ITEM in LONGER ARRAY
Add (the insertion location + the location in the short array) as the index in the mutable set.
Next item.
Batch insert all items.
The documentation for insertObjects:atIndexes: tells you that "the corresponding location specified in indexes after earlier insertions have been made." Which in your case with two sorted array mean all items with a lower index will already have been added and thus you should add the index of the object in the short array to the value returned from indexOfObject:inSortedRange:options:usingComparator:.
Another (probably very premature optimization) you can do is decrease the sortedRange for every item in the loop so that you don't have to search through parts of the array that you know the item to be inserted is bigger than.
There are probably many other optimizations that can be made. You should still measure first! Hopefully this will get you started.
NSArray *newArray=[firstArray arrayByAddingObjectsFromArray:secondArray];
newArray = [newArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
I would start by simply adding all of the objects of the first array to the second and then resorting the second. Time how long it takes. If it is acceptable, stop there.
If not, you could try a binary search to find the insertion point in the second array for each item in the first array. Since both arrays are sorted, you might be able to optimise the search by using the last insertion point as the lower bound each time round. Something like this:
NSInteger insertionPoint = -1;
for (id object in array1)
{
insertionPoint = [self binarySearch: array2 for: object lowerBound: insertionPoint + 1];
[array2 insertObject: object atIndex: insertionPoint];
}
The Cocoa class NSSortDescriptor together with sortedArrayUsingDescriptors: from NSArray should do what you are after.
Since you are using mutable arrays, you might want to use sortUsingDescriptors: which sorts the mutable array without creating a new one.
Look at the documentation here to see if any of the NSArray sort methods work for you. http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html. You can scroll down to the methods and there's 7 built-in ones for sorting. You could probably just combine the two arrays and run the sortedArrayUsingComparator: or one of the other methods.

Shuffling two NSMutableArrays in a predictable manner

I have two NSMutableArrays of strings that I wish to combine and shuffle together. However, I want it so that every time it shuffles the original two arrays, it always yields the same array in the same order. How can this be done?
Could I seed some constant value into the random function like in C++ srand(constant) but in Objective-C?
Edit: Or say I just have one array (not sure if this makes any difference) and I wanted to shuffle that one array in a predictable manner?
The way to do it is just to do srandom(constant) and use the random() function in Objective C. This way you'll always get the same shuffle and random values.

vb.net remove a row in two-dimensional array

In vb.net how do you delete a row in a two dimensional array?
If you need to remove items from an array you probably shouldn't use an array but should be using a list of some kind (List(Of List(Of String)) or something.
If you do want to stick with the array, there's two different solutions described on this page, one slow shift everything by hand and one faster that copies the memory. The samples are for one dimensional arrays but should be fairly easy to adapt.
If it is the last row you want to remove and you are using the second dimension to represent rows, you can use ReDim with the preserve option like so:
Dim myArray(2,1)
ReDim Preserve myArray(2, 2)
Warning: I suggestion you check out this article before using the above example: The Redim Preserve Performance Trap
If you need to remove a row in the middle, you are going to have to shift everything down a row first, then truncate the last dimension of the array.
This coupled with the need to pivot your concept of rows to the second dimension probably makes it more trouble than it is worth. Chances are, you are using the wrong type in the first place if you need to arbitrarily delete items like that. Traditional arrays (especially multi-dimensional ones) are really best used for fixed-size data sets.