Re: problem:4x4magicSquare in prolog
- From: Jan Wielemaker <jan@xxxxxxxxxxxxxxxxxxx>
- Date: 16 Jan 2006 15:38:02 GMT
On 2006-01-16, lee.jinsong802@xxxxxxxxxxxxxx <lee.jinsong802@xxxxxxxxxxxxxx> wrote:
>
> pls just give me a hand for correcting the follwing program: 4x4
> magic square, output all results. however it must be done in about
> 10mins im computer.
>
> i need too long time(2-3 hours) to run my program . there must be
> something wrong inside.
If you write in German and use unreadable layout you cannot expect that
many replies. Bart gave you the suggestion to fix the layout and avoid
assert/retract. Thats a very good start. I'll do one predicate.
> zerlegen(17,_N).
> zerlegen(N1,N2):-
> N1=16,N2=16->
> return;
> not(N1=17),
> N2=17->
> _N1 is N1+1,zerlegen(_N1,1);
> N1 = N2->
> _N2 is N2+1,zerlegen(N1,_N2);
> 17 is N1+N2->
> zerlegen_besonder(N1,N2);
> zerlegen_ander(N1,N2,1).
Why two clauses, one with a single case and the other with multiple
using if-then-else?? There is something to be said for both, but
mixing is generally very bad style. Also, `return' is not part of
Prolog, so either this case doesn't occur or your program misbehaves
(if your prolog doesn't trap undefined predicates as errors) or your
program generates an error. One style might be:
zerlegen(17, _) :- !.
zerlegen(16, 16) :- !.
zerlegen(N, 17) :- !,
N1 is N + 1,
zerlegen(N1, 17).
zerlegen(N, N) :- !,
N2 is N + 1,
zerlegen(N, N2).
zerlegen(N1, N2) :-
17 =:= N1 + N2, !,
zerlegen_besonder(N1,N2).
zerlegen(N1, N2) :-
zerlegen_ander(N1,N2,1).
I think this is the correct translation of this predicate. This
version doesn't leave a choicepoint for N1=17. It also doesn't
call return. It will only be a bit faster. Avoiding assert/retract
can make a real diference.
--- Jan
.
- References:
- problem:4x4magicSquare in prolog
- From: lee . jinsong802
- Re: problem:4x4magicSquare in prolog
- From: Bart Demoen
- Re: problem:4x4magicSquare in prolog
- From: lee . jinsong802
- problem:4x4magicSquare in prolog
- Prev by Date: Re: problem:4x4magicSquare in prolog
- Next by Date: Re: for loop in prolog
- Previous by thread: Re: problem:4x4magicSquare in prolog
- Next by thread: Re: problem:4x4magicSquare in prolog
- Index(es):