Sudoku Program

Write a Sudoku validator for 4x4 grids made up of 2x2 regions instead of 9x9 grids made up of 3x3 regions. Sudoku puzzles that use 4x4 grids only use the numerical digits 1 through 4 instead of 1 through 9.
Things to Remember:
-Dont use arrays
-Input 16 values into 16 seperate variables
-Try using only if and if/else statements
Outcome should look something like this:
Welcome to the Sudoku Checker v1.0!
This program checks simple, small, 4x4 Sudoku grids for correctness. Each column, row and 2x2 region contains the numbers 1 through 4 only once.
To check your Sudoku, enter your board one row at a time, with each digit separated by a space. Hit ENTER at the end of a row.
Enter Row 1: 1 2 3 4
Enter Row 2: 3 4 2 1
Enter Row 3: 1 2 3 4
Enter Row 4: 4 3 2 1
Thank you. Now checking ...
REG-1:GOOD
REG-2:GOOD
REG-3:GOOD
REG-4:GOOD
ROW-1:GOOD
ROW-2:GOOD
ROW-3:GOOD
ROW-4:GOOD
COL-1:BAD
COL-2:BAD
COL-3:GOOD
COL-4:GOOD
SUDO:INVALID

I built a generic sudoku solver which not only validates, but suggests moves /solves an n x m (dimensions can be different and arbitrary) board by using an int[m][n] array for entered value and a Set<Integer>[m][n] for the possibilities. I added a method called runRules() and created rules off of the following two abstract classes.
package tjacobs.games.sudoku;
Remove possible values on cell row,col using the entered values in the board
public abstract class AbstractCellRule {
     public abstract void runCellRule(SudokuBoard sudoku, int[][] board, int row, int col);
package tjacobs.games.sudoku;
import java.awt.Rectangle;
For rules dealing with a range (row, column, box) in general, not focused on 1 particular cell
public abstract class AbstractRangeRule {
     public abstract void runRangeRule(SudokuBoard sudoku, int[][] board, Rectangle bounds);
}

Similar Messages

  • My sudoku program, any comments, improvements appreciated

    Hi all,
    So I've been refining my amateur-ish programming skills for around a month, and have been writing a C++ program that solves sudoku. (My background is in physics.) I realize there are a lot of mathematical sides in sudoku, but I'm concentrating on the programming side and not too much on the math/brain side. Now the program is basically finished (I hope!) and I just thought the hackers here can have a look and see if there are any things I can improve.
    The link is here: http://ifile.it/jkr56v8/Sudoku.tar
    Basically, a sudoku is an instance of Board, an abstract base class with the pure abstract function Go(). Any concrete class derived from it is essentially a strategy. I think this design pattern is called strategy?
    I've implemented two basic strategies, BruteForce and Priority. BruteForce does the good old sudoku brute force algorithm, which use trial-and-error from the top left box to the bottom right box all possibilitiies until the correct one is found. Priority does basically the same as BruteForce, except instead of trying from top left to bottom right, it plugs numbers in the box that has the most filled "associated" boxes.
    To accommodate "composite strategies," I implemented the prototype pattern, so for example, I can write
    void HyperBF::Go(void)
    BruteForce::Go();
    When a solution is found, I throw an exception to notify the main program, am I correct in that this is a clear and elegant use? Or is it a misuse and an alternative should be considered?
    To actually choose a strategy, I created an abstract factory, a singleton. I'm aware there are all the advice out there that says don't use a singleton unless absolutely necessary? So, should I use a singleton in this case? Also, I think my implementation of the singleton leads to a bug, which is the only known bug: when I put a completed sudoku as input, it gives the output as usual, but gives a segmentation fault afterwards:
    ./Sudoku Puzzle/test_1_Basic.psv BruteForce | tail -n 12 | head -n9 | tee completed
    |5|1|8|2|9|6|7|3|4|
    |3|9|7|8|4|1|2|6|5|
    |6|4|2|5|7|3|1|9|8|
    |1|5|6|4|2|7|3|8|9|
    |4|7|9|3|6|8|5|1|2|
    |8|2|3|9|1|5|6|4|7|
    |7|8|4|1|3|2|9|5|6|
    |2|3|5|6|8|9|4|7|1|
    |9|6|1|7|5|4|8|2|3|
    ./Sudoku completed BruteForce
    Starting configuration:
    |5|1|8|2|9|6|7|3|4|
    |3|9|7|8|4|1|2|6|5|
    |6|4|2|5|7|3|1|9|8|
    |1|5|6|4|2|7|3|8|9|
    |4|7|9|3|6|8|5|1|2|
    |8|2|3|9|1|5|6|4|7|
    |7|8|4|1|3|2|9|5|6|
    |2|3|5|6|8|9|4|7|1|
    |9|6|1|7|5|4|8|2|3|
    Final configuration:
    |5|1|8|2|9|6|7|3|4|
    |3|9|7|8|4|1|2|6|5|
    |6|4|2|5|7|3|1|9|8|
    |1|5|6|4|2|7|3|8|9|
    |4|7|9|3|6|8|5|1|2|
    |8|2|3|9|1|5|6|4|7|
    |7|8|4|1|3|2|9|5|6|
    |2|3|5|6|8|9|4|7|1|
    |9|6|1|7|5|4|8|2|3|
    Number of attempts: 0.
    Time elapsed: 0.00 s.
    Segmentation fault
    So what's wrong here?
    Having implemented the basic functionalities, I tried to play around and gain some simple experience in some optimization. I looked at the Go() function and saw probably the expensive operation is IsConsistent(), so I optimized it by only checking the consistency of changed boxes. By doing so, I reduced the computational time to around 1/3 the original time. Is this the right move, or bad move, or are there better moves?
    As a last question, I defined the number of attempts as a global variable. My reason is that, although it is possible to put it in class Board, I just think it doesn't "naturally belong" there, and putting it in a restricted scope would mean a lot of passing of parameters, slowing the program down unnecessarily. So, is this global variable fine?
    Lastly, please have a look at my Makefile. This is the first Makefile I wrote, and it took me 3 solid days to get all the .o files in Release/ ! Are there things I've left out?
    I realize the Generator is a joke, but at this moment I don't care too much about that, unless anyone has some good ideas.
    Any comments would be greatly appreciated! Thanks in advance!

