アインシュタインの謎を解く


19

アインシュタインはなぞなぞを書いた。彼は、世界の98%がそれを解決できなかったと言いました。

電車に乗って仕事をしながら約25分でこの謎を解きました。基本的には単なる控除です。

なぞなぞ

5つの異なる色の家が5つ並んでいます。
各家には異なる国籍の人が住んでいます。
5人の所有者は特定の種類の飲料を飲み、特定のブランドの葉巻を吸って、特定のペットを飼っています。
同じペットを持っている所有者、同じブランドの葉巻を吸う所有者、または同じ飲み物を飲む所有者はいません。
質問: 魚の所有者は誰ですか?

この謎を解決するために、アインシュタインは15のヒントを提供します。

  1. ブリットは赤い家に住んでいます。
  2. スウェーデン人は犬をペットとして飼っています。
  3. デーンはお茶を飲みます。
  4. グリーンハウスはホワイトハウスのすぐ左にあります。
  5. 温室の所有者はコーヒーを飲みます。
  6. ポールモールを吸う飼い主は鳥を飼っています。
  7. 黄色い家の所有者はダンヒルを吸っています。
  8. センターハウスに住んでいる所有者は牛乳を飲みます。
  9. ノルウェー人は最初の家に住んでいます。
  10. ブレンドを吸う飼い主は、猫を飼っている飼い主の隣に住んでいます。
  11. 馬を飼っている飼い主は、ダンヒルを吸う人の隣に住んでいます。
  12. ブルーマスターズを吸うオーナーはビールを飲みます。
  13. ドイツ人は王子を吸う。
  14. ノルウェー人は青い家の隣に住んでいます。
  15. Blendsを吸う所有者は、水を飲む人の隣に住んでいます。

これらのヒントを使用して、解決策を見つけることができます。

あなたの仕事:この謎を解決するプログラムを作成してください。ソリューションのハードコーディングは許可されません(duh)

ヒントは任意の形式でハードコードできます。
形式の例:

//Hints in order
(Nationality:Brit)==(Color:Red)
(Nationality:Swede)==(Pet:Dogs)
(Nationality:Dane)==(Drink: Tea)
(Color:Green)/(Color:White)
(Color:Green)==(Drink:Coffee)
(Smoke:PallMall)==(Pet:Birds)
(Color:Yellow)==(Smoke:Dunhill)
(House:3)==(Drink:Milk)
(Nationality:Norwegian)==(House:1)
(Smoke:Blend)/\(Pet:Cats)

==は次と等しいことを 意味します\の
左側にある
ことを意味します
/ \の 右側にあることを意味します

私が言ったように、ヒントをハードコードするか、入力として持つことができます。

出力:出力は次の形式である必要があります(正しい値を使用して、トロールのことを言っています;))

 _____________    _____________    _____________    _____________    _____________
|   Number    |  |   Number    |  |   Number    |  |   Number    |  |   Number    |
| Nationality |  | Nationality |  | Nationality |  | Nationality |  | Nationality |
|    Color    |  |    Color    |  |    Color    |  |    Color    |  |    Color    |
|    Drink    |  |    Drink    |  |    Drink    |  |    Drink    |  |    Drink    |
|    Smoke    |  |    Smoke    |  |    Smoke    |  |    Smoke    |  |    Smoke    |
|     Pet     |  |     Pet     |  |     Pet     |  |     Pet     |  |     Pet     |
---------------  ---------------  ---------------  ---------------  ---------------

The <Nationality> in the <Color> house owns the fish!

アスキーアートボックスは、ボックスである限り、どのシンボルを使用しても問題ありません。

この謎と解決策に関する知識は、プログラムで使用することできません。謎を解決するには、純粋な論理と演deを使用する必要があります。

これをcodegolfとしてタグ付けしましたが、コードの挑戦かもしれませんが、確かではありません。コードチャレンジの受賞基準に関するご意見はお気軽に共有してください:)

今のところ、これはコードゴルフであるため、バイトカウントが最小のプログラムが勝ちます。

幸運と幸せなコーディング:)


15
最初の段落の主張はほぼ間違いなく虚偽です。
ピーターテイラー

