Mercurial > repos > other > SevenLanguagesInSevenWeeks
changeset 41:f4ea1f637f22
Add answers for 6 and 7 (transpose and write/read matrix)
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Thu, 14 Sep 2017 21:00:05 +0100 |
parents | 82627dd71c75 |
children | 54608c26bda2 |
files | .hgignore 2-Io/day2-self-study.io |
diffstat | 2 files changed, 67 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.hgignore Thu Sep 14 21:00:05 2017 +0100 @@ -0,0 +1,1 @@ +2-Io/matrix.txt \ No newline at end of file
--- a/2-Io/day2-self-study.io Thu Sep 14 20:24:25 2017 +0100 +++ b/2-Io/day2-self-study.io Thu Sep 14 21:00:05 2017 +0100 @@ -127,6 +127,72 @@ my_arr get(5, 5) println +#6) Bonus "transpose" method (ugly and inefficient method) +TwoDList transpose := method( + new_list := TwoDList clone + x := self arr size + y := self arr at(0) size + new_list dim(y, x) + for (i, 0, x - 1, + for (j, 0, y - 1, + new_list set(j, i, self get(i, j)) + ) + ) + return new_list +) + +transposed := my_arr transpose +transposed get(1, 2) println +transposed get(0, 1) println +transposed get(2, 1) println +transposed get(1, 0) println + +#7) Write a matrix to a file and read it back +# Might as well use the TwoDList as a matrix +# Note: This isn't white-space safe, but nvm +TwoDList as_string := method( + x := self arr size + y := self arr at(0) size + #str := "#{self arr size}×#{self arr at(0) size}\n" interpolate + str := "" + for (i, 0, x - 1, + for (j, 0, y - 1, + str = "#{str}#{self get(i, j)} " interpolate + ) + str = "#{str asMutable strip}\n" interpolate + ) +) + +TwoDList load := method(matrix_string, + # strip to make sure that we don't get trailing new lines + rows := matrix_string strip split("\n") + row_count := rows size + # Ugly way to get column count + col_count := rows at(0) split(" ") size + self dim(row_count, col_count) + for (i, 0, row_count - 1, + row := rows at(i) split(" ") + for (j, 0, col_count - 1, + self set(i, j, row at(j)) + ) + ) +) +matrix_file := "matrix.txt" +f := File with(matrix_file) +f remove +f openForUpdating +f write(my_arr as_string) +f flush +f close + +f2 := File with(matrix_file) +f2 openForReading +new_list := TwoDList clone +new_list load(f2 contents) +f2 close +new_list get(1, 2) println +new_list get(0, 1) println + # 4) final piece list(1, 2, 3, "foo") myAverage \ No newline at end of file