    Grazz256 wrote:
    Just looking over your code a little I have a couple of comments about your coding style. Please keep in mind that these are just comments...
    I think you need to comment your code more. I know its a pain and I'm horrible about it as well but it really does help when/if you go back to read your code in a couple of years.
    I try to avoid lines like these:
      fprintf( stdout, "Starting configuration:\n" ); a->Write(stdout);
      start = clock(); a->Go();
    by putting two commands on one line it makes the code harder to read. with one command on each line I can quickly scan through and know
    generally what each line does, with two I have to actually read each line fully so that I don't miss anything.
    Descriptive variable names can also help with readability, I've always been taught the convention of using the first character to indicate type then
    using a short descriptive name. For instance you have a function that returns a long value, the value would be decalred like this:
    long lRetVal;
    so looking through the code I would know thats a long value that represents a return value.
    This is an area I'm all over the place with, I always try to stick to one convention but never seem manage it...
    As far as your problem goes, where are the boards normally deleted? ie if an incomplete sudoku is inputed?
    One possible solution is to run an IsComplete check before you start processing the board. so you would have...
    if (a->IsConsistent()) {
    if (a->IsComplete()) {
    a->Go()
    I'll be honest in that I don't really understand the flow of your code, but instead of having the board deleted within strategy or within win why not just delete it on the next line... eg:
    start = clock(); a->Go();
    delete a;
    the downside to this approach is that you would have to delete it within each exception as well but this is relatively minor.
    Cheers
    Thanks for your comments. At my present level of programming skills, any comments will help.
    I thought all my code was basically concise and self-explanatory, and each function is small enough that a quick skim through the definition and declaration would be enough to understand. As the project grew, however, things got slightly more complicated. I have added more comments in my source files, trying to comment why rather than how. I thought the flow of the code was fairly obvious though, by inspecting the main loop. It takes care of the input, bark if anything's wrong, trigger a.Go(), and try to catch a Win. Do you mean the flow within Go()? Anyway, it is very true I need clearer coding style.
    Yeah I now solved the segfault problem. The reason a completed sudoku was deleted twice is because the original sudoku is meant to be deleted by the abstract factory, while the solved sudoku is meant to be deleted by Win. When a solved sudoku is inputted it would be deleted twice. Due to lack of programming experience, I failed to see the obvious way is to, as Grazz256 said, check in the beginning whether the inputted sudoku is already solved. If it is, then I duplicate the inputted sudoku and throw the win exception.
    By the way, I think I'm beginning to understand why some people are obsessed wtih optimization. I did 3 optimization techniques in my program. First, I thought the most expensive procedure is the IsConsistent() method. By evaluating it lazily I reduced the time to 1/3 the original time. Then following http://www.acm.org/crossroads/xrds1-4/ovp.html, I used initialized the 2D vector within each sudoku via constructor rather than as statements. Doing so gave a 20% time boost. Using a friend procedure while copying sudokus boost another 5%. Doing a right move and getting positive feedback through better performance can be so satisfying.
    EDIT:
    I found out there was memory leak after all, which I finally solved.
    What happens is with all my brute force algorithms I keep creating new Board's and call the Board's Go() recursively. To delete all Board's in the heap I need to have, within each Board::Go(), instead of
    Board* a = Clone(); // return new derived Board(*this);
    a->Put(x,y,'0'+k);
    a->Go();
    delete a; // if an exception is thrown this line never gets executed
    this
    Board* a = Clone();
    a->Put(x,y,'0'+k);
    try {a->Go(); }
    catch( const Win& e) {
    delete a;
    throw(e);
    delete a;
    But this deletes the winning sudoku too. This means I have to keep the result in Win, either by duplicating the winning sudoku or storing the string. In the end I overloaded Board::Write(File* f) to also have Board::Write(std::string& p) to sprintf on the reference of a string, so Win just stores the solution in string format. Finally, no memory leak, no need to do a first check to see if the inputted sudoku is already solved, and no pointer deleted twice.
    So in the end, to manage pointers I recursively threw exceptions. That made me ask, is using exceptions worth it, or should I stick to the more conventional methods, such as have Go() return a boolean value, then deleting pointers which would give an implementation that is essentially the same as recursive exceptions?
    I still think exceptions is the way to go, the reasons being:
    1) Exception mechanism provide a natural place to hold the result. Throwing exceptions recursively and the traditional way is essentially the same, but where should the result be stored in the latter case?
    2) Arguing over the dictionary, an exception is not necessarily an "error." Winning is an exception in this algorithm, because failure is the norm (as in life).
    3) Exception arguably gives better presentation in the main loop, to my "unbiased" eyes at least. Board* a->Go() is triggered in the try block in the main(), with all (foreseeable) possible results caught as exceptions. It is true that this might be a bit unconventional, but given proper comments I still think it is at least as good as the conventional way, in terms of presentation.
    So what do you think?
    Last edited by dumas (2009-12-21 12:37:47)