1
@PeterTaylorどういう意味ですか?98%とアインシュタインのビット?確かにそれを知っているだろう、interwebsはそれを言うと、私はそれを解決したときに関係なく、バックグラウンド:)のためにその楽しさは、私は「それらの2%にイェーイイム」を、特別に感じた
Teunプロンク

4
これらのビットの両方。インターウェブにはTimecubeも搭載されているため、特に証拠がない場合は、彼らが言うすべてを信じないようにしてください。
ピーターテイラー

1
@PeterTaylorはい、私は知っていますが、私が言ったように、背景の面白さはともかく、事実やフィクションが好きではないことは、与えられた問題にとって不可欠です。また、ウィキペディアは、それについての本当の証拠がないと述べています:)
テウンプロンク

3
ソリューションは、任意の数の家、プロパティ、およびヒントに一般化できるはずです。そうすれば、本当に「ハードコーディングなし」を原則としてスローする必要のない、本当に興味深い質問になります。私の経験では、どれだけハードコーディングなのかという疑問が常に生じます。
ランチャー

回答:


24

プロローグ-954キャラクター

m(A,Z):-member(A,Z).
e:-e(Z),w(Z).
e(Z):-Z=[[1,A,F,K,P,U],[2,B,G,L,Q,V],[3,C,H,M,R,W],[4,D,I,N,S,X],[5,E,J,O,T,Y]],m([_,b,r,_,_,_],Z),m([_,s,_,d,_,_],Z),m([_,d,_,_,t,_],Z),m([WH,_,w,_,_,_],Z),m([GH,_,g,_,_,_],Z),GH=:=WH-1,m([_,_,g,_,c,_],Z),m([_,_,_,b,_,p],Z),m([_,_,y,_,_,d],Z),m([3,_,_,_,m,_],Z),m([1,n,_,_,_,_],Z),m([BH,_,_,_,_,b],Z),m([CH,_,_,c,_,_],Z),(BH=:=CH+1;BH=:=CH-1),m([DH,_,_,_,_,d],Z),m([HH,_,_,h,_,_],Z),(HH=:=DH+1;HH=:=DH-1),m([_,_,_,_,b,l],Z),m([_,g,_,_,_,r],Z),m([NH,n,_,_,_,_],Z),m([YH,_,b,_,_,_],Z),(NH=:=YH+1;NH=:=YH-1),m([SH,_,_,_,_,b],Z),m([XH,_,_,_,w,_],Z),(SH=:=XH+1;SH=:=XH-1),p([n,d,b,g,s],[A,B,C,D,E]),p([y,b,r,g,w],[F,G,H,I,J]),p([c,h,b,f,d],[K,L,M,N,O]),p([w,t,m,c,b],[P,Q,R,S,T]),p([d,b,p,r,l],[U,V,W,X,Y]).
t(X,[X|R],R).
t(X,[F|R],[F|S]):-t(X,R,S).
p([W|X],Y):-p(X,V),t(W,Y,V).
p([],[]).
b:-write('+--+--+--+--+--+--+'),nl.
z(A):-writef('|%2L|%2L|%2L|%2L|%2L|%2L|',A),nl.
w([A,B,C,D,E]):-b,z(A),z(B),z(C),z(D),z(E),b.

出力

+--+--+--+--+--+--+
|1 |n |y |c |w |d |
|2 |d |b |h |t |b |
|3 |b |r |b |m |p |
|4 |g |g |f |c |r |
|5 |s |w |d |b |l |
+--+--+--+--+--+--+

キー:

  • 最初の列は家番号です。
  • 2列目は国籍です。
  • 3列目はお気に入りの色です。
  • 4列目はペットです。
  • 5列目は飲み物です。そして
  • 6列目はタバコです(r =王子、l =ブルーマスター)。

9
これは仕事に適した言語です。
マリヌス

ゴルフ番号を比較できるようにするために名前を綴るべきではありませんか?
blabla999

5

Ruby 322 +入力442

250億の可能な答えのブルートフォース検索。
私のコンピューターでこのプログラムを実行するには、約75日かかります。
このプログラムが正しい答えを出力するかどうかは確認しませんでした!

として実行 ruby riddle.rb < riddle.in

riddle.rb(332バイト)

