Skip to content

Instantly share code, notes, and snippets.

@PkmX
Created October 6, 2012 02:31
Show Gist options
  • Save PkmX/3843511 to your computer and use it in GitHub Desktop.
Save PkmX/3843511 to your computer and use it in GitHub Desktop.
strobogrammatic numbers
import Control.Applicative
import Control.Monad
import Control.DeepSeq
import Data.List
import System.Environment
--
{-
strobo' :: Int -> [String]
strobo' n
| n <= 0 = [""]
| n == 1 = ["0", "1", "8"]
| otherwise =
let surrounders = fmap surround [('0', '0'), ('1', '1'), ('6', '9'), ('8', '8'), ('9', '6')]
in surrounders <*> strobo' (n - 2)
where
surround (x, y) xs = x : xs ++ [y]
strobo :: Int -> [String]
strobo = filter predicate . strobo'
where predicate = (||) <$> (/=) '0' . head <*> (==) 1 . length
-}
strobo'' :: Int -> [String]
strobo'' n
| n <= 0 = error "Must be positive"
| n <= 2 = ["1", "9", "8", "6"]
| otherwise = (flip (:)) <$> strobo'' (n - 2) <*> ['0', '1', '9', '8', '6']
strobo' :: Int -> [String]
strobo' n
| n <= 0 = error "Must be positive"
| n == 1 = ["0", "1", "8"]
| n == 2 = ["1", "9", "8", "6"]
| otherwise = (flip (:)) <$> strobo'' (n - 2) <*> (if odd n then ['0', '1', '8'] else ['0', '1', '9', '8', '6'])
strobo :: Int -> [String]
strobo n
| odd n = map (foldl' f <$> tail <*> id) $ strobo' n
| otherwise = map (foldl' f <$> id <*> id) $ strobo' n
where
f acc '6' = '9' : acc
f acc '9' = '6' : acc
f acc x = x : acc
sn :: [String]
sn = join $ map strobo [1..]
--
main :: IO ()
main = do
args <- getArgs
case args of
"interactive":_ -> forever $ do
n <- read <$> getLine
putStrLn $ sn !! (n - 1)
"digits":n:_ ->
(join $ map strobo [1..read n]) `deepseq` return ()
_ ->
mapM_ putStrLn $ sn
HC := ghc
HFLAGS := -O2 -Wall
LDFLAGS := -package deepseq -rtsopts
SRCS := Main.hs
OBJS := $(SRCS:.hs=.o)
INTS := $(SRCS:.hs=.hi)
PROG := run
.PHONY: all clean
all: $(PROG)
$(PROG): $(OBJS)
$(HC) $(LDFLAGS) $^ -o $@
%.o: %.hs
$(HC) $(HFLAGS) -c $< -o $@
clean:
-rm $(PROG) $(INTS) $(OBJS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment