-1

I am supposed to make an app that generates fully complete Sudoku puzzles. I can get the first row to generate properly with the following code, but, no matter what I do, I cannot get the next rows to work right. They all generate the right way in that I get the numbers 1-9 in a random order, but I cannot get it to make a workable Sudoku puzzle.

Code:

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:8];
    for (int integerA = 0; integerA < 10; integerA ++) {
        [array addObject:[NSNumber numberWithInt:integerA]];
        //NSLog(@"%i", (integerA + 1));
    }

 for (int x = 8; x >= 0; x --) {
        [array exchangeObjectAtIndex:(arc4random() % (x + 1)) withObjectAtIndex:x];
        section[x][0] = ([[array objectAtIndex:x] intValue] + 1);
        for (int y = 8; y >= 0; y --) {
            if (0) {

            }
        }
    }

That part works. If I try to make another array and generate the "y" values for each "x" value, it goes all weird. Without numerous conditional statements, is there an efficient way to generate a fully solved Sudoku puzzle?

The "weird results":

2 0 1 | 2 3 3 | 5 2 2
7 0 3 | 2 1 5 | 1 4 4
2 0 1 | 0 3 4 | 6 7 3
 - - - - - - - - - -
8 4 0 | 1 3 6 | 5 2 7
5 0 4 | 3 2 1 | 1 1 1
7 0 0 | 3 1 4 | 6 5 1
 - - - - - - - - - -
2 7 0 | 5 6 3 | 4 1 8
7 6 1 | 1 3 2 | 5 0 5
0 1 1 | 2 3 5 | 0 1 5
6
  • 2
    "2 0 1 | 2 3 3 | 5 2 2" is a proper first row??
    – Wooble
    Dec 21, 2011 at 19:46
  • Not at all. That is my problem. I would really like to have a better way to make this.
    – Justin
    Dec 21, 2011 at 19:47
  • 4
    In order to build a Sudoku you have to solve the Sudoku. What is your algorithm for solving the Sudoku?
    – Hot Licks
    Dec 21, 2011 at 20:01
  • I don't have one. I have to make it start with every single slot filled in correctly.
    – Justin
    Dec 21, 2011 at 20:13
  • 2
    Hey, some of your numbers are repeated multiple times on each row/column. Just wanted to let you know. Dec 21, 2011 at 21:29

2 Answers 2

6

The problem of find a correct Sudoku scheme is a very common homework and it has many different solutions.

I will not provide you the code, but let me give you some suggestions: as you certainly know, the aim is to generate a scheme that has non-repeating numbers in row, column and square.
This is, more basically, the problem of generating random non-repeating numbers. The web is full of solutions for this problem, just a couple of examples here and here.

Now that we are able to generate non-repeating numbers, the problem is to fill the table.

There are many possible approaches: obviously you cannot avoid to check (in some way) that the current number appears only once per row, column, square.


