Recursive Sudoku solver

I got back to coding after a long absence cause mainly by the final exams. My first project was to implement a recursive Sudoku solver.

I had previously written an iterative Sudoku solver that makes use of the same techniques that people do by ruling out what numbers can fit in a cell untill there is only one possible number that can fir. However, this method fails on harder puzzles where a guess has to be made in order to solve the puzzle.

Brute force algorithms enter here. The Sudoku puzzle lends itself well to the classic recursive brute force algorithm,

The step by step algorithm:

  1. If puzzle is solved
    1. End
  2. If puzzle is not valid
    1. End
  3. Find first empty cell : cell that contains 0
  4. While the cell value is less than 10 and while the puzzle is unsolved
    1. Increment cell by 1
    2. Solve
  5. If the cell value is greater than 9
    1. Reset the cell value to 0 : This means that a previous guess was invalid so this ends and the previous cell value is incremented

Mapping the random function

As described over here, the rand() function in C++ is a pseudo random generator that returns a number between 0 and RAND_MAX. This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using srand.

RAND_MAX is a constant defined in <cstdlib>

But just how random is the rand() function. Its easy to find out by calling the function and comparing how often different values are returned. I do this graphically using OpenGL code to render the graph.

Using fraps, I recorded the variation of outputs from the rand() function.

The graph tends towards a straight line indicating that the more often you call the rand() function, the more even its distribution.

Project Euler # 18

Project Euler # 18

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 4
4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)

Brute Force

The obvious solution is to brute force the solution by trying every possible route, through recursion. However, since at each junction the path branches into two, there will be 214 = 16384 routes. With a 100 rows, there will be 299 rows, which is way too much to brute force!

Non – Obvious method

Logic:
Let us understand this with the help of this small triangle:

3
7 4
4 6
8 5 9 3

Each element can lead to the element directly below, or the element directly below and to the right.

Assuming a given element is a point on the solution path, the next element has to be the greatest of the two possible elements. Thus add the greatest number below a given number to it and iterate upwards. This is demonstrated on the small triangle.

Original:

3
7 4
4 6
8 5 9 3

Add bottom row elements to the top.

8 > 5

9 > 5

9 > 3

3
7 4
10 13 15
8 5 9 3

Add the new row to the row above it.

10 < 13

13 < 15

3
20 19
10 13 15
8 5 9 3

And again, add the new row, this time to the topmost row.

20  > 19

23
20 19
10 13 15
8 5 9 3

The topmost element is the largest sum!

Source in C++

Data file containing triangle (Program reads from this file)

Note: You can use this to solve problem 67 as well. Remember to change array sizes, iteration limits and the data file!

Minesweeper

When Vista came out, Microsoft did away with the classic Minesweeper game that they distributed with Windows XP. So, for my own entertainment and that of the general public, I decided to create my own implementation 😛

 

Board Screenshot

Its written in C++, with openGL for graphics, and the SOIL library for texture loading.

Menu Screenshot

Windows Installer

Source

Basketball

My very first sports game! A simple basketball game. Get the ball into the basket. No nonsense, really. The physics for this game was relatively simple. And fun. But then again, physics is always fun.

The key here is to setup a good aiming system. The game builds itself around that. One of the best solutions is to represent exactly half the parabolic path of the ball. The player will still have to judge the path of the ball, but the portion that we show on the screen would give him an idea of the velocity and angle.

Our interest is in calculating the path of the ball, which is determined by two parameters:

  • The velocity
  • The launch angle

Given that the mouse pointer represents the highest point on the parabolic path, both launch velocity and launch angle can be calculated. It’s really simple (should you have taken physics in high school).

Parabolic path of the ball

 

In the above equations R is the range of the projectile and H is the maximum height to which it rises. It’s easy to see why, for a given position of the mouse, R and H are constants that can be calculated. Rearranging and solving these equations will give us the velocity and angle which is what we need to describe the motion. The velocity will then be resolved into components, for convenience.

The game depends on a few libraries like SOIL for texture loading, freeglut for openGL and irrKlang for audio.

Coming up next is a version with highscore tables! Gotta learn a little php for that 😛

Edit: High score table is live but a little buggy.

Available on gumroad:
Basketball

Source

Tower Defense

First tower defense game 😀 Of course, it doesn’t have all the bells and whistles of commercial games. But it’s simple enough to play a couple of times.

If this project taught me anything, it’s that some things are easier with Vectors. The key to any good tower defense game is predicting the path of the enemy in order to hit!

Diagrammatic representation

