[home] [PDF Version]

Misc Tech : Connect 4 Maths

Originally published 27th October 2003

I get an email like this from time to time:

Im doing some gsce courswork at the moment and our aim is to investigate the number of wiining lines in the game connect 4.we have to find a series of formulas. Do you have any info which would help me?

So here's my stock answer:

	Let your grid be x by y squares large
Let the length of a solution be n squares

(So in a standard game, x=7, y=6, n=4)

horizontal lines = y * (x-n) (NOTE: while x-n > 0)
vertical lines = x * (y-n) (NOTE: while y-n > 0)
diagonal lines = 2 * (x-n) * (y-n) (NOTE: while x-n > 0 and y-n > 0)

total lines = (y * (x-n)) + (x * (y-n)) + (2 * (x-n) * (y-n))

If x-n or y-n are 0 or less, then the board is too small to fit a horizontal or vertical winning line in. Obviously this means the game is unplayable (e.g. playing connect 4 on a 3 by 3 grid) but is worth remembering when working out the formulas.

Here's a bit of an extension:

	Let your grid be x by y squares large
Let the solution line be a by b squares large (for solution rectangles)

(So in a standard game, x=7, y=6, a=4, b=1)

horizontal lines = (y-(b-1)) * (x-a)
vertical lines = (x-(b-1)) * (y-a)
diagonal lines = 2 * (x-(a+b-1)) * (y-(a+b-1))

total lines = ((y-(b-1)) * (x-a)) + ((x-(b-1)) * (y-a)) + (2 * (x-(a+b-1)) * (y-(a+b-1)))

If you want to start getting fancy, consider 3 dimensional grids. Infact, you can quite easily find a general solution for a grid that's a1,a2,a3...an in size, with a winning line of b1,b2,b3...bn in size. I'll leave that one for you to work out ;)