The first solution that comes in my mind is a recursive procedure (let's call it int fill(int row)):

In a do-while loop (I'll explain later why) do this operations:

  • generate an array of random (this is to avoid that the algorithm generates always the same scheme) non-repeating numbers (from 1 to 9)

this is a possible candidate to become the row-esim row of your scheme. Of course, most of the case you will not be such lucky to have your row ready, so you have to check some conditions:

  • for each number in your array check if it's the first time it appears in column and in the square (you do not need to check in the row since you built an array of non-repeating numbers).

I will not explain further how to check since it's almost trivial.
If yes, copy it in your scheme and move it at the end of your array. This way, at the beginning of your array, you will always have non-used numbers.
If no, skip it and try the next one.

Be careful: you must keep the reference of the number of used numbers, otherwise you may use two times the same number in one row.

  • However, this way it is possible to arrive in a situation in which no number seems to fit your table. In this case, simply return 0

  • If, instead, you inserted all 9 numbers in the current row, call int chk = fill(row+1). Of course you must not call the recursive step if you reached the final row (row==9). In this case simply return 1.

chk will store the return value of the recursive step.

  • If chk==0 it means that the algorithm was not able to find a suitable row for the next level. In this case simply restart the initial do-while loop.

  • Otherwise the recursive step was successful, so you can return 1.


However, this is only a possible solutions. There are many others possible algorithms/variations. It's up to you to increase performance and do some optimization.

1
  • This was very helpful. Thanks a lot. When I finish my code (in 10-15 minutes, probably), I will tell you how it turned out. By the way, thanks for not giving me the code. I signed up for programming classes because I like the challenge, but I simply needed a push in the right direction, which you provided.
    – Justin
    Dec 21, 2011 at 22:06
3

For sudoku generates we need to check only three - four step

  1. Get row filled numbers array => rawArray.

  2. Get Column filled numbers array => columnArray.

  3. Get current cell's 3x3 grid array => cellArray.

  4. Create array of 1-9 number (numberArray) and Remove numbers of above three array (rawArray , columnArray , cellArray)

    finalArray = (numberArray) - (rawArray , columnArray , cellArray)

  5. get random number from finalArray

    and placed it to current cell

  6. if any conflicted repeat step 1-5

bellow is code how to generate random sudoku

#import "ViewController.h"

@interface ViewController (){
   NSMutableArray *field;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self genrateSudoku];
}

-(void)genrateSudoku{
    [self fillEmptyGrid];
    @autoreleasepool {
        int n = 3;
        BOOL flag=NO;
        for (int i = 0; i < n*n; i++) {

            for (int j = 0; j < n*n; j++){
                if ([field[i][j] isEqualToString:@"_"]) {
                    if (![self fileValue:i and:j]) {
                        flag=YES;
                        break;
                    }
                }else{
                    continue;
                }
            }
            if (flag) {
                break;
            }
        }

        if (flag) {
            [self genrateSudoku];
        }else{
            NSLog(@"field fill =%@",field);
        }
    }
}
-(void)fillEmptyGrid{
      int n = 3;
    field=[[NSMutableArray alloc]init];
    for (int i = 0; i < n*n; i++) {
        NSMutableArray *a=[[NSMutableArray alloc]init];
        [field addObject:a];
        for (int j = 0; j < n*n; j++){
            [field[i] addObject:[NSString stringWithFormat:@"_"]];
        }
    }
}
-(BOOL)fileValue:(int)i and:(int)j{
    NSMutableArray *rawArray=field[i];
    NSMutableArray *cellArray=[self boxArray:i and:j];
    NSMutableArray *columnArray=[self colArray:i and:j];
    NSString *value =[self getRandomCol:columnArray rowA:rawArray box:cellArray];
    if (value==nil) {
        return NO;
    }else{
        field[i][j]=value;
        return YES;
    }

}

-(NSMutableArray *)boxArray:(int)i and:(int)j {
    int x= (i<3)?0:((i<6)?3:6);
    int y=(j<3)?0:((j<6)?3:6);

    NSMutableArray *ar=[[NSMutableArray alloc]init];

    for (int a=x; a<x+3; a++) {
        for (int b=y; b<y+3; b++) {
            [ar addObject:field[a][b]];
        }
    }
    return ar;
}
-(NSMutableArray *)colArray:(int)i and:(int)j{
    NSMutableArray *ar=[[NSMutableArray alloc]init];
        for (int b=0; b<9; b++) {
            [ar addObject:field[b][j]];
        }
    return ar;
}

-(NSString *)getRandomCol:(NSMutableArray *)col rowA:(NSMutableArray *)row box:(NSMutableArray *)box{
    NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9", nil];

    [array removeObjectsInArray:row];
    [array removeObjectsInArray:box];
    [array removeObjectsInArray:col];
    if (array.count>0) {
        int x=arc4random()%array.count;
        return array[x];
    }
    else{


        return nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.