Simply aiming at the enemy when you’re about to fire is no good. He isn’t likely to hang around there for two long!
The problem and its givens are listed:

We know,

  • The position of the enemy(which moves) at the time of firing
  • The position of the gun (which doesn’t move)
  • The absolute velocity (speed) of the bullet. (The direction is what we need to determine).
  • The direction and magnitude of the velocity of the enemy

My approach was as follows:

In order to hit the enemy, the final position of the bullet and the enemy must be the same. Also, in time t, the displacement of the bullet and the enemy must be equal. This is written vectorially as:

Which on expanding,


And on squaring and rearranging,

Where cos θ is given by,

Solving this equation using the quadratic formula, and selecting the positive root (since time can’t be negative, in this discussion), will give us the time after which the bullet and the enemy will collide.

Velocity of the bullet is then given by:

Keep in mind that they’re all vectors, so you need to write appropriate classes/structures to deal with them.

Game Screenshot

Source

Executable (Windows) 

Making Paint.

Recently, I took on a project that turned out to be real fun. I attempted to recreate paint. With OpenGL handling the drawing, it was a task to find a good UI library that integrated OpenGL code. An obvious solution would be to use Win32 controls but they’re cumbersome and difficult to use. GLUI turned out to be a disappointment as well, as it refused to work with Visual Studio without the dll. Finally, FLTK provided a much needed break. It’s pretty spiffy as far as GUI libraries go, is cross platform as well.

It’s also the first time I’ve split a project onto a more than 3 source files;
Screenshots:

 

Source

Release (Windows) 

Tetris

Roses are red,
Violets are Blue,
In Soviet Russia,
Tetris plays you

Tetris is a tile-matching puzzle video game originally designed and programmed byAlexey Pajitnov in the Soviet Union. It was released on June 6, 1984. Over the years, Tetris has been released on several platforms, from Nintendo’s NES to the iPhone.

I have attempted to remake Tetris, keeping most of the basic features intact. The game features the original soundtrack as well. 🙂
My version of Tetris is written in C++. I use OpenGL (GLFW Library) to draw, the SOIL library for texture loading, and the irrKlang Library for audio.

Download the C++ source

Download the release 

Note: You need to have the VC Redist installed on your PC

Project Euler – Problem 10

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Problem 10 is reasonably demanding. Unless you are familiar with Eratosthenes Sieve method (or any other sieve method), solving this problem in less than a minute will be next to impossible.

Sieve of Eratosthenes

In mathematics, the sieve of Eratosthenes , one of a number of prime number sieves, is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2.
Wikipedia Entry

General Algorithm

Above is a visual representation of the algorithm. Now, we must translate it into program code, in order to solve the problem.

  1. Declare an Boolean array with 2,000,000 elements (since we want to find primes less than 2 million).
  2. Fill the entire array with ‘true’ or 1. By doing this, we are assuming that all the numbers are prime. We will now “cross out” (mark false) those numbers which are multiples of other numbers.
  3. For each value of ifrom 2 to 2000000:
    1. Visit the ith element of the array. If it is true, then:
      1. For each element (j) which is a multiple of i, change the value of array[j]to false.
      2. Add the value of i to the sum.
    2. Else, continue iterating.
  4. Print the sum.

On my machine, the program takes about 0.063 seconds to run. It’s slightly memory intensive, requiring an array of 2000000 bytes to be allocated, but it can’t be helped.
If you know of some other prime number sieve which works faster, do let me know.

Solution in C++ 

Project Euler – Problem 9

Problem 9 is sort of easy too! 🙂

The problem statement is as follows:

A Pythagorean triplet is a set of three natural numbers, a<b<c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Knowing a little maths can take you a long way in this problem.

Mathematical Discussion

(skip this it bores you. The problem can still be solved without it)

Knowing this can cut your run time from 0.291 seconds to 0.001 seconds (as measured by the ctime library), which is basically 99.6% faster!

Basically, Pythagorean Triplets are an expression for possible integral values of the sides of a right angled triangle. Armed with this little nugget of knowledge, we can effectively reduce the iterations that we have to go through to find the required triplet.

General Algorithm

  1. We know that a + b + c = 1000.
  2. Therefore, m2 n2 + 2mn + m2 + n2 = 1000. So, 2m2 + 2mn = 1000.
  3. We now attempt to get the answer by applying brute force on the above expression, rather than plugging in all possible values of a, b and c.
  4. I believe that the brute force method merits no discussion. It has been included in the source, for comparison with the above method.

Solution in C++