challenge あみだくじ

次のような書式で与えられた「あみだくじ」があります。
(あみだくじはコード中に埋め込んでも、標準入力や
外部ファイルから読み込んでも、書きやすい方法でかまいません)

A B C D E
| | |-| |
|-| | |-|
| |-| |-|
|-| |-| |
|-| | | |

このあみだくじをたどって
A B C D E
| | |-| |
|-| | |-|
| |-| |-|
|-| |-| |
|-| | | |
B D C A E
のように結果を表示させるプログラムを作ってください。

Posted feedbacks - Common Lisp

全体のあみだくじの文字列をamidaに渡すと、結果の文字列を返します。

(princ

(amida

"A B C D E

| | |-| |

|-| | |-|

| |-| |-|

|-| |-| |

|-| | | |"))

;=>

A B C D E

| | |-| |

|-| | |-|

| |-| |-|

|-| |-| |

|-| | | |

B D C A E

||<

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
(require :cl-ppcre)

(defun amida (amida)
  (with-input-from-string (str amida)
    (let ((items (ppcre:split "\\s*" (read-line str nil nil))))
      (do ((line (read-line str nil :eof) (read-line str nil :eof)))
          ((eq :eof line) (format nil "~A~%~{~A~^ ~}" amida items))
        (exch line items)))))

(defun exch (pat items)
  (do ((pos (ppcre:all-matches "-" pat) (cddr pos)))
      ((endp pos) items)
    (let ((p (truncate (car pos) 2)))
      (rotatef (nth p items) (nth (1+ p) items)))))

Index

Feed

Other

Link

Pathtraq

loading...