Sudoku Function returning array of identical boards - objective-c

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.

Related

NSArray not removing objects

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.

NSMutableArray inside setTitle

I've stored 4 unique numbers inside an NSMutableArray from 1-4. i've done that by using this code:
storeArray = [[NSMutableArray alloc] init];
BOOL record = NO;
int x;
for (int i=1; [storeArray count] < 4; i++) //Loop for generate different random values
{
x = arc4random() % 4;//generating random number
if(i==1)//for first time
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
else
{
for (int j=0; j<= [storeArray count]-1; j++)
{
if (x ==[[storeArray objectAtIndex:j] intValue])
record = YES;
}
if (record == YES)
{
record = NO;
}
else
{
[storeArray addObject:[NSNumber numberWithInt:x]];
}
}
}
I can then print the numbers out using storeArray[1] and so on.
the problem is i want to print the numbers inside this.
[option1 setTitle:questions[r][storeArray[0]] forState: UIControlStateNormal];
[option2 setTitle:questions[r][storeArray[1]] forState: UIControlStateNormal];
[option3 setTitle:questions[r][storeArray[2]] forState: UIControlStateNormal];
[option4 setTitle:questions[r][storeArray[3]] forState: UIControlStateNormal];
How can i do this?, cause i when i do this i get thread sigbrt error?
The problem is that your algorithm is faulty and when there are collisions because you are trying to keep the numbers unique, you don't record anything so your array might not always be the expected length. Actually there is a 91% chance of this happening in your case so it looks like it happens all the time.
Instead of trying to write your own algorithm, just use the existing classes. Simply use an NSSet to guarantee the uniqueness of the numbers in your array.
NSMutableSet *set = [[NSMutableSet alloc] init];
while(set.count < 4) {
int x = arc4random() % 4;
[set addObject:[NSNumber numberWithInteger:x]];
}
NSArray * storeArray = [set allObjects];

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 :)

EXC_BAD_ACCESS on getting value from NSValue

I'm constructing a series of MKPolygons and storing them in an array of NSValues:
for (NSDictionary* country in countries) {
NSMutableArray* polygons = [[NSMutableArray alloc] init];
for (NSArray* polygon in [country objectForKey:#"polygons"]) {
CLLocationCoordinate2D polygonCoords[polygon.count];
int i;
for (i = 0; i < polygon.count; i++) {
NSValue* coords = [polygon objectAtIndex:i];
CLLocationCoordinate2D stored_coords;
[coords getValue:&stored_coords];
polygonCoords[i] = stored_coords;
}
MKPolygon* poly = [MKPolygon polygonWithCoordinates:polygonCoords count:polygon.count];
[polygons addObject:[NSValue valueWithBytes:&poly objCType:#encode(MKPolygon)]];
[chillPillMap addOverlay:poly];
}
[country setValue:polygons forKey:#"polygon_objects"];
}
However, when I try to access them later, I get two or three in and a EXC_BAD_ACCESS occurs:
for (NSDictionary* country in countries) {
NSArray* polygon_objects = [country objectForKey:#"polygon_objects"];
int i;
for (i = 0; i < polygon_objects.count; i++) {
MKPolygon* saved_poly = [MKPolygon alloc];
[[polygon_objects objectAtIndex:i] getValue:&saved_poly];
}
}
Not sure why this is.
MKPolygon is an objective-C object. You can put it into the array without converting it to a NSValue. Furthermore, you are telling NSValue to take the value of the bytes, but you are passing it the address of the pointer. Bad news.
Why not just...
[polygons addObject:poly]
then...
MKPolygon *saved_poly = [polygon_objects objectAtIndex:i];

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];