NSArray not removing objects - objective-c

I have 5 objects in Array and want to delete 2 in loop but I have a small minor problem in below code
NSMutableArray *totalPages = [[NSMutableArray alloc] init];
[totalPages addObject:#"Test1"];
[totalPages addObject:#"Test2"];
[totalPages addObject:#"Test3"];
[totalPages addObject:#"Test4"];
[totalPages addObject:#"Test5"];
int currentPage = 2;
for (int x = 0; x < [totalPages count]; x++) {
//int pageIds = [[totalPages objectAtIndex:x] intValue];
//NSLog(#"%d",pageIds);
NSLog(#"Array Count %d", (int)[totalPages count]);
NSLog(#"Current Page %d", currentPage);
NSLog(#"Current Iterator Value %d", x);
if (x > currentPage) {
[totalPages removeObjectAtIndex:x];
NSLog(#"Array Count %d", (int)[totalPages count]);
NSLog(#"Number of Pages to be removed %d", x);
}
}
As I want to delete "Test4" and "Test5" but my above code is deleting only "Test5" and if I keep this logic as
if (x >= currentPage)
so it deletes my "Test4" and "Test5" objects but logic fails when int currentPage = 0; so what is the recommended approach to delete Test4 and Test5 as objects in arrays are dynamically added and when currentPage = 0; so Arrays has only 1 Object in it as a pages.

The array is changing as you deleting elements from it, it is getting shortened.
Adjust your for statement and count backwards, that should solve the problem for you.

Related

Error with using local variable to access array index

For some reason this occurs every time i try to access a specific index from the array by specifying a variable int in the index in a forloop. When i do i get a Thread 1 Error, but if i use a variable that has not be declared in the forloop itself than it seem to work fine.
Code:
for(int i =0 ; i<= [array count]; i++) {
NSNumber *convert = [array objectAtIndex:i]; //results in error
NSLog(#"%i", [convert intValue]);
}
Problem is you are trying to access array beyond its capacity. Array starts with 0 index and goes upto array.count - 1. That said, please try with below code and you should be good:
for (int i = 0 ; i <= array.count - 1 ; i++) {
NSNumber *convert = [array objectAtIndex:i];
NSLog(#"%i", [convert intValue]);
}
Another variation could be:
for (int i = 0 ; i < array.count ; i++) {
NSNumber *convert = [array objectAtIndex:i];
NSLog(#"%i", [convert intValue]);
}

Sudoku Function returning array of identical boards

I am writing a recursive Sudoku solver and I am having some issues with 2D array handling. I included the function which is giving the trouble. There are some unnecessary lines I was using for debugging in there.
- (Stack *)successors
{
Stack *stack = [[Stack alloc] init];
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *test = [[NSMutableArray alloc] init];
temp = [self.board copy];
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
if ([self.board[x][y] isEqualToString:#""] ||
[self.board[x][y] isEqualToString:#"."]) {
NSLog(#"%d %d", x, y);
for (int i = 1; i < 10; i++) {
NSLog(#"%d", i);
[temp[x] setObject:[NSString stringWithFormat:#"%d", i] atIndex:y];
State *tempState = [[State alloc] initWithBoard:temp];
if ([tempState legal]) {
NSMutableArray *input = [NSMutableArray arrayWithArray:temp];
[stack push:input];
[stack push:input];
[test addObject:input];
}
}
NSLog(#"test %#", test);
int p = [stack size];
for (int i = 0; i < p; i++) {
NSLog(#"%#", [stack pop]);
}
return stack;
}
}
}
return stack;
}
essentially, it begins at the top of the array and if the space is empty, it tries putting in the number 1 through 9 and if it is legal, based on another function I wrote previously, it will input it in the temp array and add it to the stack. I checked this and it works great. However, after adding them all together, I NSLog to check the stack and find that all of the stacked arrays now begin with the number 9, the last number checked in the temp array. I believe I am having some issue with keeping reference to the temp array, but I cannot figure it out. Any help is great.

Array - find how many times an object repeats consecutively

My array objects are as follows:
10,10,10
20,23,14
10,10,10
10,10,10
10,10,10
32,23,42
32,23,42
10,10,10
32,23,23
32,23,23
How can I go through this array and find out how many times the same object repeats sequentially, then add a , and the number of times it repeats?
Then save a new array with objects like:
10,10,10,1
20,23,14,1
10,10,10,3
32,23,42,2
10,10,10,1
32,23,23,2
Any help would be appreciated.
Thanks!
Try this:
NSMutableArray *outArray = [[NSMutableArray alloc] init];
for (NSUInteger j = 0; j < [theArray count]; j++) {
id object = [theArray objectAtIndex:j];
NSUInteger repeats = 1;
while (j + 1 < [theArray count] && [[theArray objectAtIndex:j + 1] isEqual:object]) {
j++;
repeats++;
}
[outArray addObject:object];
[outArray addObject:[NSNumber numberWithUnsignedInteger:repeats]];
}
return outArray;
This can also be done in place if the input array is mutable. I leave that as an exercise for the reader.
Break up every three integers into its own array (make sure they are strings).
Then iterate through each one of those arrays, and input into an NSMutableDictionary, the key is the string (your number), the value is a counter (if seen once, add 1, etc...)
Keep a pointer to the highest key (if newCount > highestCountPointer, then highestCountPointer=newCount)
At the end of that iteration, add the number that the highestCountPoints to to the end of the array.
I'm not an Objective C programmer, so please pardon any language gaffes. Something like the following should do the job:
NSMutableArray *result = [[NSMutableArray alloc] init];
id pending = nil;
NSUInteger count = 0;
for (NSUInteger i = 0; i < [theArray count]; i++) {
id object = [theArray objectAtIndex:i];
if ([object isEqual:pending]) {
count++;
} else {
if (pending != nil) {
[result addObject:[NSString stringWithFormat:#"%#,%d", pending, count]];
}
pending = object;
count = 1;
}
}
if (pending != nil) {
[result addObject:[NSString stringWithFormat:#"%#,%d", pending, count]];
}
Just run "uniq -c" from command line :)

Randomly select x amount of items in a "list"

I would like to select x amount of items randomly from a "list" in objective C store them in an other "list" (each item can only be selected one) , I'm talking about lists because I'm coming from Python. What would be the best way to store a list of strings in Objective C ?
cheers,
You should use NSMutableArray class for changeable arrays or NSArray for non-changeable ones.
UPDATE: a piece of code for selecting a number of items from an array randomly:
NSMutableArray *sourceArray = [NSMutableArray array];
NSMutableArray *newArray = [NSMutableArray array];
int sourceCount = 10;
//fill sourceArray with some elements
for(int i = 0; i < sourceCount; i++) {
[sourceArray addObject:[NSString stringWithFormat:#"Element %d", i+1]];
}
//and the magic begins here :)
int newArrayCount = 5;
NSMutableIndexSet *randomIndexes = [NSMutableIndexSet indexSet]; //to trace new random indexes
for (int i = 0; i < newArrayCount; i++) {
int newRandomIndex = arc4random() % sourceCount;
int j = 0; //use j in order to not rich infinite cycle
//tracing that all new indeces are unique
while ([randomIndexes containsIndex:newRandomIndex] || j >= newArrayCount) {
newRandomIndex = arc4random() % sourceCount;
j++;
}
if (j >= newArrayCount) {
break;
}
[randomIndexes addIndex:newRandomIndex];
[newArray addObject:[sourceArray objectAtIndex:newRandomIndex]];
}
NSLog(#"OLD: %#", sourceArray);
NSLog(#"NEW: %#", newArray);

How to simplify my code... 2D NSArray in Objective C...?

self.myArray = [NSArray arrayWithObjects: [NSArray arrayWithObjects: [self generateMySecretObject], [self generateMySecretObject],nil], [NSArray arrayWithObjects: [self generateMySecretObject], [self generateMySecretObject],nil],nil];
for (int k=0; k<[self.myArray count]; k++) {
for(int s = 0; s<[[self.myArray objectAtIndex:k] count]; s++){
[[[self.myArray objectAtIndex:k] objectAtIndex:s] setAttribute:[self generateSecertAttribute]];
}
}
As you can see this is a simple 2*2 array, but it takes me lots of code to assign the NSArray in very first place, because I found that the NSArray can't assign the size at very beginning. Also, I want to set attribute one by one. I can't think of if my array change to 10*10. How long it could be. So, I hope you guys can give me some suggestions on shorten the code, and more readable. thz
(Some Assumptions: myArray will have a fixed size. It won't grown up or become smaller in the run time.)
Generate the array by -addObject:.
NSMutableArray* myArray = [NSMutableArray array];
for (int k = 0; k < 10; ++ k) {
NSMutableArray* subArr = [NSMutableArray array];
for (int s = 0; s < 10; ++ s) {
id item = (s == 0 && k == 0) ? [self d] : [self generateMySecretObject];
[item setAttribute:[self generateSecertAttribute]];
[subArr addObject:item];
}
[myArray addObject:subArr];
// use [myArray addObject:[[subArr copy] autorelease]] for deep immutability.
}
return [[myArray copy] autorelease];
(Don't query self.myArray many times. Each corresponds to an ObjC call and while someone calls an ObjC call is cheap, it's still not free.)
If the array is a fixed size and each row is the same length then you could uses a 1D array and an offset, EG:
int rowLength = 5;
int rowNumber = 0;
int columnNumber = 3;
[myArray objectAtIndex: (rowLength * rowNumber) + columnNumber];