我正在尝试以下列格式打印出一个矩阵,但我不知道该怎么做。所以这是我想要打印它的格式。
************
***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**
这就是我创建矩阵的方法,我需要更改哪些内容才能像上面一样打印出来?
:- use_module(library(clpfd)).
%Create Matrix
setMatrix(N, Matrix) :-
length(Matrix, N),
maplist(length_list(N), Matrix).
length_list(L, Ls) :- length(Ls, L).
答案 0 :(得分:3)
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.