Skip to content

Instantly share code, notes, and snippets.

@khayrov
Created May 13, 2011 07:56
Show Gist options
  • Save khayrov/970169 to your computer and use it in GitHub Desktop.
Save khayrov/970169 to your computer and use it in GitHub Desktop.
Ulam spiral visualization
import Data.List
import Graphics.Gloss
import Graphics.Gloss.Data.Point
infixl 6 |+|
(x, y) |+| (x', y') = (x + x', y + y')
spiral = scanl (|+|) (0, 0) steps
where
steps = concat $ zipWith replicate sides (iterate r90ccw (1, 0))
sides = concatMap (replicate 2) $ map fromIntegral [1..]
r90ccw (x, y) = (-y, x)
primes :: [Int]
primes = 2 : 3 : filter isPrime [5, 7 ..]
where
isPrime n = and [n `mod` i /= 0 |
i <- takeWhile (\i -> i * i <= n) (tail primes)]
primesMask = merge [1..] primes
where
merge (n : nt) ps@(p : pt)
| n == p = True : merge nt pt
| otherwise = False : merge nt ps
side = 600
picture = color black $ pictures $ [translate x y (rectangleSolid 1 1) |
(x, y) <- takeWhile isVisible filteredSpiral]
where
filteredSpiral = map fst $ filter snd $ zip spiral primesMask
isVisible p = pointInBox p (side, side) (-side, -side)
main = displayInWindow "Ulam spiral" windowSize (100, 100) white picture
where windowSize = (round side, round side)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment