Reputation: 13
I am trying to print out a matrix in the following format but I am not sure how to. So this is the format I want to print it in.
************
***35****35*
***2938**28*
**28*2358*32
*3512**23*93
*28*3258*328
**92*329*21*
*318*5913*13
*53*28**2345
*84*8125*21*
**13**5329**
**12****58**
This is how I am creating my matrix, what would I need to change in order to print out it like the above?
:- use_module(library(clpfd)).
%Create Matrix
setMatrix(N, Matrix) :-
length(Matrix, N),
maplist(length_list(N), Matrix).
length_list(L, Ls) :- length(Ls, L).
Upvotes: 1
Views: 407
Reputation: 40768
Before I answer the actual question, a few additional points:
Think in terms of relations between entities, and describe what holds. Wording like "create", "set" etc. make no sense in this view: The described entities come into existence by describing them in any number of ways, for example, by writing them down directly.
Taking into account the earlier point, you can for example use:
n_matrix(N, Matrix) :-
length(Matrix, N),
maplist(same_length(Matrix), Matrix).
Notice that n_matrix/2
can be used in all directions, including: using a partially filled matrix, determining N
from a given or partially instantiated matrix, testing whether a matrix is an N×N matrix etc. Therefore, we have chosen a name that encompasses all such use cases simultaneously by stating what each argument stands for, using declarative wording.
And now in response to the actual question:
Try to answer the simpler question:
How would you print a single row of this matrix in the way you want?
One way to do it is:
print_row(Ls) :- maplist(write, Ls), nl.
And now you can easily apply this to print the entire matrix:
?- n_matrix(N, Ms), maplist(print_row, Ms).
When describing relations over lists, it is often a good strategy to first define the relation for single element, and then to use the meta-predicates maplist/2
or maplist/N
to describe the relation for the whole list.
Upvotes: 3