LoginSignup
2
2

More than 5 years have passed since last update.

もう少しだけFizzBuzzを

Last updated at Posted at 2014-01-22

そりゃ職業プログラマはFizzBuzzを5分以内に書けなきゃ大変にまずいだろうが、一般化しようとすると結構難しい(単純に分岐するやり方は使えない)。ついでにmodも使わないという方向で書くとこんな感じになるだろうか:

module Main where
import Data.List
import System.Environment (getArgs)

asocs = [ (3,"Fizz"), (5,"Buzz"), (7,"Kazz"), (11,"Pozz") ]

mkWords = map (\(n,w) -> (cycle $ (genericTake (n-1) $ repeat [])++[w]))

fizzbuzz n = zipWith compose (map concat $ transpose $ mkWords asocs) [1..n]
   where compose [] n = show n
         compose fbs _ = fbs

main = do
  args <- getArgs
  let n = read $ args !! 0
  mapM_ putStrLn $ fizzbuzz n

元々のFizzBuzzは何も考えずにそのまま書くと:

module Main where
import System.Environment (getArgs)

fizzbuzz n
  |mod n 3 == 0 && mod n 5 == 0 = "FizzBuzz"
  |mod n 3 == 0 = "Fizz"
  |mod n 5 == 0 = "Buzz"
  |otherwise = show n

main = do
  args <- getArgs
  let n = read $ args !! 0
  mapM_ (putStrLn . fizzbuzz) [1..n]

これはghciで確かめながら書いてコンパイルしてバイナリ作るまでにぴったり5分。で、そこから冒頭の一般化したヴァージョンを書き始めて更に20分ちょっとかかった。

そういえば、Project Eulerは100問解いてから飽きて放置しているが、FizzBuzzですら微妙だったりするらしいということなら、Project Eulerの最初の方ですら新人プログラマの選考には難しすぎたりするんだろうか。IT業界と無縁な情弱文系には状況はまったくわからないのだが。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2