Reputation: 39
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
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