  • Panel isn't expanding with the window

    Hey,
    I am writing a Sudoku program, and well I haven't really done anything yet. All it does is draw the board (9x9 grid) on a Panel, then the panel is added to the Applet. Thing is, the Applet is set to a 550x550 size, but the Panel doesn't expand with it. It's stuck at the default(?) size. The TextFields (the grid) expand with the window, so only a few are shown on the screen. A screenshot can be found here -> http://i46.tinypic.com/2wnzqtu.png
    Here's the code:
    package sudoku;
    import java.applet.Applet;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.Panel;
    import java.awt.TextField;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class PlaySudoku extends Applet implements ActionListener
         static final int FRAME_WIDTH  = 550;
         static final int FRAME_HEIGHT = 550;
         static final int BOARD_ROWS    = 9;
         static final int BOARD_COLUMNS = 9;
         static final int BOARD_WIDTH   = 500;
         static final int BOARD_HEIGHT  = 500;
         TextField[][] grid = new TextField[BOARD_ROWS][BOARD_COLUMNS];
         Panel board = new Panel(new GridLayout(BOARD_ROWS, BOARD_COLUMNS));
         public void init()
              this.setLayout(new BorderLayout());
              this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
              for (int i = 0 ; i < BOARD_ROWS ; i++)
                   for (int j = 0 ; j < BOARD_COLUMNS ; j++)
                        grid[i][j] = new TextField();
                        board.add(grid[i][j]);
              this.add(board, BorderLayout.CENTER);
         public void actionPerformed(ActionEvent e)
    }Thanks,
    Coh3n

    Only just checked the image.
    - What OS is that?
    - What is the exact (copy/pasted in code tags) HTML used for the applet viewer?
    Or perhaps - run this variant of your code and report back.
    // <applet code='PlaySudoku' width='650' height='250'></applet>
    import java.applet.Applet;
    import java.awt.*;
    public class PlaySudoku extends Applet
         static final int BOARD_ROWS    = 9;
         static final int BOARD_COLUMNS = 9;
         TextField[][] grid = new TextField[BOARD_ROWS][BOARD_COLUMNS];
         Panel board = new Panel(new GridLayout(BOARD_ROWS, BOARD_COLUMNS));
         public void init()
              this.setLayout(new BorderLayout());
              for (int i = 0 ; i < BOARD_ROWS ; i++)
                   for (int j = 0 ; j < BOARD_COLUMNS ; j++)
                        grid[i][j] = new TextField();
                        board.add(grid[i][j]);
              this.add(board, BorderLayout.CENTER);
              // always a good idea
              validate();
              System.out.println("Size: " + getSize());
              System.out.println("os.name: " + System.getProperty("os.name"));
              System.out.println("java.vendor: " + System.getProperty("java.vendor"));
              System.out.println("java.version: " + System.getProperty("java.version"));
              System.out.println("java.vm.version: " + System.getProperty("java.vm.version"));
    }Here are the results I'm getting, with no odd sizing artifacts.
    andrew@pc1:/media/disk/proj$ javac PlaySudoku.java
    andrew@pc1:/media/disk/proj$ appletviewer PlaySudoku.java
    Size: java.awt.Dimension[width=650,height=250]
    os.name: Linux
    java.vendor: Sun Microsystems Inc.
    java.version: 1.6.0_14
    java.vm.version: 14.0-b16
    andrew@pc1:/media/disk/proj$ Note that on this OS/SDK, the appletviewer can parse an applet element out of the first (commented) line of the Java source file.

  • Multiple apps with same name

    With all the trouble I've been having with App Store update inconsistencies, I went and looked at the directory where the .ipa files are stored. (These are the actual application files.) I was already aware of the multiple generations of files that are kept in the directory when apps are updated, but I noticed something else...
    There are some applications that have the same name. In my case, I have more than one Solitaire game simply called "Solitaire" and I have more than one Sudoku game with the name "Sudoku". It looks like the way iTunes differentiates them is by giving them generational number. For example, one Sudoku program is called "Sudoku.ipa", and another is called "Sudoku 1.ipa". Then if there is an update to the first program, it gets the new name "Sudoku 2.ipa". You can see that different programs have different files sizes, but by looking at names there is no way to tell which is which.
    I wonder if this factors into some of the problems with application updates and synching them to the iPhone? It seems odd that the same sequential numbering scheme is used for two different purposes: 1. Distinguishing different applications that have the same file name, and 2. Keeping multiple generations of the same program in the directory. It could get pretty confusing.

    If I delete extra .ipa files when two different applications have the same name, then I need to keep track of which is the current version of what. "Sudoku 4.ipa" might be the latest version of one program, and "Sudoku 7.ipa" could be the latest version of another.
    I wish Apple would create a naming scheme where every application has a unique name, and sequential generations are not used. This would make it much cleaner, and there would be no ambiguity as to either which program is which, or which version is which.
    I find the safest way to get rid of all the dups is to just delete them all and re-download the app. The bugs in iTunes still make a mess of things, though.

  • Java program for Sudoku puzzle

    I basically need to list the possible solutions to every blank space in a sudoku puzzle. I can make my puzzle in a .txt file and then just run that in my program.
    Here's an example of a line I would create in my.txt file:
    5 3 _ _ 7 _ _ _ _ (So possible solutions for the third spot would be 1,2, or 4. Then you'd continue down the line)
    So to get started I need to create a 9x9 array to store my .txt file. Read in my input one line at a time, then use a StringTokenizer to break apart each value in the line. So basically I need help starting that beginning part of my program. I'm a pretty slow learner with this stuff so a little help getting me started helps out a lot, then I tend to catch on to what is going on and I can finish up from there.
    Thanks Guys

    I still need to loop through and rows, columns, and grid to find possible solutions but I didn't ask for help on that. I know how to set up a 2d array, but when I set it up it's not reading out my .txt file. I was going to use 'char' in my array, but I don't know how I'm going to read from that .txt file, charAt I was thinking. Then for the stringTokenizer I'm really confused on how I would break apart each value from my .txt file.So, it looks like you're panicking and trying to do everything all at once. Maybe that's why you aren't getting anywhere. You need to start small. Don't try to write the whole program in one go, but instead start with a simpler program that doesn't do the whole business. In fact, start with a really simple program that does just one thing.
    What's the first thing that's necessary? You have to read your input data from a file, one line at a time. (Yes, then you have to break each of the lines into pieces, but don't get ahead of yourself.) So write a little program that only reads your input file one line at a time. To check that it's working, just write each of the lines out to the console.
    Then when that's working, add another feature. That would be splitting the lines into pieces. Again, for now just write the pieces out to the console to check that it's working. Then carry on from there.

  • Is it possible to create a java program which can find the answer to any sudoku

    This is may sound as a beginner question but thats because i am a beginner. i have just learned the java language and now i am reading essential classes on oracle tutorials.
    anyway is this possible ? i think it is and i have been trying to do it but havent been sucessful. and if it is possible is it supposed to be easy ?
    i have been trying to do it by making a 2d array of 8 arrays having 8 ints each which is basically a sudoku. and creating a 1d array called possiblity having nos from 1 to 9. then using decision making statements and loops to eliminate the possiblities of each box and repeating until the sudoku is complete
    also if you could provide some project ideas that would be really appreciated.
    (PS i am still an intermediate at best so please dont provide very difficult project ideas)

    f1b8d129-b881-44f7-a736-5eef31471720 wrote:
    This is may sound as a beginner question but thats because i am a beginner. i have just learned the java language and now i am reading essential classes on oracle tutorials.
    anyway is this possible ?
    Yes.
    i think it is and i have been trying to do it but havent been sucessful. and if it is possible is it supposed to be easy ?
    Maybe.
    It should be easy to do a "brute force attack" to find the solution meaning that you simply try each and every possibility.
    i have been trying to do it by making a 2d array of 8 arrays having 8 ints each which is basically a sudoku. and creating a 1d array called possiblity having nos from 1 to 9. then using decision making statements and loops to eliminate the possiblities of each box and repeating until the sudoku is complete
    shouldn't there be 9 sqares with 9 fields each?
    also if you could provide some project ideas that would be really appreciated.
    But an array of primitives (int?) will not do the trick. Somehow you have to remember wich positions are fixed. and which numbers are still availabe for the current sqare.
    At your level the most obvisual approach may be a second array holding this information.
    I'd prefer to build a cusom object representing a square and another custom object to represent a field within this square with two attributes: currentNumber and isFix.
    Based on this the Sqare object could have a method to create a new combination by shifting the numbers that are not fix.
    If you need further assistance please show the code you have and what problem(s) you have with it.
    bye
    TPD

  • Threaded Sudoku solver - Assignment question (NOT LOOKING FOR ANSWERS  )

    Hi All,
    I'm going to be upfront and point out this is an assignment that i'm currently working on and i'm not receiving much in the way of feedback from the class forums.
    This is currently a 4th year OO assignment for UNSW Australia.
    What I am having trouble doing is figuring out where my program is deadlocking or dying. There have been a number of requirements set out by the assignment, basically no synchronization, no locking. We are able to use volatile, atomic, immutable and thread-local objects. The task is to find all solution for a given N x N sudoku problem using X number of threads. I have successfully built the solver (X = 0) without too much trouble and I thought i had managed to modify the recursive algorithm to suit but unfortunately I think I have come unstuck.
    Any generalized tips would be appreciated when implementing threads that utilise checking flags to determine when the thread is finished processing.
    Kind Regards,
    Chris Gibbs

    Honestly, I think that recursion (as you stated) would be the easiest way to have solved this problem. But as you stated, threads must be used to solve this problem as a requirement of the project...
    You could easily launch a Thread each time instead of calling your recursive method... that could possibly result in a crap load of threads, but the idea would work.
    Definitely take a look at the SwingWorker class here if you're able to use J2SE 6: [http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html|http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html]
    I currently use it while gathering data from several websites at the same time. What I did was create and execute() X number of MySwingWorker objects to collect the data, while they are not complete (i.e. MySwingWorker.isDone() is false) I just Thread.sleep(...).
    Give it a try. It may suit your needs.

  • Sudoku Algorithm

    Hi, i was venturing out to design an algorithm to generate sudoku puzzles, I was thinking of emplying 2D Matrix arrays. The idea I have is filling up the whole grid first with a solution then taking away a few numbers. I don't really know how to do this, though I have an idea, getting it to check the rows and columns add up to 45 and each 3x3 grid adds up to 45, 45 being the sum of all the numbers in a 3x3 grid. Would anyone be able to tell me if this would work and how would I be able to program this in JAVA. Many thanks in advance.

    And I need an algorithm to solve sudokupuzzles.
    That's the hard part, at least if you want to solve
    it without brute force.Indeed, I thought that only with brute force Sudoku can be solved.
    Indeed, I don�t think that there is a "magic intelligent" algorithm that can solve it . Well, Sudoku is cool exactly because it can just be solved by brute force. LOL!!!!
    Maybe some math genius person knows how to write an algorithm to solve Sudoku easily, or how to explain and prove mathematically that an algorithm to solve that is not possible.

  • SUDOKU in JAVA  Plz Help

    Hi
    I want to develop a Java program to solve Sudoku puzzles
    My program must be able to:
    �Read in a puzzle (from the predefined file format � see below)
    �Display the unsolved puzzle
    �Solve the puzzle
    �Display the solved puzzle
    File Format
    The file consists of a number of integers.
    The first integer signifies the size of the puzzle e.g. a 2 indicates a 4x4 puzzle, a 3 indicates a 9x9 puzzle, a 4 indicates a 16x16 puzzle and so on.
    The remaining numbers are one integer for each square of the puzzle (e.g. 81 integers for a 9x9 puzzle) and should be read left to right and top row to bottom row. A zero means that the square is empty. A non-zero indicates the number in that square.

    > Hi
    I want to develop a Java program to solve Sudoku
    puzzles
    My program must be able to:
    non-zero indicates the number in that square.
    And your question is?

  • Sudoku Pluzzle

    I'm looking for Algorithms that will solve sudoku puzzles. Im trying to write my own program for this to get ready for a compition. Would anyone know where to find these algorithms or ways to slove sudoku puzzles using a system every time? Any suggestions are helpfull thank you,
    Cobbweb

    I think you are going to have to write your own algorythm for this.
    The math is beyond me, but off the bat I am going to guess that a brute-force-from-zero approach is not going to work anytime this century. However, if you make an initial elimination pass and then start trying possibilities with recursive elimination passes from there I bet it would chop things down enough that you could just do it that way without any really clever algorythm.
      A B C
    A 1 ? ?
    B ? ? 3
    C ? 2 ?With coordinates given as X,Y - so that the 3 is at C,B.
    The number at A,B could be 1, 2, or 3, given only the rules of the game. Your "initial pass" is where you just run through the colum (A) and the row (B) and eliminate possibilities. So we know it cannot be 1 because there is a 1 at A,A and it cannot be 3 because there is a 3 at C,B. In a puzzle this simple that already tells us the answer (since only 1 is left) but obviously this will not be the case in a real puzzle. However, we will still have chopped out a LOT of possibilities.
    Next we just pick an order for empty spaces - say left to right, top to bottom. The first one is B,A, so we go there. Then we just pick a number (moving from 1 up) to try out. That number gives us more information, so we make another pass over the entire grid eliminating stuff again. Then we just walk down the grid in a binary search tree type of dealy.
    I bet that even a big puzzle would be no problem for a modern computer this way.
    Drake

  • Sudoku GUI

    Hey am trying to create a GUI for my Sudoku board.
    Here is how it currently looks: (See code below)
    There are two things I wanna change
    1. How do I center align the number so they are not stuck to the right edge as they are now?
    2. How do I add a bolder line around blocks/boxes(e.g. the 3*3 sections). Im sure these are pretty easy but havent been able to figure it out as of yet!
    Any help would be greatly appreciated.
    Code:
    package proj.sudoku.gui;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Cursor;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.InputMethodEvent;
    import java.awt.event.InputMethodListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingConstants;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import proj.sudoku.representation.Board;
    import proj.sudoku.representation.Square;
    import proj.sudoku.ui.Sudoku;
    public class SudokuGUI extends JFrame implements ActionListener{
    private JTextField unfilledSquaresTextField;
    private JTextArea messagesTextArea;
    private JTable boardTable;
    private Board board;
    private Sudoku sudoku = new Sudoku();
    private int noOfUnfilledSquares = 20;
    private static final long serialVersionUID = 1L;
    class BoardTableTableModel extends AbstractTableModel {
    public final String[] COLUMN_NAMES = { "Row 0", "Row 1", "Row 2", "Row 3", "Row 4", "Row 5", "Row 6", "Row 7", "Row 8"};
    public int getRowCount() {
    return 9;
    public int getColumnCount() {
    return COLUMN_NAMES.length;
    public String getColumnName(int columnIndex) {
    return COLUMN_NAMES[columnIndex];
    public Object getValueAt(int rowIndex, int columnIndex) {
    int squareValue = board.getSquare(rowIndex, columnIndex).getSquareValue();
    if(squareValue == 0){
    return null;
    }else{
    return new Integer(squareValue);
    public boolean isCellEditable(int row, int col){
    return true;
    public void setValueAt(Object value, int row, int col) {
    int intValue = ((Integer)value).intValue();
    if((intValue >= 0) && (intValue < 10)){
    Square square = board.getSquare(row, col);
    square.setSquareValue(((Integer)value).intValue());
    board.setSquare(square, row, col);
    fireTableCellUpdated(row, col);
    public Class getColumnClass(int c) {
    return Integer.class;
    * Create the frame
    public SudokuGUI(Board newBoard) {
    super();
    getContentPane().setBackground(new Color(128, 128, 255));
    board = newBoard;
    getContentPane().setLayout(new GridBagLayout());
    setTitle("Sudoku Sudokme");
    setBounds(100, 100, 607, 456);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JPanel tablePanel = new JPanel();
    tablePanel.setLayout(new GridBagLayout());
    final GridBagConstraints gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.weighty = 0.5;
    gridBagConstraints.weightx = 1;
    getContentPane().add(tablePanel, gridBagConstraints);
    boardTable = new JTable();
    boardTable.setRowHeight(40); // TODO This line has been changed
    boardTable.setFont(new Font("", Font.PLAIN, 20));// TODO This line has been changed
    boardTable.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
    boardTable.setRowSelectionAllowed(false);
    boardTable.setShowGrid(true);
    boardTable.setModel(new BoardTableTableModel());
    final GridBagConstraints gridBagConstraints_2 = new GridBagConstraints();
    gridBagConstraints_2.gridx = 0;
    gridBagConstraints_2.gridy = 0;
    gridBagConstraints_2.insets = new Insets(0, -265, 0, 0);// TODO This line has been changed
    //gridBagConstraints_2.insets = new Insets(5, -265, 5, 0);
    tablePanel.add(boardTable, gridBagConstraints_2);
    final JPanel messagesPanel = new JPanel();
    messagesPanel.setLayout(new GridBagLayout());
    final GridBagConstraints gridBagConstraints_6 = new GridBagConstraints();
    gridBagConstraints_6.weighty = 0.3;
    gridBagConstraints_6.weightx = 1.0;
    gridBagConstraints_6.gridy = 1;
    gridBagConstraints_6.gridx = 0;
    getContentPane().add(messagesPanel, gridBagConstraints_6);
    messagesTextArea = new JTextArea();
    messagesTextArea.setAlignmentY(Component.BOTTOM_ALIGNMENT);
    messagesPanel.add(messagesTextArea, new GridBagConstraints());
    messagesTextArea.setText(board.getMessage());
    messagesTextArea.setEditable(false);
    final JPanel generateButtonPanel = new JPanel();
    generateButtonPanel.setLayout(new GridBagLayout());
    final GridBagConstraints gridBagConstraints_3 = new GridBagConstraints();
    gridBagConstraints_3.gridy = 2;
    gridBagConstraints_3.gridx = 0;
    getContentPane().add(generateButtonPanel, gridBagConstraints_3);
    final JButton generateEmptyBoardButton = new JButton();
    generateEmptyBoardButton.addActionListener(this);
    generateEmptyBoardButton.setText("Generate Empty Board");
    final GridBagConstraints gridBagConstraints_9 = new GridBagConstraints();
    gridBagConstraints_9.gridy = 0;
    gridBagConstraints_9.gridx = 0;
    generateButtonPanel.add(generateEmptyBoardButton, gridBagConstraints_9);
    final JButton generateBoardButton = new JButton();
    generateBoardButton.addActionListener(this);
    generateBoardButton.setText("Generate Board");
    final GridBagConstraints gridBagConstraints_10 = new GridBagConstraints();
    gridBagConstraints_10.gridx = 2;
    generateButtonPanel.add(generateBoardButton, gridBagConstraints_10);
    final JLabel unfilledSquaresLabel = new JLabel();
    unfilledSquaresLabel.setText("Unfilled Squares");
    final GridBagConstraints gridBagConstraints_11 = new GridBagConstraints();
    gridBagConstraints_11.gridy = 0;
    gridBagConstraints_11.gridx = 3;
    generateButtonPanel.add(unfilledSquaresLabel, gridBagConstraints_11);
    unfilledSquaresTextField = new JTextField();
    unfilledSquaresTextField.setFont(new Font("", Font.BOLD, 14));
    unfilledSquaresTextField.addActionListener(this);
    unfilledSquaresTextField.setText(new Integer(noOfUnfilledSquares).toString());
    unfilledSquaresTextField.setBackground(Color.WHITE);
    final GridBagConstraints gridBagConstraints_12 = new GridBagConstraints();
    gridBagConstraints_12.gridy = 0;
    gridBagConstraints_12.gridx = 4;
    unfilledSquaresLabel.setLabelFor(unfilledSquaresTextField);
    generateButtonPanel.add(unfilledSquaresTextField, gridBagConstraints_12);
    final JPanel solveButtonsPanel = new JPanel();
    solveButtonsPanel.setRequestFocusEnabled(false);
    solveButtonsPanel.setLayout(new GridBagLayout());
    final GridBagConstraints gridBagConstraints_1 = new GridBagConstraints();
    gridBagConstraints_1.weighty = 0.1;
    gridBagConstraints_1.weightx = 1;
    gridBagConstraints_1.gridy = 3;
    gridBagConstraints_1.gridx = 0;
    getContentPane().add(solveButtonsPanel, gridBagConstraints_1);
    final JButton heuristicsSolveButton = new JButton();
    heuristicsSolveButton.addActionListener(this);
    heuristicsSolveButton.setText("Heuristics Solve");
    final GridBagConstraints gridBagConstraints_4 = new GridBagConstraints();
    gridBagConstraints_4.gridx = 0;
    solveButtonsPanel.add(heuristicsSolveButton, gridBagConstraints_4);
    final JButton bruteForceSolveButton = new JButton();
    bruteForceSolveButton.addActionListener(this);
    bruteForceSolveButton.setText("Brute Force Solve");
    final GridBagConstraints gridBagConstraints_7 = new GridBagConstraints();
    gridBagConstraints_7.gridx = 1;
    solveButtonsPanel.add(bruteForceSolveButton, gridBagConstraints_7);
    final JButton hybridSolveButton = new JButton();
    hybridSolveButton.addActionListener(this);
    hybridSolveButton.setText("Hybrid Solve");
    final GridBagConstraints gridBagConstraints_8 = new GridBagConstraints();
    gridBagConstraints_8.gridx = 2;
    solveButtonsPanel.add(hybridSolveButton, gridBagConstraints_8);
    final JPanel testButtonsPanel = new JPanel();
    testButtonsPanel.setLayout(new GridBagLayout());
    final GridBagConstraints gridBagConstraints_5 = new GridBagConstraints();
    gridBagConstraints_5.weighty = 0.1;
    gridBagConstraints_5.weightx = 1.0;
    gridBagConstraints_5.gridy = 4;
    gridBagConstraints_5.gridx = 0;
    getContentPane().add(testButtonsPanel, gridBagConstraints_5);
    final JButton checkIfValidButton = new JButton();
    checkIfValidButton.addActionListener(this);
    checkIfValidButton.setText("Check If Valid");
    testButtonsPanel.add(checkIfValidButton, new GridBagConstraints());
    final JButton checkIfLegalButton = new JButton();
    checkIfLegalButton.addActionListener(this);
    checkIfLegalButton.setText("Check If Legal");
    testButtonsPanel.add(checkIfLegalButton, new GridBagConstraints());
    public static void main(String args[]) {
    try {
    SudokuGUI frame = new SudokuGUI(new Board());
    frame.setVisible(true);
    //frame.pack();
    } catch (Exception e) {
    e.printStackTrace();
    public void actionPerformed(ActionEvent arg0) {
    if(arg0.getSource().getClass().getName().equals("javax.swing.JTextField")){
    noOfUnfilledSquares = new Integer(((JTextField)arg0.getSource()).getText()).intValue();
    this.repaint();
    }else{
    try{
    board = sudoku.processGUICommands(board, arg0.getActionCommand(), noOfUnfilledSquares);
    messagesTextArea.setText(board.getMessage());
    this.repaint();
    }catch(Exception e){
    e.printStackTrace();
    }

    1) Use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags when posting code so the code is readable
    2) The code you posted isn't compileable or executable so we see exactly what you layout looks like
    3) If you have a Grid type layout, then I would think a GridLayout would be more appropriate to use then the GridBagLayout. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers for more information.
    How do I add a bolder line around blocks/boxes[url http://java.sun.com/docs/books/tutorial/uiswing/misc/border.htmlHow to Use Borders[/url]
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.

  • Sudoku corrupted.

    I have a Nokia N70 with preinstalled software.
    Yesterday, I wanted to play the game "Sudoku" but the game showed only the welcome screen (MBounce) and immediatly after that screen a message: "file corrupted".
    Does anybody knows how to reinstall the file?
    TIA

    Hi Chris,
    This game is bundled with the preinstalled software of the phone.
    As far as I know, a "General Reset" should bring the phone to it's original state and reload all the preloaded software.
    But I dont know if the corrupted file will be reloaded with an uncorrupted version.
    I have tried to reload different versions I own of "Sudoku", but they are all refused tp install with the same error notification.
    And it is imppossible to delete the original Sudoku as this is a preinstalled program.
    TIA
    g

  • Sudoku code

    hi,
    any one can send sudoku code in ABAP as it is very urgent plz send the screen file also
    my mail id is [email protected]
    please do me this favour as it is very essential for me
    SUDOKU CODE

    Check this link to get all details -
    http://forum.codecall.net/database-database-programming/121-sudoku-can-solved-using-sql-take-look.html
    Re: Just a wild idea
    http://www.di-mgt.com.au/src/sudoku.bas.html
    http://www.di-mgt.com.au/sudoku.html#source
    Hope this helps.

  • Sudoku code in ABAP

    Hi,
    every one
    plz send sudoku code in ABAP as it is very urgent
    my mail id is [email protected]
    send screen downloded files also

    Check this link to get all details -
    http://forum.codecall.net/database-database-programming/121-sudoku-can-solved-using-sql-take-look.html
    Re: Just a wild idea
    http://www.di-mgt.com.au/src/sudoku.bas.html
    http://www.di-mgt.com.au/sudoku.html#source

  • Free Constraint Programming Library for Java?? what to use?

    Hi everyone,
    I am currently programming the popular Sudoku game as my final year project at university. After doing some research I found that using Constraint Programming would be the best way to generate and solve the Sudoku puzzles... however, I'm in a bit of a dilemma....
    I'm not sure what Constraint Library to use - the most popular one out there is Koalog - but its a commercial application - and I was looking for an open source or free application.
    I have been looking into the Choco (http://choco.sourceforge.net) Library but I am having trouble with getting hold of the global constraints I need ie AllDifferent.
    An extensive guide of how to use Constraint Programming is shown on the Java Sun Website: http://today.java.net/pub/a/today/2005/11/29/solving-sudokus-in-java.html
    Any advise would be greatly appreciated.
    Thanks in advance
    :o)

    Hi aniseed,
    Thanks for the user guide link -- I have looked through and I am beginning to understand it all.... but my main problem is that the user guide specifies a global constraint called allDifferent
    Here are described som of those constraints :
    1. pb.allDifferent(IntVar[] vars) creates a constraint ensuring that all pairs of variable
    have distinct values (which is useful for some matching problems)When I try to type pb.allDifferent into my program - it does not recognise the method so it does not compile- all the other methods work apart from this one.
    Any ideas?? :o)

Maybe you are looking for

  • Ebs 11i Cloning in Win 2003 dbtier fails with ERROR: Could not open

    Hi, The rapidclone - DBTier cloning (11i) on Windows 2003 server fails with the following weird error message. There is no detailed log file created. echo %PATH% f:\oracle\prodora\8.0.6\bin;f:\oracle\proddb\9.2.0\apache\perl\perl\5.0053\bin\mswin32-x

  • Attachments coding - Purchase order

    i am trying to find out all the purchase order ( header) which does not have a attachment to it? Query select segment1 from apps.po_headers_all pha where type_lookup_code = 'BLANKET' AND ORG_ID = 87 AND pha.po_header_id NOT in ( select distinct pk1_v

  • Oracle Disk I/O hitting 100% ?

    Hi, We're having an issue where our 2 ZCM servers are no longer responding to user logins, I have to manually stop & restart the Zenserver / Zenloader services as an interim. Our DB admins told us that the Zen database is causing 100% disk I/O and th

  • Linux_815patches

    Dear All, Please tell me how and where to find "linux_815patches". I'm unable to install 9ias on linux. If you can send me this patch wud be grateful. Thanks Navin

  • Can't get the trail run to open, i've only been on it once.

    I downloaded the free 30 day trail yesterday.  I was able to open it this morning and start editing.  I closed it out, tried to open it now and it won't open.  a Any suggestions??