I wrote a prolog program which generates all possible positions of elements in a two-dimensional table. The number of elements and the table size are given.
My code:
geni(Min, Min, Max) :- Min =< Max.
geni(Min, X, Max) :- Max >= Min, MinInc is Min+1, geni(MinInc, X, Max).
generate(_, 0, []) :- !.
generate(TSize, N, [X|Tail]) :- X=k(X1,Y1), geni(1,X1,TSize),
geni(1,Y1,TSize), NDec is N-1,
generate(TSize,NDec, Tail), not(member(X, Tail)).
(where TSize is the size of the table, N is the number of elements, and the last one is the result)
Predicate 'geni' generates number X in interval [A;B].
Example (2 elements in 2x2 table):
?- generate(2, 2, R).
R = [k(1, 1), k(1, 2)] ;
R = [k(1, 1), k(2, 1)] ;
R = [k(1, 1), k(2, 2)] ;
R = [k(1, 2), k(1, 1)] ;
R = [k(1, 2), k(2, 1)] ;
R = [k(1, 2), k(2, 2)] ;
R = [k(2, 1), k(1, 1)] ;
R = [k(2, 1), k(1, 2)] ;
R = [k(2, 1), k(2, 2)] ;
R = [k(2, 2), k(1, 1)] ;
R = [k(2, 2), k(1, 2)] ;
R = [k(2, 2), k(2, 1)] ;
false.
It works correctly but is too slow when I use higher numbers. I think the predicate 'geni' is good but something is wrong with 'generate'. How could I optimize it?