Prisoner Hat Riddle in MATLAB

Shahid Karim Mallick
2 min readJul 1, 2016

--

Riddles are fun. I’ve been tackling a few lately, and I found this TED-Ed series to be pretty good.

This one is my favorite riddle:

I liked it so much that I decided to make a little game to simulate it for any number of people (n):

Odds and evens are the key to this game. The tallest person has an opportunity to reveal to the rest of the line if he/she sees an odd or even number of black hats. Since the group is allowed to come up with a strategy, it must decide what the code will be. For instance, if the tallest person says “black,” that means he/she sees an odd number of black hats. This allows everyone else in line to correctly determine the color of their hats.

The game requires each person in line to keep track of the previous responses, in order to determine if there are an even or odd number of black/white hats remaining.

I wrote the code from the perspective of every person in line, starting from the tallest person. That is, I went through the observations and decisions that each person must make in order to answer correctly.

The figure below shows the original hat assignment compared to the answers my program calculated each person should give. As you can see, because the tallest person said “white,” indicating that she saw an even number of black hats, everyone else in line was able to guess their hat color and save themselves.

The challenging part of this program wasn’t the code determining each person’s response. It was actually figuring out how to store an array of jpegs and display it in a figure (answer: store images in a cell array and convert to a matrix before plotting).

Check out my Github for the MATLAB file.

My next logic project is a bit more advanced and visually informative: a Monte Carlo simulation of Penney’s Game!

--

--

Shahid Karim Mallick

I build natural interfaces (see my latest work at smallick.com). Studied neuroscience @BrownUniversity. Product @NeoSensory, previously @CalaHealth