m09
m09

Reputation: 7493

Turn a list into a matrix

I worked all afternoon on a simple thing but cannot seem to get it right for some reason : how to turn a list into a matrix of given width.

Example : I got a list such as

[1, 3, 5, 7, 6, 8, 9, 0]

and want to create a matrix such as

[[1, 3],
 [5, 7],
 [6, 8],
 [9, 0]]

through a predicate

list2matrix/3 : list2matrix(List, Size_of_Rows, Matrix).

In this example used like :

list2matrix([1, 3, 5, 7, 6, 8, 9, 0], 2, Matrix).

The predicate should fail if the length of the list is not a multiple of the size of the rows.

I decided not to post my work since I think I got it so wrong that it would not help me to get correction on it ;(

Thanks by advance if you can propose any leads about how to deal with such a problem.

Upvotes: 1

Views: 2486

Answers (3)

m09
m09

Reputation: 7493

BTW, I thought I'd mention the code I finally wrote :

length_(Length, List) :- length(List, Length).

list2matrix(List, RowSize, Matrix) :-
    length(List, L),
    HowManyRows is L div RowSize,
    length(Matrix, HowManyRows),
    maplist(length_(RowSize), Matrix),
    append(Matrix, List).

It's more high order oriented and funnier to read I guess :)

Upvotes: 2

gusbro
gusbro

Reputation: 22585

You can divide the problem in two parts. The first building block would be to build a row of N elements. That is to take the input list and split it in two lists, one will have exactly N elements (the row) and the other is the remaining of the input list.

The second building block would be to build the matrix which is made of rows.

list_to_matrix([], _, []).
list_to_matrix(List, Size, [Row|Matrix]):-
  list_to_matrix_row(List, Size, Row, Tail),
  list_to_matrix(Tail, Size, Matrix).

list_to_matrix_row(Tail, 0, [], Tail).
list_to_matrix_row([Item|List], Size, [Item|Row], Tail):-
  NSize is Size-1,
  list_to_matrix_row(List, NSize, Row, Tail).

Upvotes: 2

Cristobal
Cristobal

Reputation: 61

Look for a pattern in your desired outcome. That means pair numbers will be allocated as the second number in each pair and non pairs will be in first place each time. Create a bi dimensional array and assign non pair positions to sub index "a" and pairs to "b".

As you could see "i" is an index for an array, a multidimensional array. i[a][b]

You need to iterate through both arrays in order to accomplish this.

Hope it helps.

Upvotes: 1

Related Questions