Solution of the Hat Problem