g=readlines
v=g.shift(5).map &:split
c,*d=v.map{|a|[*a.permutation]}
c.product(*d){|a|(f=eval a.map{|b|b.each_with_index.map{|s,i|"#{s}=#{i}\n"}.join}.join+'g.map{|h|eval h}.all?&&fish')&&(r=['-----------']*5
puts [r,[*0..4],*a,r].map{|s|s.map{|t|'|%11s|'%t}.join},"The #{a[0][f]} in the #{a[1][f]} house owns the fish!")}

riddle.in(442バイト)

brit dane german norwegian swede
blue green red white yellow
beer coffee milk tea water
blends bluemasters dunhill pall_mall prince
birds cats dogs fish horse
brit==red
swede==dogs
dane==tea
green==white-1
green==coffee
pall_mall==birds
yellow==dunhill
2==milk
norwegian==0
blends==cats-1||blends==cats+1
horse==dunhill-1||horse==dunhill+1
bluemasters==beer
german==prince
norwegian==blue-1||norwegian==blue+1
blends==water-1||blends==water+1

入力ファイルには、5行の名前とそれに続く論理式の行が含まれている必要があります。家番号は0〜4 fishです。

プログラムはArray#permutation5回呼び出して、国籍、色、飲み物、煙、ペットの配列を注文するすべての方法を見つけます。長いループはc.product(*d){|a|...}Array#product約250億の可能な答えを繰り返すことを呼び出しています。ループ本体の形式は(f=eval ...)&&(...)です。eval ...一部には、論理式を評価します。すべてが当てはまる場合fは、魚の番地であり、&&(...)パートが答えを出力します。家番号0はRubyでは真です。

コードゴルフとは、スピードのためにコードを追加しないことを意味します!しかし、私はプログラムを実行するために75日を欠いています!


1
ブルートフォースの代わりに1つまたは2つの手がかりを使用しても、多くの検索を節約できます。
qwr 14年

私はRubyを知りませんが、インターネットはそれが遅いと言います。回答をコンパイル済みの言語に翻訳し、少しでも最適化すると、妥当な時間内に正確性を検証するために必要な5000%の高速化に近づきます(r?)。最も粗雑な、しかし十分に文書化されたJava翻訳でさえ書いたなら、私はそれをあなたのために最適化してから正しいことを確かめたいです。
レインボルト

4

プロローグ、653文字

a([],L,L).
a([H|T],L2,[H|L3]):-a(T,L2,L3).
m(X,L):-a(_,[X|_],L).
r(X,Y,L):-a(_,[X,Y|_],L).
n(X,Y,L):-r(X,Y,L);r(Y,X,L).
s:-s(S),w(S).
s(S):-length(S,5),m([b,r,_,_,_],S),m([s,_,_,_,d],S),m([d,_,t,_,_],S),r([_,g,_,_,_],[_,w,_,_,_],S),m([_,g,c,_,_],S),m([_,_,_,p,b],S),m([_,y,_,d,_],S),S=[_,_,[_,_,m,_,_],_,_],S=[[n,_,_,_,_],_,_,_,_],n([_,_,_,b,_],[_,_,_,_,c],S),n([_,_,_,d,_],[_,_,_,_,h],S),m([_,_,b,l,_],S),m([g,_,_,r,_],S),n([n,_,_,_,_],[_,b,_,_,_],S),n([_,_,_,b,_],[_,_,w,_,_],S),m([_,_,_,_,f],S).
b:-write('----------------+'),nl.
z(Y,A):-write(Y),writef('|%2L|%2L|%2L|%2L|%2L|',A),nl.
w([S1,S2,S3,S4,S5]):-b,z(1,S1),z(2,S2),z(3,S3),z(4,S4),z(5,S5),b.

1
コード内の不要なスペースや改行を自由に削除して、653文字まで削減しました。
16年

1
SWI-Prologでテストし、?? sと入力するだけです。
ej8000

3

Smalltalk 1332文字

単純なSmalltalkの使用:

