Open Source WEB

2006-07-31 [Haskell] 入試問題(その10)

http://www.i.u-tokyo.ac.jp/edu/course/ci/pdf/ci-2006-programming-2nd.pdf の最後の問題,問題 4 にも挑戦してみよう.

この問題は付け加えられたルールがちょっと解りにくい. セルが削除された場合,インデックスの大きい側から詰めるとするのが簡単だが,

ただし,c0 が削除された場合は,もとの cn-1 つまり左のセルが c0 の位置 に入る.

とある.このただし書きは,c0を特別扱いすることが意図だと解釈すると. 関数 extrarule :: CellSpace -> CellSpace は

-- Problem 4

extrarule :: CellSpace -> CellSpace
extrarule cs
 = case grouping cs of
     (n,gs@(g:_)) -> case n of
                       -1 -> cs'
                       0  -> if length g >= 3
                               then case head g of
                                      0 -> rotateL 1 cs'
                                      1 -> rotateR 1 cs' -- c0を特別扱い
                               else cs' 
                       _  -> rotateR n cs'
                     where cs' = concatMap add0del1 gs

grouping :: [Int] -> (Int, [[Int]])
grouping xs 
 = if ngs == 1 
     then (-1, gs)
     else if even ngs 
            then (0, gs)
            else case splitAt (ngs - 1) gs of
                   (hg:gs,[lg]) -> (length hg, gs++[lg++hg])
   where gs  = group xs
         ngs = length gs

add0del1 :: [Int] -> [Int]
add0del1 xs@(0:_) = if length xs >= 3 then 0:xs else xs
add0del1 xs@(1:_) = if length xs >= 3 then tail xs else xs

ただし書きを無視すると,extrarule 関数の定義は

extrarule :: CellSpace -> CellSpace
extrarule cs
 = case grouping cs of
     (n,gs@(g:_)) -> case n of
                       -1 -> cs'
                       0  -> if length g >= 3
                               then case head g of
                                      0 -> rotateL 1 cs'
                                      1 -> cs' -- 但し書きを無視
                               else cs' 
                       _  -> rotateR n cs'
                     where cs' = concatMap add0del1 gs

となる.ううむ.

--nobsun


Name:
Comment:

There is no comment.

このサイトは、 IPA の「平成15年度オープンソフトウエア活用基盤整備事業」 の委託事業として開発されたKahuaで試験的に運用しております。

Copyright (c) 2004-2007 株式会社タイムインターメディア About Us