Monkey Multiplication Table Problem

This is a response to R. Andrews post here. I have dubbed it, “The Monkey Multiplication Problem.” it was fairly neat, and I was going to post a response in the comments of his LJ, but I didn’t want to bother to sign up for an account over there, so instead I’ll post it here.

Enjoy. And forgive the lack of comments.
I managed to do it in 9 lines of haskell (not including module, import, or type declarations) however, I don’t have any datasets larger than your 12×12 table to test against, the printout is kind of funny looking, it’s designed so that you turn it 45 or so degrees clockwise and it looks right, (comes from the fact that I generate it by columns)

code follows (17 lines, with spaces and extra decls)

module Table where
import Data.List

genTable :: Int -> [[((Int, Int), Int)]]
genTable max = map (genCol max) [1..max]

genCol :: Int -> Int -> [((Int, Int), Int)]
genCol max n = [((n,n), n*n)]
	     ++ zip z (map (\(x,y) -> x*y) z)
	where z = zip [max, max - 1 .. n + 1]  (repeat n)

printTable :: Show a => [[a]] -> IO ()
printTable = putStrLn
	   $ concat
	   $ intersperse "\n"
	   $ map (concatMap (\x -> show x ++ " "))

monkeyTable = printTable $ map (map (snd)) $ transpose $ genTable 12

You can load that up in ghci and type in “monkeyTable” to get the printout, printTable, btw, is general enough to apply to anything- so if you’d like to see the internal structure of the table, you can switch that “map (map (snd))” to “map (map (fst))”. note that the ugliness of the monkeyTable function is from the fact that I used tuples instead of a customized datatype, or just a more specific genCol function.

Anywho, fun problem, I think I might use it in my local coding dojo, have fun!


Published in: on December 30, 2007 at 4:25 am  Leave a Comment  
Tags: , , ,