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:
parent
47e8d225fb
commit
fa2b8ecd77
77
matrix.go
77
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))
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user