Paul Tarau 为 Hitchhiker Prolog 提供了一个测试平台,其中包含几个有趣的纯 Prolog '程序':queens、sudoku、lambdas、peano 算术。在此处查看文件夹progs或将我的实现(来自hhprolog)作为片段运行...
N-Queens,一个我以前从未见过的非常优雅的解决方案:
place_queen(I,[I|_],[I|_],[I|_]).
place_queen(I,[_|Cs],[_|Us],[_|Ds]):-place_queen(I,Cs,Us,Ds).
place_queens([],_,_,_).
place_queens([I|Is],Cs,Us,[_|Ds]):-
place_queens(Is,Cs,[_|Us],Ds),
place_queen(I,Cs,Us,Ds).
gen_places([],[]).
gen_places([_|Qs],[_|Ps]):-gen_places(Qs,Ps).
qs(Qs,Ps):-gen_places(Qs,Ps),place_queens(Qs,Ps,_,_).
goal(Ps):-qs([0,1,2,3,4,5],Ps).
function runnable(out_elem) {
settext(out_elem = out_elem || run_output)
return new Prog({
writeln: function(l) {
textln(out_elem, l)
},
nl_source: `
place_queen I _0 _1 _2 and
_0 holds list I _3 and
_1 holds list I _4 and
_2 holds list I _5 .
place_queen I _0 _1 _2 and
_0 holds list _3 Cs and
_1 holds list _4 Us and
_2 holds list _5 Ds
if
place_queen I Cs Us Ds .
place_queens nil _0 _1 _2 .
place_queens _0 Cs Us _1 and
_0 holds list I Is and
_1 holds list _2 Ds
if
place_queens Is Cs _3 Ds and
_3 holds list _4 Us and
place_queen I Cs Us Ds .
gen_places nil nil .
gen_places _0 _1 and
_0 holds list _2 Qs and
_1 holds list _3 Ps
if
gen_places Qs Ps .
qs Qs Ps
if
gen_places Qs Ps and
place_queens Qs Ps _0 _1 .
goal Ps
if
qs _0 Ps and
_0 lists 0 1 2 3 4 5 .
`
})
}
function settext(e, t) {
e.innerHTML = t || ''
}
function textln(e, l) {
e.innerHTML = e.innerHTML + `\n` + (l || '')
}
const prog = runnable()
const t0 = Date.now()
prog.run(print_sol.checked)
prog.options.writeln('elapsed secs:' + (Date.now() - t0) / 1000)
.boxed {
box-shadow: 8px 8px 5px #444;
background-image: linear-gradient(180deg, #fff, #ddd 40%, #ccc);
}
.spacing {
border: 1px solid #333;
padding: 8px 12px;
}
<script src="https://cdn.jsdelivr.net/gh/CapelliC/hhprolog/hhprolog.js"></script>
<label>print solutions
<input id=print_sol type=checkbox checked=checked>
</label>
<div class="boxed spacing">
<div>Solutions</div>
<pre id=run_output></pre>
</div>