JSudoku

Yet another Sudoku program

Main interface

Down to the basics, here’s what I did:

  1. Generate the whole board with backtracking, randomizing the number I chose at each step and remember the choice, this assures that the board is random, while still keep the algorithm run in an acceptable time (it doesn’t have to regenerate a long track of numbers if it get into some sticky situation). Sudoku board have to keep up with a number of rules that make up a complex vector class, lost in there and you’re done. The other method to generate the board was to swap the rows/column/numbers, it’s safe and much faster but it took more time to implement, and it generates only a subclass of the possible Sudoku class, but it’s a good choice if you don’t want recursive calls in your program.
  2. Difficulty: I implemented a simple, but it’s not good for real application, I think. A good difficulty implementation should have taken humans’ deduction rules into consideration (you should know what are these these if you’ve played Sudoku before), and the algorithm should also make sure that with the given cells, only one solution is possible, this is a continuous generate-remove-check for solutions-remove loop and it’s complex to implement. So, I have only removed a number of cells based on difficulty, the more difficulty chosen, the less given cell there are. This implementation suffers from the above points.
  3. Build a usable Sudoku class’ interface: I deducted from coding that you need to store both the solution and the playing board in the class, provide board and solution get method, the set move method for the board should only accept valid moves, this way you only need to count the number of moves played to know if the player have won or not. This has the drawback that you can’t store invalid values in the board (to visually notify the player of their wrong moves), but it keeps your code clean of unnecessary checks.
  4. Build the interface: If you choose to manually generate the JFrame, JButton and uses a loop to create JTextField, it saves time to point-and-click creating the cells, but you will have to manually calculate the button and frame’s position to get a nice interface; the other way around, you’ll have to create JTextFields 81 times. I choose a hybrid approach: use the designer to design the form, add a JPanel to it, and then add the JTextField in the user interface’s constructor.
  5. Just for kicks: I add a key press handler into the text fields, the handler catches input, and if it’s not a valid number, not correct according to Sudoku rules or some other reason, the cell will be highlighted so the user can see it easily, the hint function is implemented in this way too: it compares what the user have to the solution and highlight the differences.

Creating text fields

    /** Creates new form SudokuInterface */
    public SudokuInterface() {
        initComponents();

        // Automatically arranges the cells into a grid-like layout
        jPanel1.setLayout(new GridLayout(Sudoku.ROWS, Sudoku.COLUMNS));
        fields = new JTextField[Sudoku.ROWS * Sudoku.COLUMNS];
        for (int i = 0; i < Sudoku.ROWS * Sudoku.COLUMNS; i++) {
            fields[i] = new JTextField(1);
            fields[i].setSize(66, 66);
            fields[i].setFont(cellFont);
            fields[i].setName(Integer.toString(i));
            fields[i].addKeyListener(cellInputHander);
            fields[i].setHorizontalAlignment(JTextField.CENTER);
            fields[i].setEnabled(false);
            jPanel1.add(fields[i]);
        }

        // First screen
        String intro = "JSudoku";
        for (int i = 1; i < intro.length() + 1; i++) {
            fields[4 * Sudoku.ROWS + i].setText(intro.charAt(i - 1) + "");
        }

    }

Handling key input

    private final KeyListener cellInputHander = new KeyListener() {

        /**
         * Controls, the user's input, let them input invalid data and display it
         * to avoid confusing the user (higher usability), but this won't be
         * reflected in the actual game, we have to keep track of which cells are
         * invalid, resulting in this complex implementation
         */
        public void keyTyped(KeyEvent e) {
            e.consume();
            int move = 0;
            String moveString = e.getKeyChar() + "";
            try {
                move = Integer.parseInt(moveString);
            } catch (Exception exception) {
                return;
            }
            // If the move is invalid, do nothing, the key won't appear
            int cellIndex = Integer.parseInt(e.getComponent().getName());
            if (!game.set(cellIndex, move)) {
                ((JTextField)e.getSource()).setForeground(cellIncorrectForeground);
                jLabel3.setText("You have just performed an invalid move");
                isInvalid[cellIndex] = true;
            } else {
                ((JTextField)e.getSource()).setForeground(cellEnabledForeground);
                jLabel3.setText("");
                isInvalid[cellIndex] = false;
            }
            ((JTextField)e.getSource()).setText(moveString);
            if (game.won()) {
                JOptionPane.showMessageDialog(rootPane, "You have solved the puzzle!", "Congratulation", JOptionPane.INFORMATION_MESSAGE);
                newGame(lastDifficulty);
            }
        }

        public void keyPressed(KeyEvent e) {

        }

        public void keyReleased(KeyEvent e) {

        }
    };

Move checking
Like I said, there’s plenty of room for improvement, so here’s the source code if you want to do just that 😉

Object oriented experiment

class Shape {
    // This method will be overridden by its children, even if it's not abstract
    // and its children have not specified @Override
    void draw() {
        System.out.println("Shape drawn");
    };

    @Override
    protected Object clone() {
        return null;
    }
}

class Rectangle extends Shape {
    void draw() {
        System.out.println("Draw rectangle!");
        super.draw();
    }

