Zebra puzzle: Difference between revisions

Content deleted Content added
WillNess (talk | contribs)
added J
Line 210:
}
 
sub pair {NB. h =.~.&> compose&.>~/y,<h
 
my ($c1, $c2, $diff) = @_;
$diff //= [0];
Line 662 ⟶ 663:
</pre>
Run-time about 0.76 seconds.
 
=={{header|J}}==
 
Propositions 1 .. 16 without 9,10 and15
<lang j>ehs=: 5$a:
 
cr=: (('English';'red') 0 3} ehs);<('Dane';'tea') 0 2}ehs
cr=: cr, (('German';'Prince') 0 4}ehs);<('Swede';'dog') 0 1 }ehs
 
cs=: <('PallMall';'birds') 4 1}ehs
cs=: cs, (('yellow';'Dunhill') 3 4}ehs);<('BlueMaster';'beer') 4 2}ehs
 
lof=: (('coffee';'green')2 3}ehs);<(<'white')3}ehs
 
next=: <((<'Blend') 4 }ehs);<(<'water')2}ehs
next=: next,<((<'Blend') 4 }ehs);<(<'cats')1}ehs
next=: next,<((<'Dunhill') 4}ehs);<(<'horse')1}ehs</lang>
'''Example'''
<lang j> lof
┌─────────────────┬───────────┐
│┌┬┬──────┬─────┬┐│┌┬┬┬─────┬┐│
││││coffee│green│││││││white│││
│└┴┴──────┴─────┴┘│└┴┴┴─────┴┘│
└─────────────────┴───────────┘</lang>
 
Collections of all variants of the propositions:
<lang j>hcr=: (<ehs),. (A.~i.@!@#)cr
hcs=:~. (A.~i.@!@#)cs,2$<ehs
hlof=:(-i.4) |."0 1 lof,3$<ehs
hnext=: ,/((i.4) |."0 1 (3$<ehs)&,)"1 ;(,,:|.)&.> next</lang>
 
A street with fixed properties 9, 10 and 15.
<lang j>houses=: ((<'Norwegian') 0}ehs);((<'blue') 3 }ehs);((<'milk') 2}ehs);ehs;<ehs</lang>
{{out}}
<lang j> houses
┌───────────────┬──────────┬──────────┬──────┬──────┐
│┌─────────┬┬┬┬┐│┌┬┬┬────┬┐│┌┬┬────┬┬┐│┌┬┬┬┬┐│┌┬┬┬┬┐│
││Norwegian││││││││││blue││││││milk││││││││││││││││││
│└─────────┴┴┴┴┘│└┴┴┴────┴┘│└┴┴────┴┴┘│└┴┴┴┴┘│└┴┴┴┴┘│
└───────────────┴──────────┴──────────┴──────┴──────┘</lang>
Set of proposition varaints:
<lang j>constraints=: hcr;hcs;hlof;<hnext</lang>
The worker and its helper verbs
<lang j>select=: ~.@(,: #~ ,&(0~:#))
filter=: #~*./@:(2>#S:0)"1
compose=: [: filter f. [: ,/ select f. L:0"1"1 _
 
solve=: 4 :0
h=. ,:x
whilst. 0=# z do.
for_e. y do. h=. h compose > e end.
z=.(#~1=[:+/"1 (0=#)S:0"1) h=.~. h
end.
)</lang>
{{out}}
<lang j> >"0 houses solve constraints
┌─────────┬─────┬──────┬──────┬──────────┐
│Norwegian│cats │water │yellow│Dunhill │
├─────────┼─────┼──────┼──────┼──────────┤
│Dane │horse│tea │blue │Blend │
├─────────┼─────┼──────┼──────┼──────────┤
│English │birds│milk │red │PallMall │
├─────────┼─────┼──────┼──────┼──────────┤
│German │ │coffee│green │Prince │
├─────────┼─────┼──────┼──────┼──────────┤
│Swede │dog │beer │white │BlueMaster│
└─────────┴─────┴──────┴──────┴──────────┘</lang>
So, the German owns the zebra.
 
A longer running solver by adding the zebra variants.
 
<lang j>zebra=: (-i.5)|."0 1 (<(<'zebra') 1}ehs),4$<ehs</lang>
 
 
=={{header|Perl}}==