From fa2b8ecd7742747dc5ef74e65185708388b1f189 Mon Sep 17 00:00:00 2001 From: surtur Date: Wed, 14 Sep 2022 00:33:11 +0200 Subject: [PATCH] go: add logic for matrix min-sum-path traversal * also print the path both as a graph and as a vector of coordinates --- matrix.go | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 74 insertions(+), 3 deletions(-) diff --git a/matrix.go b/matrix.go index 199125d..c180b0b 100644 --- a/matrix.go +++ b/matrix.go @@ -7,6 +7,7 @@ import ( "log" "os" "strconv" + "strings" "time" ) @@ -99,11 +100,81 @@ func convertMatrix(strmatrix [][]string) matrix { return m } +// fmtPath efficiently formats positional values for printing. +func fmtPath(x, y, val int) string { + s := "[" + strconv.Itoa(x) + "," + strconv.Itoa(y) + "] (" + + strconv.Itoa(val) + ")" + return s +} + // traverseMatrix traverses the given matrix in such a manner as to accumulate // the smallest possible sum. allowed movements are down and to the right. -func traverseMatrixMinSumPath(m matrix) { //nolint:unparam - // ad unparam: m will be used shortly. +// it also prints a cute ascii path of traversal. +func traverseMatrixMinSumPath(m matrix) { start := time.Now() - log.Printf("traversing the matrix took: %s", time.Since(start)) + cols := len(m.rows[0]) + rows := len(m.rows) + // current column. + col := 0 + // current row index. + i := 0 + sum := m.rows[i][col] + traversing := true + path := "init" + graph := "x" + + log.Printf("matrix cols: %d, rows: %d\n", cols, rows) + + for traversing { + path += ", " + fmtPath(i, col, m.rows[i][col]) + + nextCol := col + 1 + nextRow := i + 1 + + switch { + case nextCol < cols && nextRow < rows: + // can go either way. + right := m.rows[i][col+1] + down := m.rows[i+1][col] + + if right < down { + col++ + + sum += right + graph += "x" + } else { + i++ + + sum += down + graph += "\n" + strings.Repeat(" ", col) + "x" + } + + case nextRow == rows && nextCol < cols: + // can only go right. + col++ + sum += m.rows[i][col] + graph += "x" + + case nextCol == cols && nextRow < rows: + // can only go down. + i++ + sum += m.rows[i][col] + graph += "\n" + strings.Repeat(" ", col) + "x" + + default: + path += ", finish" + + log.Printf( + "traversal concluded with sum: %d\n"+ + "graph:\n%s\n"+ + "traversal path:\n%s\n\n", + sum, graph, path, + ) + + traversing = false + } + } + + log.Printf("traversing the matrix took: %s\n", time.Since(start)) }