Turn a list into a matrix

后端 未结 3 647
半阙折子戏
半阙折子戏 2021-01-25 18:42

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 a

3条回答
  •  抹茶落季
    2021-01-25 19:15

    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).
    

提交回复
热议问题