0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

第7回オフラインリアルタイムどう書く。Haskell による実装。

Last updated at Posted at 2013-02-07

問題は http://nabetani.sakura.ne.jp/hena/ord7selectchair/
解答リンク集は http://qiita.com/items/4364285801d1c9f370a1

面白そうな問題だったので、Haskell で実装してみました。
座席の両端に座れない空席を置いて判定を単純化してみようと頑張ってみまし
た。

off-line07.hs
import Data.Char
import System.Environment

main :: IO ()
main = do arg <- getArgs
          let (n, str) = getData (arg !! 0)
          print $ solve n str

getData :: String -> (Int, String)
getData cs = (read a, tail b)
  where (a, b) = break (== ':') cs

solve :: Int -> String -> String
solve n cs = init $ tail $ foldl f (replicate (n + 2) '-') cs
  where f seat c = if (isUpper c) then sit c seat else rm (toUpper c) seat

sit :: Char -> String -> String
sit c cs = as ++ (c : bs)
  where
    (as, _ : bs) = splitAt (search cs) cs
    search cs@(_ : cs')
      | take 2 cs == "--" = search' 0 ( 1, -1) cs
      | otherwise         = search' 1 (-1, -1) cs'
    -- search' c (i1, i2) cs
    --  c : index counter
    --  i1, i2 : 「条件 2」と「条件 3」に適合する index
    search' _ (i1, i2) "-" = if i1 < 0 then i2 else i1
    search' c (i1, i2) cs@(s : cs')
      | take 3 cs == "---"              = c + 1
      | (i1 < 0) && (take 2 cs == "--") = search' (c + 1) ( c, i2) cs'
      | (i2 < 0) && (s == '-')          = search' (c + 1) (i1,  c) cs'
      | otherwise                       = search' (c + 1) (i1, i2) cs'

rm :: Char -> String -> String
rm c cs = as ++ ('-' : bs)
  where (as, _ : bs) = break (== c) cs
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?