Skip to content

Instantly share code, notes, and snippets.

@ggreif
Last active November 18, 2015 10:25
Show Gist options
  • Save ggreif/9263e1a095917535b705 to your computer and use it in GitHub Desktop.
Save ggreif/9263e1a095917535b705 to your computer and use it in GitHub Desktop.
Given two coordinates, compute the Ulam spiral number at that place.
import Data.Char
ch = chr . (+65)
-- east quadrant
ulam x y | x > y && x > -y = (x*2 - 1)^2 + (x + y) - 1
-- north quadrant
ulam x y | x <= y && x > -y = (y*2)^2 - (x + y)
-- west quadrant
ulam x y | x <= y && x <= -y = (x*2)^2 - (x + y)
-- south quadrant (default)
ulam x y = (y*2 - 1)^2 + (x + y) - 1
matrix = [[ch $ ulam x y | x <- [-4 .. 4]] | y <- reverse [-4 .. 4]]
vis = mapM_ putStrLn matrix
primes = [2,3] ++ filter isPrime [5,7 ..]
isPrime x = and [x `rem` p /= 0 | p <- takeWhile (\p -> p*p <= x) primes]
pmatrix :: Int -> [String]
pmatrix w = [[test $ ulam x y | x <- [-w .. w]] | y <- reverse [-w .. w]]
where test n = ch $ isPrime (n + 2)
ch True = '@'
ch _ = ' '
prvis w = mapM_ putStrLn (pmatrix w)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment