Good morning. I need your help. I want to make a list of list (matrix with size SQRT(N)*SQRT(N)) from a list with Size N
I am tried but It does not work for me :(
gen(L,T,Matrix)
which T is the size of Matrix You are free to add more param if you want
for example
gen([1,2,3,4,5,6,7,8,9],3,Matrix)
Matrix = [[1,2,3],[4,5,6],[7,8,9]]
This is actually a fairly straightforward problem. The trick is to remember that
append/3
has many instantiation patterns, and can be used not just to glue lists together but also to break them apart:You can use
length/2
to control the size of the list you make as well:This is almost everything you need right here. The rest is just wrapping this in a recursive call. You need a base case:
This essentially says, my dimension doesn't matter if I'm out of flat-representation or matrix representation.
Now the recursive case:
This is a very basic recursive predicate. The
append/3
followed bylength/2
steps are the same as above; they establish a lengthT
prefix of List as the next chunk of the result. Then we recursively apply ourselves to the remaining List to generate the Rest of the result.As a cool side benefit, this predicate works both ways:
How nice is that!