Time for an 2014 update…

This commit is contained in:
Ingy döt Net 2014-01-17 05:32:22 +00:00
parent 372c577f83
commit 09687c4926
2520 changed files with 34227 additions and 7318 deletions

View file

@ -1,28 +1,18 @@
module Main where
import Data.Bits
import Data.Char
import Numeric
import Text.Printf
main = mapM_ (putStrLn . flip grayconvstr 5) [0..31]
-- Conversion to and from traditional binary and Gray code
grayToBin :: (Integral t, Bits t) => t -> t
grayToBin 0 = 0
grayToBin g = g `xor` (grayToBin $ g `shiftR` 1)
-- Convert number to bit list, MSB first. Second argument is minimum width.
num2bin :: (Integral t) => t -> t -> [t]
num2bin n w = num2bin' n w [] where
num2bin' n w acc | n <= 0 && w <= 0 = acc
| otherwise = num2bin' m (w-1) (b:acc)
where (m, b) = divMod n 2
binToGray :: (Integral t, Bits t) => t -> t
binToGray b = b `xor` (b `shiftR` 1)
xor2 :: (Integral t) => t -> t -> t
xor2 x y = (x + y) `mod` 2
bin2gray :: (Integral t) => [t] -> [t]
bin2gray [] = []
bin2gray (x:xs) = x : zipWith xor2 xs (x:xs)
gray2bin :: (Integral t) => [t] -> [t]
gray2bin = scanl1 xor2
-- Prettyprinting, since it is in the task description...
grayconvstr :: (Integral t, Show t) => t -> t -> String
grayconvstr n w = (show n) ++ ": " ++ (show b) ++ " => " ++ (show g) ++ " => " ++ (show u)
where
b = num2bin n w
g = bin2gray b
u = gray2bin g
-- Print the first 32 Gray codes alongside their decimal and binary equivalences.
main = flip mapM_ (take 32 [0,1..] :: [Int]) (\num -> do
let bin = showIntAtBase 2 intToDigit num ""
gray = showIntAtBase 2 intToDigit (binToGray num) ""
printf "int: %2d -> bin: %5s -> gray: %5s\n" num bin gray)