A logical puzzle

Hello all, this is my first Prolog programme and I want to know how it might be canonically written. I.e. how someone good at Prolog would write it. The programme is a little logic game on a 4x4 grid, where each grid cell is in the range 0 to 23. Some of the cells have fixed values, and the rest of the cells are derived by adding or subtracting the values of other cells modulo 23. I’ve limited the derived cells to use 2 or 3 other cells. Aim of the game is to work out which cells have fixed values.

Usage: generate([12,4,8],X) will use the fixed values 12,4,8 and derive another 13 members to complete the puzzle data. The result (a 16 member list) can then be shuffled and presented as a 4x4 grid.

Code:

use_module(library(random)).

rand_mem(L,X) :- random_member(X,L).

mult(X, Y, Z) :- Z is X * Y.

formula(L,F) :-
    random_member(X, [2,3]),
    length(L1, X),
    length(L2, X),
    maplist(rand_mem(L), L1),
    maplist(rand_mem([-1,1]), L2),
    maplist(mult, L1, L2, P),
    sumlist(P,S),
    F is S mod 23.
    
generate(L,X) :- length(L,16), X = L.

generate(L,X) :-
    formula(L,F),
    append(L,[F],Y),
    generate(Y,X).

I’d be grateful if you could let me know if there is a more elegant way to express this.

Your spec never mentions a random element. Why is there randomness in the code? :wink:

The randomness just varies the formula for each derived cell so that it is not calculated in a deterministic way . Otherwise the puzzles would be easy.