    // We can change the return type and access of a overridden method from its
    // parent class! Note that access modifier must be the same or more relaxing
    // like private -> protected -> public, but not the other direction
    @Override
    public Rectangle clone() {
        return null;
    }
}
class Triangle extends Shape {
    void draw() {
        System.out.println("Draw Triangle!");
    }
}
class Circle extends Shape {
    void draw() {
        System.out.println("Draw Circle!");
    }
}
public class AbstractClass {
    public static void main(String[] args) {
        Shape s = new Circle();
        s.draw();
        s = new Triangle();
        s.draw();
        s = new Rectangle();
        s.draw();
        
    }
}

Setting the encoding in Eclipse or Netbeans

It’s the era of Unicode, and you though the problem of encoding is a story of the past. Well, not if you’ve got to view old code. This is what you may get:

Can you read it?

Eclipse allows you to set the encoding in Edit / Set encoding, but unfortunately it only offers UTF variants and standard encoding (cp1252 and ASCII). But what it didn’t tell you is: you can type in the box and access other code pages, like in this example, I want to view a file encoded with code page 949 (Korean)

Code page dialog

And the result…

Properly encoded

Here’s a small list of encodings for your reference:

List of encodings

In Netbeans

You can only set encoding for the whole project, by right-clicking the project and set the encoding:

Netbeans project properties

This is why I prefer Netbeans: it have a list of ALL encodings listed, you can just pick one and doesn’t have to remember the above list.

The science of choices and hapiness

 There are moments in our lives when we find ourselves at a  crossroads. The choices we make in those moments can define the rest of  our days. Of course, when faced with the unknown, most of us prefer to  turn around and go back.

Source: http://waternymph.tumblr.com

There are moments in our lives when we find ourselves at a crossroads. The choices we make in those moments can define the rest of our days. Of course, when faced with the unknown, most of us prefer to turn around and go back.

It’s been a week since I descended onto this path. I feel like a fresher: afraid, fragile and stressful. Why? I bypassed an offer for such a great job. Maybe the salary at where I’m going could never compete with that job. A RMIT lecturer worked there too. That should tell you how interesting that job is. That compelled me to explore more. Why? It’s the choice I made after carefully considered the pro and cons. Why am I still haunted about my decision? Why do I still want more of something I can’t have any more?

Coincidentally, I got time to watch some TED presentations, and among the most favoured ones are these:

http://video.ted.com/assets/player/swf/EmbedPlayer.swf

Dan Gilbert: Why are we happy?

http://video.ted.com/assets/player/swf/EmbedPlayer.swf

Barry Schwartz on the paradox of choices.

I am biased against these talks at first because it’s natural human psychological behaviour to feel that way when things go against your expectations but I think they are right. Happiness is not something you will have eternally, it goes up and down with what you call “morale” or “emotion”. Your life goals have nothing to do with happiness, when you achieve it, the happiness is there but it won’t linger for long. It will be defeated with other matters like what you will eat for dinner and how will you survive the day. It’s your instinct to pursuit what make us happy but it’s your consciousness that decides which happy thing to have when there are many choices.

And that’s what tormented me.

I have more choice that other people. And a real choice, it’s not about choosing between rice or noodles for dinner, it’s about where I’m going for the next three years, it’s between taking an opportunity to achieve a life-long dream or living a nice life, which is also my target-to-be after I have my dream achieved.

It’s a choice I have to live with.

It’s natural that I get this feeling, being miserable for the choice I didn’t made, to find so many negative things that goes with my choice only after I’ve done it. Well, there is a bias working around here. Should I have take the other option, maybe I will find something negative about it too, especially when I doesn’t have as many data to evaluate it at the time, and there’s no way I can get more now.

Life is so crude, it make you push yourself, make choices that deep inside you just don’t want to make. But it’s a war of consciousness and desire. It’s what you will get along the way and in the end that matters. Sum them up and see which you like better. It’s easy to make a choice, you know you’ll do it any way, but it’s the preceding process of choice and the succeeding process of living the choice that’s hard mentally. But as another TED presentation have said, to be success you need to persist through CRAP, which is criticism, rejection, assholes and pressure, of which three comes from yourself.

  • Don’t criticize yourself about your choice, you know it’s hard to make and you’ll do exactly the same should things happened again.
  • Don’t reject yourself, no matter what you do, as long as you are striving, you’ll achieve something. It may be big or small, but you know you did your best provided you can’t turn back time.
  • Don’t pressure yourself,  you know humans doesn’t live well with stress, so there’s just no reason to be so pessimistic about the future. You don’t know what you’ll get, you can’t control it so blaming yourself doesn’t make things any better.

It’s so true that having choices and freedom may torment people, but the cure is also there, you can control your happiness, live positively, believe in yourself. It’s against common sense, people just won’t see why you are doing it, you are expected to be better. But hey, it’s your life not theirs!

In the end, I’m still glad life gave me so many choices, so many opportunities, so many ways I can live to my heart’s true desire :D. This is not the last time I have to make a choice. This path will lead to more choices. I hope the next time I have to choose, I will be glad I made the right choice, be a grown up and control my own life 🙂