diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2020-11-29 22:25:11 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-11-29 22:25:11 +0000 |
| commit | 997f3befe5ec5e5e0f45b6f22babf8823e835f4f (patch) | |
| tree | 6b8839cf4ce4d94ae1fa259e8c9c6024ae6a6a5c | |
| parent | c86ea552f44882c283830a0c3b257ba77e3a678c (diff) | |
| parent | 0fb1e10f0b233caf4b8b46fd732f9d1d30b79fec (diff) | |
| download | perlweeklychallenge-club-997f3befe5ec5e5e0f45b6f22babf8823e835f4f.tar.gz perlweeklychallenge-club-997f3befe5ec5e5e0f45b6f22babf8823e835f4f.tar.bz2 perlweeklychallenge-club-997f3befe5ec5e5e0f45b6f22babf8823e835f4f.zip | |
Merge pull request #2875 from adamcrussell/challenge-088
Prolog solution to part 2.
| -rw-r--r-- | challenge-088/adam-russell/prolog/ch-2.p | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/challenge-088/adam-russell/prolog/ch-2.p b/challenge-088/adam-russell/prolog/ch-2.p new file mode 100644 index 0000000000..7c780ff4ae --- /dev/null +++ b/challenge-088/adam-russell/prolog/ch-2.p @@ -0,0 +1,65 @@ +/* + You are given m x n matrix of positive integers. + Write a script to print spiral matrix as a list. +*/ +write_remove_top(Matrix, UpdatedMatrix):- + nth0(0, Matrix, Top), + atomic_list_concat(Top, ",", TopString), + write(TopString), + nth0(0, Matrix, _, UpdatedMatrix). + +write_remove_last([], UpdatedMatrix, UpdatedMatrix). +write_remove_last([H|T], RemainderAccum, UpdatedMatrix):- + length(H, L), + Last is L - 1, + nth0(Last, H, Right), + write(Right), + write(","), + nth0(Last, H, _, UpdatedRow), + write_remove_last(T, [UpdatedRow|RemainderAccum], UpdatedMatrix). + +write_remove_right(Matrix, UpdatedMatrix):- + write_remove_last(Matrix, [], UpdatedMatrix). + +write_remove_first([], UpdatedMatrix, UpdatedMatrix). +write_remove_first([H|T], RemainderAccum, UpdatedMatrix):- + nth0(0, H, Left), + write(Left), + write(","), + nth0(0, H, _, UpdatedRow), + write_remove_first(T, [UpdatedRow|RemainderAccum], UpdatedMatrix). + +write_remove_left(Matrix, UpdatedMatrix):- + write_remove_first(Matrix, [], UpdatedMatrix). + +write_remove_bottom(Matrix, UpdatedMatrix):- + length(Matrix, L), + Last is L - 1, + nth0(Last, Matrix, Bottom), + reverse(Bottom, ReverseBottom), + atomic_list_concat(ReverseBottom, ",", BottomString), + write(BottomString), + nth0(Last, Matrix, _, UpdatedMatrix). + + +spiral(Matrix):- + spiral(Matrix, _). +spiral([], _). +spiral(Matrix, UpdatedMatrix):- + write_remove_top(Matrix, UpdatedMatrix), + write(","), + write_remove_right(UpdatedMatrix, RightRemainder), + reverse(RightRemainder, RemainderRight), + write_remove_bottom(RemainderRight, BottomRemainder), + write(","), + write_remove_left(BottomRemainder, LeftRemainder), + spiral(LeftRemainder, []). +spiral(_, []):- + write("\b"). + +main:- + spiral([ + [ 1, 2, 3 ], + [ 4, 5, 6 ], + [ 7, 8, 9 ] + ]), halt. |
