Add diagonal of 2 dimensional array in Objective C - ios

Given: 2 dimensional array :
[[1 2 3]
[4 5 6]
[9 8 9 ]]
Need to add diagonal of the array : 1+5+9 = 15
NSMutableArray *array = [NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:#1,#2,#3,nil],
[NSMutableArray arrayWithObjects:#4,#5,#6,nil],
[NSMutableArray arrayWithObjects:#9,#8,#9,nil],nil];
NSNumber* total = 0;
for (NSNumber* row in array) {
total = total + array[row][row];
}
NSLog(#"%#",total);
Here I can't access the element of the array. It gives error on "array[row][row]". What is the best way to initialize a 2D array and access the element of the array in Objective-C?

In your code, what you are doing here: for (NSNumber* row in array) is putting each element of array, inside the row variable (this is called array enumeration btw).
What you need is to use the index of the array - not the value of each element (that's what you are doing above).
Also, you don't have to use an object (NSNumber *) for your calculations. A simple NSInteger will do.
Here's the code:
NSMutableArray *array = [NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:#1,#2,#3,nil],
[NSMutableArray arrayWithObjects:#4,#5,#6,nil],
[NSMutableArray arrayWithObjects:#9,#8,#9,nil],nil];
NSInteger total = 0;
for (NSUInteger row = 0; row < array.count; row ++) {
total = total + [array[row][row] integerValue]; // integerValue converts the NSNumber to an NSInteger
}
NSLog(#"%d",total);

Related

Added NSMutableArray elements into another NSMutableArray in jumble way

I have NSMutableArray of 100 elements in it.
I want to load "20 - 50", "10 - 20", "60 - 100" and 50 - 60. elements into separate NSMutableArray and its Index value into another NSMutableArray.
is there away I can load 20 - 50 elements 30 count items after the 10 - 20 elements 10 count items then 60 - 100 items i.e 40 count finally 50 - 60 items 10 count items added into one new NSmutableArray and there index storied value into another NSmutableArray.
Is there a way i can add the items
NSMutableArray *valueArray; // Value array count is 100.
NSMutableArray *indexValue;
NSMutableArray *addValueRangeArray;
for (int i = 0; i< [ valueArray count ]; i ++) {
if (i == 20 && i <= 50 )
{
[addValueRangeArray addObject:[valueArray objectAtIndex:i]];
[indexValue addObject:i];
}
}
Here its not working since for count loop starts 0 to 99
and items added starts from 0
I want to added item with range base where i do get objects added and also the index value too.
Your input are highly appreciated
Let me know if not understand the question.
Since its tricky one.
You can use subarrayWithRange to get specific range from array.
if (valueArray.count >= 100) {
NSMutableArray *rangeArray = [[NSMutableArray alloc] init];
[rangeArray addObjectsFromArray:[valueArray subarrayWithRange:NSMakeRange(20, 30)]];
//and so on.
}
Note: With NSMakeRange passed first parameter as range's starting point and second one is length so pass the number of objects for that range, so for first range 20-50 it is NSMakeRange(20, 30). It may cause you crash if your valueArray doesn't have objects with that range.
You can do it like this
NSArray *arr = [NSArray arrayWithObjects:#"Temp1",#"Temp2",#"Temp3",#"Temp4",#"Temp5",#"Temp6",#"Temp7",#"Temp8",#"Temp9",#"Temp10",#"Temp11",#"Temp12",#"Temp13",#"Temp14",#"Temp15",#"Temp16",#"Temp17",#"Temp18", nil];
// Here create an array of your ranges through which you want your data
NSArray *arrIndex = [NSArray arrayWithObjects:[NSValue valueWithRange:NSMakeRange(3,4)],[NSValue valueWithRange:NSMakeRange(0,4)],[NSValue valueWithRange:NSMakeRange(11,7)],[NSValue valueWithRange:NSMakeRange(7,4)], nil];
NSMutableArray *arrTemp = [NSMutableArray new];
for (int i=0;i<arrIndex.count;i++) {
[arrTemp addObject:[arr subarrayWithRange:[arrIndex[i] rangeValue]]];
}
for (NSArray *arr in arrTemp) {
NSLog(#"Arra - %#",arr);
}
As per your question your range would be
NSArray *arrIndex = [NSArray arrayWithObjects:[NSValue valueWithRange:NSMakeRange(20,30)],[NSValue valueWithRange:NSMakeRange(10,10)],[NSValue valueWithRange:NSMakeRange(60,40)],[NSValue valueWithRange:NSMakeRange(50,10)], nil];

Matching Mutable Array value to index of another Array and getting other Array value at that index

Objective: compare values stored in Mutable array(which are changing constantly) to the index of a static Array. When the values match I would like to add the object(s) of the static array to a new mutable array.
Example:
Values of MutableArray at present state:
(1,2,3)
(Index) - Values of Static Array:
(0) - "Zero"
(1) - "One"
(2) - "Two"
(3) - "Three"
(4) - "Four"
Take values from initial MutableArray and compare them to the static array index's. Output the values at those index's to a new MutableArray
("One","Two","Three")
The initial array is derived by passing the MutableArrayContents for a search via predicate into this:
NSMutableArray *indexArray = [NSMutableArray array];
for (NSMutableArray* obj in _searchResults)
{
if([_questionsArray containsObject:obj] && ![indexArray containsObject:obj])
[indexArray addObject:#([_questionsArray indexOfObject:obj])];
}
IndexArray is the array of "index's".
I've tried for loops but they are not working correctly, any help would be appreciated.
Thanks!
You can try this:
NSArray *staticArr = #[#"Zero",#"One",#"Two",#"Three",#"Four"];
NSArray *otherArr = #[#1,#2,#3];
NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:[otherArr count]];
for(int i = 0; i < [staticArr count]; i++) {
for(int j = 0; j < [otherArr count]; j++) {
if([[otherArr objectAtIndex:j] intValue] == i) {
[array insertObject:[staticArr objectAtIndex:i] atIndex:j];
break;
}
}
}
Try this method
NSArray *staticArr = #[#"Zero", #"One", #"Two", #"Three", #"Four"];
NSArray *otherArr = #[#(1), #(2), #(3)];
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[otherArr count]];
[staticArr enumerateObjectsUsingBlock:^(NSString *string, NSUInteger staticIndex, BOOL *staticStop) {
[otherArr enumerateObjectsUsingBlock:^(NSNumber *number, NSUInteger index, BOOL *stop) {
if (number.integerValue == staticIndex) {
[array insertObject:string atIndex:index];
}
}];
}];
I am typing this on a tab. Please forgive any formatting issues
NSMutableArray *indices; //I am omitting the adding of data, it contains required indices as NSNumber objects
NSArray *staticArr = #[#"One", #"Two", #"Three", #"Four", #"Five"];
NSMutableArray *array = [NSMutableArray new];
for(NSNumber *index in indices) {
NSInteger idx = [index integerValue];
If(idx < staticArr.count)
{
[array addObject:[staticArr objectAtIndex:idx];
}
}
This will be in the order of the elements in indices array and may have repetitions in case there are repetitions in indices array.
This is the most straightforward way, there are many ways to get the subarray using Apple's API

IOS how to compare two array with different values and number of elements

I have two array, array A has 4 elements and array B has 10 elements. How to compare this two array together to find out whether array A has values that contains in array B.
Here is the codes.
for(int i = 0; i <= deepsightSig.count; i++){
for(int p = 0; p <= feeds.count; i++){
if(feeds[i] == deepsightSig[i]){
badIPCount++;
}
else
goodIPCount++;
}
}
NSMutableSet* set1 = [NSMutableSet setWithArray:array1];
NSMutableSet* set2 = [NSMutableSet setWithArray:array2];
[set1 intersectSet:set2]; //this will give you only the obejcts that are in both sets
NSArray* result = [set1 allObjects];
if result.count is greater than one it means array A have values that are in array B.

Sort NSArray in descending order

I have an NSArray with 4 objects, let's say 1, 2, 3 and 4. I want to sort this array in ascending order, but with a randomly selected starting number. For instance; 2, 3, 4 and 1 or 4, 1, 2 and 3.
How can I do this?
What I have thus far:
NSArray *playersArray = [_players allKeys];
NSSortDescriptor *sortPlayerArray = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
playersArray = [playersArray sortedArrayUsingDescriptors:#[sortPlayerArray]];
This results in 1, 2, 3, 4, obviously. I am also able to randomly order the players, like so:
activePlayersArray = [_players allKeys];
NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:activePlayersArray];
int count = (int)[temp count];
for (int i = 0; i < count; ++i) {
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[temp exchangeObjectAtIndex:i withObjectAtIndex:n];
}
activePlayersArray = [NSArray arrayWithArray:temp];
So how can I "combine" these two to get the results I want?
Hope you guys can help me.
Thanks!
This is really an algorithm problem, not an iOS problem. Here are the steps to follow
make a note of your randomly selected number
Sort the array in descending order as you normally would (as in Sort an NSArray in Descending Order)
Then split the array at the location of your special number (similar to How to split an NSArray into two equal pieces?)
after the split create a new array where the second piece now comes first
Another solution is to create a circular array of sorted elements and then traverse the array in reverse order.
I think this is what #Konsol intends, with a couple fixes: (1) it looks like the OP wants the order to be ascending, and (2) the array split in the other answer is at the midpoint. But I think the spirit is correct...
// Start with an unsorted (immutable?) input array of numbers (or any object
// that implements compare:.
// Pick a random location and produce an output array as described by the OP
NSMutableArray *mutableArray = [inputArray mutableCopy]; // if its not mutable already
[mutableArray sortUsingSelector:#selector(compare:)];
NSInteger inputIndex=arc4random_uniform(mutableArray.count);
NSArray *start = [mutableArray subarrayWithRange:NSMakeRange(inputIndex, mutableArray.count-inputIndex)];
NSArray *end = [mutableArray subarrayWithRange:NSMakeRange(0, inputIndex)];
NSArray *outputArray = [start arrayByAddingObjectsFromArray:end];
NSLog(#"%#", outputArray);
int count = (int)[activePlayersArray count];
int n = (arc4random() % nElements) + i;
NSMutableArray *temp = [[NSMutableArray alloc] init];
for (int i = 0; i < count; ++i) {
int nElements = count - i;
[temp addObject:[activePlayersArray objectAtIndex:(n-i)%count]];
}
activePlayersArray = [NSArray arrayWithArray:temp];
Hope it works!

Shuffle Randomize an NSMutableArray excepting item at index0

Have an NSMutableArray, and when my users press a button, I'd like all items in the array to randomly change position, !! except for the first !!.
Right now I have
-(void)shufflemyList{
NSLog(#"Un Shuffled array : %#",myList);
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
while ([myList count] > 0)
{
int index = arc4random() % [myList count];
id objectToMove = [myList objectAtIndex:index];
[array addObject:objectToMove];
[myList removeObjectAtIndex:index]; }
// test
NSLog(#"Shuffled array : %#",array);
myList=array; }
This works to completely shuffle the list.
Is there a way to shuffle the whole list, excepting the first item?
Just add 2 lines
-(void)shufflemyList{
NSLog(#"Un Shuffled array : %#",myList);
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
// new code ---
[array addObject:myList[0]];
[myList removeObjectAtIndex:0];
// ---
while ([myList count] > 0)
{
int index = arc4random() % [myList count];
id objectToMove = [myList objectAtIndex:index];
[array addObject:objectToMove];
[myList removeObjectAtIndex:index]; }
// test
NSLog(#"Shuffled array : %#",array);
myList=array; }
Also it is better to use 'arc4random_uniform(n)' instead of 'arc4random() % n'. From docs:
arc4random_uniform() will return a uniformly distributed random number
less than upper_bound. arc4random_uniform() is recommended over
constructions like ``arc4random() % upper_bound'' as it avoids "modulo
bias" when the upper bound is not a power of two.

Resources