Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

How many ways can you tile a chessboard with dominoes?

$
0
0

Suppose you have an n by m chessboard. How many ways can you coverthe chessboard with dominoes?

It turns out there’s a remarkable closed-form solution:


How many ways can you tile a chessboard with dominoes?

Here are some questions you may have.

But what ifn andm are both odd? You can’t tile such a board with dominoes.

Yes, in that case the formula evaluates to zero.

Do you need an absolute value somewhere? Or a floor or ceiling?

No. It looks like the double product could be a general complex number, but it’s real. In fact, it’s always the square of an integer.

Does it work numerically?

Apparently so. If you evaluated the product in a package that could symbolically manipulate the cosines, the result would be exact. In floating point it cannot be, but at least in my experiments the result is correct when rounded to the nearest integer. For example, there are 12,988,816 ways to tile a standard 8 by 8 chessboard with dominoes, and the following python script returns 12988816.0. For sufficiently large arguments the result will not always round to the correct answer, but for moderate-sized arguments it should.

from numpy import pi, cos, sqrt def num_tilings(m, n): prod = 1 for k in range(1, m+1): for l in range(1, n+1): prod *= 2*cos(pi*k/(m+1)) + 2j*cos(pi*l/(n+1)) return sqrt(abs(prod)) print(num_tilings(8,8))

The code looks wrong. Shouldn’t the ranges go up to m and n ?

No, Python ranges are half-open intervals. range(a, b) goes from a to b-1 . That looks unnecessarily complicated, but it makes some things easier.

You said that there was no need for absolute values, but you code has one.

Yes, because while in theory the imaginary part will be exactly zero, in floating point arithmeticthe imaginary partmight be small but not zero.

Where did you find this formula?

Thirty-three Miniatures: Mathematical and Algorithmic Applications of Linear Algebra


Viewing all articles
Browse latest Browse all 9596

Trending Articles