I need to write this code in prolog:
void rec_k(int k,int i,int j) {
if (!(k<9)) return;
if ((i <> j) and (i <> k) and (j <> k)) {
writeln(100 * i + 10 * j + k);
}
rec_k(k+1,i,j);
}
I tried this:
rec_k(K, I, J):-
((K >= 9) -> !;
((I <> J and I <> K and J <> K) -> write(100 * I + 10 * J + K);)
),
rec_k(K+1,I,J).
Doesn't work, of course.
Try this:
The output of
rec_k(0,2,3).
isPlease note: arithmetic terms can be calculated by using
is
. My solution introduces a helper predicate which does the output: once it has checked thatI
,J
andK
are different it will prevent backtracking (with a so called cut!
), calcluates and prints the output. IfI
,J
andK
are not different it will just do nothing. The main predicaterec_k/3
needs to know when to stop (notK < 9
). Otherwise it will call the write-predicate and call itself with an incrementedK
(KK
).It can be written without the helper predicate (return the same output):