go: add logic for matrix min-sum-path traversal

* also print the path both as a graph and as a vector of coordinates
This commit is contained in:
surtur 2022-09-14 00:33:11 +02:00
parent 47e8d225fb
commit fa2b8ecd77
Signed by: wanderer
SSH Key Fingerprint: SHA256:MdCZyJ2sHLltrLBp0xQO0O1qTW9BT/xl5nXkDvhlMCI

@ -7,6 +7,7 @@ import (
"log" "log"
"os" "os"
"strconv" "strconv"
"strings"
"time" "time"
) )
@ -99,11 +100,81 @@ func convertMatrix(strmatrix [][]string) matrix {
return m 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 // traverseMatrix traverses the given matrix in such a manner as to accumulate
// the smallest possible sum. allowed movements are down and to the right. // the smallest possible sum. allowed movements are down and to the right.
func traverseMatrixMinSumPath(m matrix) { //nolint:unparam // it also prints a cute ascii path of traversal.
// ad unparam: m will be used shortly. func traverseMatrixMinSumPath(m matrix) {
start := time.Now() 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))
} }