17 April 2012

Input Redirection in GDB (MinGW)

When using GDB to debug my program, I ran into a problem that GDB cannot accept my input redirection, because the GDB provided with MinGW passes on verbatim all arguments including redirects to the debugee.

I have found several solutions to solve this problem on the Internet, which I decide to write down here in case that I forget them.
  1. Parsing a -i ifile argument using argc and argv to get input from ifile instead of stdin and parsing a -o ofile to write output to ofile instead of stdout.
  2. Setting symbols for the debugee while compiling (gcc -g), and proceeding in the following manner:
    (gdb) b main
    (gdb) r non-redirect-arguments-if-any
    (gdb) p dup2(open("input.txt", 0), 0)
    (gdb) c

Sudoku Solving Program

Although very busy with my master thesis, learning French and final exam (and the exams of my girlfriend's), I thought I should set some time apart to do something interesting. That is why this blog has been started. The first thing I do is to write some code to solve Sudoku. The codes (written in C) and the executive file can be found here.

Basically it is not a hard problem, though it has token me a lot of time to find a bug due to a wrong subscript of an array. Things like that always happen, sadly. The basic idea is depth-first search for each empty cell we list all the possibilities, guessing one of them, and then eliminate the possibilities of the relative cells (namely the cells in the same row, same column and the same 3 by 3 block).

Usage of the executive is very simple. You input the numbers given in the puzzle, and use 0 to represent empty cell. You can type in the numbers one by one after running the program without any arguments if you want, or you can put the numbers in a file and redirect the input stream to it. For the output you can do the same thing, viewing it directly on the screen or saving it to a file using the output redirection.

Here is an example to explain how it works. Suppose you have a file named input.txt, which contains the following numbers in a Sudoku puzzle, where 0 means empty cell:

0 0 0 0 2 0 0 7 4
0 0 1 0 0 0 0 0 0
6 0 8 3 0 5 0 0 0
0 0 0 8 0 0 0 0 9
0 1 4 0 9 0 7 3 0
3 0 0 0 0 1 0 0 0
0 0 0 7 0 6 5 0 2
0 0 0 0 0 0 1 0 0
2 6 0 0 1 0 0 0 0
To use them as the input of our program, we can type the following command in the system console:
sudoku <input.txt
Then you will see the output as:

5 3 9 1 2 8 6 7 4
4 2 1 9 6 7 8 5 3
6 7 8 3 4 5 9 2 1
7 5 6 8 3 4 2 1 9
8 1 4 6 9 2 7 3 5
3 9 2 5 7 1 4 6 8
1 4 3 7 8 6 5 9 2
9 8 7 2 5 3 1 4 6
2 6 5 4 1 9 3 8 7
That is the solution of the puzzle.