|n c v g p t r|n:=#(Brit Swede Dane Norwegian German
Red Green White Yellow Blue
Tea Coffee Milk Beer Water
PallMall Dunhill Blends Bluemasters Prince
Dogs Birds Cats Horses Fish).
v:=Dictionary new.n do:[:n|v at:n put:nil].g:=n splitForSize:5.
c:={{[:b :r|b==r].#Brit.#Red}.{[:s :d|s==d].#Swede.#Dogs}.{[:d :t|d==t].#Dane.#Tea}.
{[:g :w|g==(w-1)].#Green.#White}.{[:g :c|g==c].#Green.#Coffee}.
{[:p :b|p==b].#PallMall.#Birds}.{[:y :d|y==d].#Yellow.#Dunhill}.
{[:m|m==3].#Milk}.{[:n|n==1].#Norwegian}.{[:b :c|(b-c)abs==1].#Blends.#Cats}.
{[:h :d|(h-d)abs==1].#Horses.#Dunhill}.{[:m :b|m==b].#Bluemasters.#Beer}.
{[:g :p|g==p].#German.#Prince}.{[:n :b|(n-b)abs==1].#Norwegian.#Blue}.
{[:b :w|(b-w)abs==1].#Blends.#Water}}.
t:=[:c|x:=(c from:2collect:[:n|v at:n]).(x includes:nil)or:[c first valueWithArguments:x]].
p:=[|f|(((''-'',* 16),'' ''),*5)printCR.g do:[:n||w|w:=n collect:[:n|v at:n].w sortWith:n.
n do:[:n|''|''print.(n centerPaddedTo:14)print.''| ''print].''''printCR.].(((''-'',* 16),'' ''),*5)printCR.
f:=v at:#Fish.(''The %1 in the %2 house owns the fish''bindWith:(g first detect:[:n|(v at:n)==f])with:((g at:2) detect:[:n|(v at:n)==f]))printCR].
r:=[:gi|gi==0ifTrue:p ifFalse:[#(1 2 3 4 5)permutationsDo:[:perm|v declareAll:(g at:gi)from:perm.
(c conform:t)ifTrue:[r value:gi-1]].v declareAll:(g at:gi)from:#(nil),*5]].
r value:g size.

出力:

---------------- ---------------- ---------------- ---------------- ---------------- 
|  Norwegian   | |     Dane     | |     Brit     | |    German    | |    Swede     | 
|    Yellow    | |     Blue     | |     Red      | |    Green     | |    White     | 
|    Water     | |     Tea      | |     Milk     | |    Coffee    | |     Beer     | 
|   Dunhill    | |    Blends    | |   PallMall   | |    Prince    | | Bluemasters  | 
|     Cats     | |    Horses    | |    Birds     | |     Fish     | |     Dogs     | 
---------------- ---------------- ---------------- ---------------- ----------------
The German in the Green house owns the fish

ゴルフ版はほとんど読めないので、読みやすいように適切な名前、インデント、スペースを含む開発者のコ​​ードを以下に示します。

|names constraints foundSolution v groups printSolution testC test try|

names := #(Brit Swede Dane Norwegian German
 Red Green White Yellow Blue
 Tea Coffee Milk Beer Water
 PallMall Dunhill Blends Bluemasters Prince
 Dogs Birds Cats Horses Fish).

v := Dictionary new.
names do:[:n | v at:n put:nil].
groups := names splitForSize:5.

constraints := {
        {[:b :r | b==r] . #Brit . #Red   }.          "/ The Brit lives in the red house.
        {[:s :d | s==d] . #Swede . #Dogs }.          "/ The Swede keeps dogs as pets.
        {[:d :t | d==t] . #Dane . #Tea   }.          "/ The Dane drinks tea.
        {[:g :w | g==(w-1)] . #Green . #White }.     "/ The green house is on the immediate left of the white house.
        {[:g :c | g==c] . #Green . #Coffee}.         "/ The green house's owner drinks coffee.
        {[:p :b | p==b] . #PallMall . #Birds}.       "/ The owner who smokes Pall Mall rears birds.
        {[:y :d | y==d] . #Yellow . #Dunhill}.       "/ The owner of the yellow house smokes Dunhill.
        {[:m | m==3] . #Milk}.                       "/ The owner living in the center house drinks milk.
        {[:n | n==1] . #Norwegian }.                 "/ The Norwegian lives in the first house.
        {[:b :c | (b-c)abs==1] . #Blends . #Cats}.   "/ The owner who smokes Blends lives next to the one who keeps cats.
        {[:h :d | (h-d)abs==1] . #Horses . #Dunhill}."/ The owner who keeps the horse lives next to the one who smokes Dunhill.
        {[:m :b | m==b] . #Bluemasters . #Beer}.     "/ The owner who smokes Bluemasters drinks beer.
        {[:g :p | g==p] . #German . #Prince}.        "/ The German smokes Prince.
        {[:n :b | (n-b)abs==1] . #Norwegian . #Blue}."/ The Norwegian lives next to the blue house.
        {[:b :w | (b-w)abs==1] . #Blends . #Water}.  "/ The owner who smokes Blends lives next to the one who drinks water.
}.
testC := [:c | vi:=((c from:2) collect:[:n|v at:n]). (vi includes:nil) or:[c first valueWithArguments:vi]].
test := [constraints conform:testC].

printSolution :=
 [  |f|
    ((('-',* 16),' '),*5) printCR.
    groups do:[:names|
         |values|
         values := names collect:[:nm|v at:nm].
         values sortWith:names.
         names do:[:n| '|'print. (n centerPaddedTo:14)print.'| ' print].
         '' printCR.
    ].
    ((('-',* 16),' '),*5) printCR.
    f := v at:#Fish.
    ('The %1 in the %2 house owns the fish'
        bindWith:((groups at:1) detect:[:n|(v at:n)==f])
        with:((groups at:2) detect:[:n|(v at:n)==f]))printCR
 ].


try := [:gi |
    gi == 0 
     ifTrue: printSolution
     ifFalse:[
        (1 to:5) asArray permutationsDo:[:perm |
            v declareAll:(groups at:gi) from:perm.
            test value ifTrue:[
                try value:(gi-1).
            ].
        ].
        v declareAll:(groups at:gi) from:#(nil nil nil nil nil).
    ].
].
try value:groups size.

制約ソルバーライブラリの使用:

OZ / Mozartのマニュアルに記載されているものと非常によく似た制約ソルバーライブラリを使用します。これはコンテストでは無効であると不満を言うでしょう;-)、それはあなたの娯楽とインスピレーション(あなたの言語の制約パッケージを探してください)のために加えられ、文字を数えません。

|solution|

solution := Solver
    anySolutionFor:[
        |Brit Swede Dane Norwegian German
         Red Green White Yellow Blue
         PallMall Dunhill Prince Blends Bluemasters
         Tea Coffee Water Beer Milk
         Dogs Birds Cats Horses Fish|

        Brit        := (1 %% 5) name:#Brit.
        Swede       := (1 %% 5) name:#Swede.
        Dane        := (1 %% 5) name:#Dane.
        Norwegian   := (1 %% 5) name:#Norwegian.
        German      := (1 %% 5) name:#German.

        Red     := (1 %% 5) name:#Red.
        Green   := (1 %% 5) name:#Green.
        White   := (1 %% 5) name:#White.
        Yellow  := (1 %% 5) name:#Yellow.
        Blue    := (1 %% 5) name:#Blue.

        PallMall     := (1 %% 5) name:#PallMall.
        Dunhill      := (1 %% 5) name:#Dunhill.
        Prince       := (1 %% 5) name:#Prince.
        Blends       := (1 %% 5) name:#Blends.
        Bluemasters  := (1 %% 5) name:#Bluemasters.

        Tea    := (1 %% 5) name:#Tea.
        Coffee := (1 %% 5) name:#Coffee.
        Milk   := (1 %% 5) name:#Milk.
        Water  := (1 %% 5) name:#Water.
        Beer   := (1 %% 5) name:#Beer.

        Dogs         := (1 %% 5) name:#Dogs.
        Birds        := (1 %% 5) name:#Birds.
        Cats         := (1 %% 5) name:#Cats.
        Horses       := (1 %% 5) name:#Horses.
        Fish         := (1 %% 5) name:#Fish.

        Solver allDistinct:{ Brit . Swede . Dane . Norwegian . German. }.
        Solver allDistinct:{ Red. Green. White. Yellow. Blue. }.
        Solver allDistinct:{ PallMall. Dunhill. Prince. Blends. Bluemasters. }.
        Solver allDistinct:{ Tea. Coffee. Milk. Water. Beer }.
        Solver allDistinct:{ Dogs. Birds. Cats. Horses. Fish. }.

        Brit       =: Red.           "/ The Brit lives in the red house.
        Swede      =: Dogs.          "/ The Swede keeps dogs as pets.
        Dane       =: Tea.           "/ The Dane drinks tea.
        Green =: (White - 1).        "/ The green house is on the immediate left of the white house.
        Green =: Coffee.             "/ The green house's owner drinks coffee.
        PallMall   =: Birds.         "/ The owner who smokes Pall Mall rears birds.
        Yellow =: Dunhill.           "/ The owner of the yellow house smokes Dunhill.
        Milk =: 3.                   "/ The owner living in the center house drinks milk.
        Norwegian =: 1.              "/ The Norwegian lives in the first house.
        (Blends - Cats) abs =: 1.    "/ The owner who smokes Blends lives next to the one who keeps cats.
        (Horses - Dunhill) abs =: 1. "/ The owner who keeps the horse lives next to the one who smokes Dunhill.
        Bluemasters =: Beer.         "/ The owner who smokes Bluemasters drinks beer.
        German =: Prince.            "/ The German smokes Prince.
        (Norwegian - Blue) abs =: 1. "/ The Norwegian lives next to the blue house.
        (Blends - Water) abs =: 1.   "/ The owner who smokes Blends lives next to the one who drinks water.
    ].

solution printCR.

「=:」演算子に注意してください。これは「と統一」を意味します。ソルバーは、問題ブロックで定義された制約のセットでバックトラッキングアルゴリズムを使用します。残りのコードは、ソリューションをボックスに印刷します。

    |pLine pSorted f |

    pLine := [ 
        (1 to:5) do:[:i | ('-' ,* 15) print] separatedBy:[' ' print].
        '' printCR.
    ].
    pSorted := [:keys |
        |items t|

        items := keys collect:[:k| solution at:k].
        t := keys copy. items values sortWith:t. 
        pLine value:(t collect:[:x | '| ',(x centerPaddedTo:11),' |']).
    ].

    pLine value.
    pSorted value:#( Brit Swede Dane Norwegian German ).
    pSorted value:#( Red Green White Yellow Blue ).
    pSorted value:#( Tea Coffee Milk Water Beer ).
    pSorted value:#( PallMall Dunhill Prince Blends Bluemasters ).
    pSorted value:#( Dogs Birds Cats Horses Fish ).
    pLine value.

    f := solution at:'Fish'.
    ('The %1 in the %2 house owns the fish!'
        bindWith:(#( Brit Swede Dane Norwegian German ) detect:[:n| (solution at:n) == f])
        with:(#( Red Green White Yellow Blue ) detect:[:n| (solution at:n) == f])
            ) printCR.

出力:

Solution(Brit->3 Swede->5 Dane->2 Norwegian->1 German->4 Red->3 Green->4
 White->5 Yellow->1 Blue->2 PallMall->3 Dunhill->1 Prince->4 Blends->2
 Bluemasters->5 Tea->2 Coffee->4 Milk->3 Water->1 Beer->5 Dogs->5 Birds->3
 Cats->1 Horses->2 Fish->4)
--------------- --------------- --------------- --------------- ---------------
|  Norwegian  | |    Dane     | |    Brit     | |   German    | |    Swede    |
|   Yellow    | |    Blue     | |     Red     | |    Green    | |    White    |
|    Water    | |     Tea     | |    Milk     | |   Coffee    | |    Beer     |
|   Dunhill   | |   Blends    | |  PallMall   | |   Prince    | | Bluemasters |
|    Cats     | |   Horses    | |    Birds    | |    Fish     | |    Dogs     |
--------------- --------------- --------------- --------------- ---------------
The German in the Green house owns the fish!

編集:おっと-私は「魚を所有している人」の行をプレーンバージョンで印刷するのを忘れていました。


3

Ruby 1166文字

編集:正しい出力形式に更新

MBP i5では、0.2秒未満で一貫して実行されます。

ソース:Githubで表示

ワンライナー:

def q(a);a.permutation;end;def z(a,b,c,d);l(a,b,c,d)||l(c,d,a,b);end;def l(a,b,c,d);(0..4).any?{|i|a[i]==b&&c[i+1]==d};end;def i(a,b,c,d);(0..4).any?{|i|a[i]==b&&c[i]==d};end;def t(i);['White','Yellow','Blue','Red','Green','German','Swede','Brit','Norwegian','Dane','Birds','Cats','Horses','Fish','Dogs','Beer','Water','Tea','Milk','Coffee','Blends','PallMall','Prince','Bluemasters','Dunhill'][i];end;def y(s);l=13-s.length;'|'+' '*(l/2.0).floor+s+' '*(l/2.0).ceil+'|';end;def d(s);b=[' '+(0..4).map{'_'*13}.join(' '*4)];u='  ';b<<[1,2,3,4,5].map{|i|y(i.to_s)}.join(u);s.each{|i|b<<i.map{|j|y(t(j))}.join(u)};b<<(0..4).map{'-'*15}.join(u);b<<'';z=s[4].index(13);b<<"The #{t s[0][z]} in the #{t s[1][z]} house owns the fish!";b.join "\n";end;q([0,1,2,3,4]).each{|c|l(c,4,c,0)||next;q([5,6,7,8,9]).each{|n|i(n,7,c,3)||next;n[0]==8||next;z(n,8,c,2)||next;q([10,11,12,13,14]).each{|a|i(n,6,a,14)||next;q([15,16,17,18,19]).each{|d|d[2]==18||next;i(c,4,d,19)||next;i(n,9,d,17)||next;q([20,21,22,23,24]).each{|s|z(a,12,s,24)||next;i(s,21,a,10)||next;z(s,20,d,16)||next;z(s,20,a,11)||next;i(n,5,s,22)||next;i(c,1,s,24)||next;i(s,23,d,15)||next;puts d([n,c,d,s,a]);exit}}}}}

ページに収まるように改行で埋めます:

def q(a);a.permutation;end;def z(a,b,c,d);l(a,b,c,d)||l(c,d,a,b);end
def l(a,b,c,d);(0..4).any?{|i|a[i]==b&&c[i+1]==d};end;def i(a,b,c,d);
(0..4).any?{|i|a[i]==b&&c[i]==d};end;def t(i);['White','Yellow','Blue',
'Red','Green','German','Swede','Brit','Norwegian','Dane','Birds',
'Cats','Horses','Fish','Dogs','Beer','Water','Tea','Milk','Coffee',
'Blends','PallMall','Prince','Bluemasters','Dunhill'][i];end;def y(s);
l=13-s.length;'|'+' '*(l/2.0).floor+s+' '*(l/2.0).ceil+'|';end;
def d(s);b=[' '+(0..4).map{'_'*13}.join(' '*4)];u='  ';
b<<[1,2,3,4,5].map{|i|y(i.to_s)}.join(u);s.each{|i|b<<i.map{|j|
y(t(j))}.join(u)};b<<(0..4).map{'-'*15}.join(u);b<<'';
z=s[4].index(13);
b<<"The #{t s[0][z]} in the #{t s[1][z]} house owns the fish!";
b.join "\n";end;q([0,1,2,3,4]).each{|c|l(c,4,c,0)||next;
q([5,6,7,8,9]).each{|n|i(n,7,c,3)||next;n[0]==8||next;z(n,8,c,2)||next;
q([10,11,12,13,14]).each{|a|i(n,6,a,14)||next;
q([15,16,17,18,19]).each{|d|d[2]==18||next;i(c,4,d,19)||next;
i(n,9,d,17)||next;q([20,21,22,23,24]).each{|s|z(a,12,s,24)||next;
i(s,21,a,10)||next;z(s,20,d,16)||next;z(s,20,a,11)||next;i(n,5,s,22)||next;
i(c,1,s,24)||next;i(s,23,d,15)||next;puts d([n,c,d,s,a]);exit}}}}}

出力:

 _____________    _____________    _____________    _____________    _____________
|      1      |  |      2      |  |      3      |  |      4      |  |      5      |
|  Norwegian  |  |    Dane     |  |    Brit     |  |   German    |  |    Swede    |
|   Yellow    |  |    Blue     |  |     Red     |  |    Green    |  |    White    |
|    Water    |  |     Tea     |  |    Milk     |  |   Coffee    |  |    Beer     |
|   Dunhill   |  |   Blends    |  |  PallMall   |  |   Prince    |  | Bluemasters |
|    Cats     |  |   Horses    |  |    Birds    |  |    Fish     |  |    Dogs     |
---------------  ---------------  ---------------  ---------------  ---------------

The German in the Green house owns the fish!

未ゴルフコード

@colors        = [:white, :yellow, :blue, :red, :green].shuffle.permutation
@cigars        = [:blends, :pall_mall, :prince, :bluemasters, :dunhill].shuffle.permutation
@nationalities = [:german, :swedish, :british, :norwegian, :danish,].shuffle.permutation
@drinks        = [:beer, :water, :tea, :milk, :coffee].shuffle.permutation
@pets          = [:birds, :cats, :horses, :fish, :dogs].shuffle.permutation

def next_to?(set_a, val_a, set_b, val_b)
  left_of?(set_a, val_a, set_b, val_b) ||
  left_of?(set_b, val_b, set_a, val_a)
end

def left_of?(set_a, val_a, set_b, val_b)
  (0..4).any? do |i|
    set_a[i]   == val_a &&
    set_b[i+1] == val_b
  end
end

def implies?(set_a, val_a, set_b, val_b)
  (0..4).any? do |i|
    set_a[i] == val_a &&
    set_b[i] == val_b
  end
end

def solve
  i = 0
  @colors.each do |colors|
    i += 1
    next unless left_of?(colors, :green, colors, :white)
    @nationalities.each do |nationalities|
      i += 1
      next unless implies?(nationalities, :british, colors, :red)
      next unless nationalities[0] == :norwegian
      next unless next_to?(nationalities, :norwegian, colors, :blue)
      @pets.each do |pets|
        i += 1
        next unless implies?(nationalities, :swedish, pets, :dogs) 
        @drinks.each do |drinks|
          i += 1
          next unless drinks[2] == :milk
          next unless implies?(colors, :green, drinks, :coffee)
          next unless implies?(nationalities, :danish, drinks, :tea)
          @cigars.each do |cigars|
            i += 1
            next unless next_to?(pets, :horses, cigars, :dunhill)
            next unless implies?(cigars, :pall_mall, pets, :birds)
            next unless next_to?(cigars, :blends, drinks, :water)
            next unless next_to?(cigars, :blends, pets, :cats)
            next unless implies?(nationalities , :german, cigars, :prince)
            next unless implies?(colors, :yellow, cigars, :dunhill)
            next unless implies?(cigars, :bluemasters,  drinks, :beer)
            return [colors, nationalities, pets, drinks, cigars], i
          end
        end
      end
    end
  end
end

class Symbol
  def humanize
    result = self.to_s
    result.gsub!('_', ' ')
    result.split(' ').collect{|part| part.capitalize }.join(' ')
  end
end

solution, attempts = solve

puts "\nSolved in #{attempts} attempts.\n\n"

for i in (0..4)
  number, color, nationality, cigar, drink, pet = i+1, solution[0][i], solution[1][i].humanize, solution[4][i].humanize, solution[3][i], solution[2][i]
  puts "House #{number} is #{color}. The owner is #{nationality}, smokes #{cigar}, drinks #{drink}, and keeps #{pet}."
end

puts "\n"

出力:

Solved in 37663 attempts.

House 1 is yellow. The owner is Norwegian, smokes Dunhill, drinks water, and keeps cats.
House 2 is blue. The owner is Danish, smokes Blends, drinks tea, and keeps horses.
House 3 is red. The owner is British, smokes Pall Mall, drinks milk, and keeps birds.
House 4 is green. The owner is German, smokes Prince, drinks coffee, and keeps fish.
House 5 is white. The owner is Swedish, smokes Bluemasters, drinks beer, and keeps dogs.

shuffle初期セットアップでの使用により、毎回一意のソリューションパスが確保されます。これは、実行間で変更する試行回数によって確認できます。これにより、入力を個別に入力する必要が軽減されますが、そうするようにコードを変更するのは簡単です。


2
出力が必要な形式と一致しません。
メゴ

ここPPCGでは、適切なソリューションを用意するだけでは不十分です。回答は仕様と一致する必要があります。これには、正しい方法での書式設定が含まれます。
エレンディアスターマン

2
OK。チャレンジ仕様を満たすために、元の投稿がフォーマットコードで更新されました。
ショーン
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.