diwt/matrix.go

110 lines
2.5 KiB
Go
Raw Normal View History

// Copyright 2022 wanderer <wanderer at dotya.ml>
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"log"
"os"
"strconv"
"time"
)
type matrix struct {
rows [][]int
}
// stoi attempts to convert a supposed int in string form to an actual int,
// fails loudly if it doesn't work.
func stoi(s string) int {
val, err := strconv.Atoi(s)
if err != nil {
log.Fatalln("could not convert from string to int:", s, err)
}
return val
}
// rowtoi converts a row (a []string) to an []int and returns it.
func rowtoi(row []string) []int {
cols := len(row)
// prealloc, when the size is known, gosimple is wrong here.
intRow := make([]int, cols, cols) //nolint:gosimple
for i, v := range row {
intRow[i] = stoi(v)
}
return intRow
}
// isNonEmptyMatrix checks the [][]string input and determines whether it is a
// non-empty matrix, since that is the kind we care about.
func isNonEmptyMatrix(strmatrix [][]string) bool {
initCols := len(strmatrix[0])
if initCols == 0 || len(strmatrix) == 0 {
log.Printf("emptymatrix: we don't want those")
return false
}
for i, v := range strmatrix {
cols := len(v)
if cols != initCols {
2022-09-13 23:42:01 +02:00
log.Printf(
"notamatrix: all rows until now were of '%d' columns\n"+
"offending row: #%d, size: %d",
initCols, i, cols,
)
return false
}
}
return true
}
func initMatrix(strmatrix [][]string) matrix {
m := &matrix{}
// we can now safely do this because at this point we have already checked
// that strmatrix is a "valid" matrix.
cols := len(strmatrix[0])
rows := len(strmatrix)
// prealloc, when the size is known, gosimple is wrong here.
m.rows = make([][]int, rows, rows) //nolint:gosimple
for i := range strmatrix {
// prealloc, when the size is known, gosimple is wrong here.
m.rows[i] = make([]int, cols, cols) //nolint:gosimple
}
return *m
}
// convertMatrix attempts to convert the whole string matrix to an int matrix.
func convertMatrix(strmatrix [][]string) matrix {
if !isNonEmptyMatrix(strmatrix) {
log.Fatalln("bailing...")
os.Exit(2)
}
m := initMatrix(strmatrix)
for i, v := range strmatrix {
m.rows[i] = rowtoi(v)
}
return m
}
// 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.
start := time.Now()
log.Printf("traversing the matrix took: %s", time.Since(start))
}