【发布时间】:2016-08-08 22:52:31
【问题描述】:
我尝试使用 Racket 解决这个难题 https://puzzling.stackexchange.com/questions/40094/who-committed-the-crime。
一个人作案,犯罪嫌疑人5人。每个 嫌疑人在测谎仪下被问及他们认为谁犯了罪。
他们的答案如下:
Terry : It wasn't Carl, It was Steve
Steve : It wasn't Matt, It wasn't Carl
Matt : It was Carl, It wasn't Terry
Ben : It was Matt, It was Steve
Carl : It was Ben, It wasn't Terry
测谎仪显示 每个嫌疑人都说了一个谎言和一个真相。谁犯了罪?
以下是我的代码:
(define (oneof a b)
(or (and a (not b)) (and b (not a))))
(for ((i 5))
(define templist (list #f #f #f #f #f)) ; make a temporary list of all false;
(set! templist (list-set templist i #t)) ; one by one keep one as true in this loop;
(define t (list-ref templist 0)) ; allocate each person according to above list (one kept true one by one)
(define s (list-ref templist 1))
(define m (list-ref templist 2))
(define b (list-ref templist 3))
(define c (list-ref templist 4))
(when ; test if all statements fit with above assignment:
(and
(oneof (not c) s) ; Terry's statement
(oneof (not m) (not c)) ; Steve's statement
(oneof c (not t)) ; Matt's statement
(oneof m s) ; Ben's statement
(oneof b (not t))) ; Carl's statement
(println (list "t" "s" "m" "b" "c")) ; print allocation if all statement fit in;
(println templist)))
输出表明马特犯了罪:
'("t" "s" "m" "b" "c")
'(#f #f #t #f #f)
它可以工作,但代码是命令式的并且不是很实用(尤其是定义 t、定义 s、... 部分)。如何改进?感谢您的 cmets/答案。
【问题讨论】:
-
代码审查 SO 会更合适。