user2947488
user2947488

Reputation: 39

Prolog: list of n of n x n matrix

How to create n x n matrix in Prolog and inside the matrix is list of n to 1. I can create the coding for generate list but do not know how to create a matrix n x n:

make_num_list(N, List) :-
   make_list(N, List).

make_list(N, []) :-
   N =< 0,
   !.
make_list(N, [N|Rest]) :-
   N > 0,
   N2 is N - 1,
   make_list(N2, Rest).

Upvotes: 0

Views: 2925

Answers (2)

chamini2
chamini2

Reputation: 2918

Reuse your code, and your ideas.

make_num_matrix(N, Matrix) :-
    make_matrix(N, N, Matrix).

make_matrix(_, N, []) :-
    N =< 0,
    !.
make_matrix(M, N, [R|Rs]) :-
    make_list(M, R),
    N2 is N - 1,
    make_matrix(M, N2, Rs).

make_list(N, []) :-
    N =< 0,
    !.
make_list(N, [N|Rest]) :-
    N > 0,
    N2 is N - 1,
    make_list(N2, Rest).

?- make_num_matrix(4, M).
M = [[4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1]].

Upvotes: 1

CapelliC
CapelliC

Reputation: 60014

most Prolog out there have between/3, and surely will have findall/3

make_matrix(N, M) :- findall(Ns, (between(1,N,_), make_list(N,Ns)), M).

Upvotes: 1

Related Questions