advent-of-code/hacker-rank/diagonal-difference/main.go
xuu 04bbac8559
Some checks failed
Go Bump / bump (push) Failing after 6s
Go Test / build (push) Successful in 47s
chore: add hackerrank solutions
2024-10-26 12:03:06 -06:00

85 lines
1.7 KiB
Go

package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
/*
* Complete the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*/
func diagonalDifference(arr [][]int32) int32 {
var sum int32
for i, row := range arr {
sum += row[i] - row[len(row)-i-1]
}
if sum < 0 {
sum *= -1
}
return sum
}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 16 * 1024 * 1024)
stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
checkError(err)
defer stdout.Close()
writer := bufio.NewWriterSize(stdout, 16 * 1024 * 1024)
nTemp, err := strconv.ParseInt(strings.TrimSpace(readLine(reader)), 10, 64)
checkError(err)
n := int32(nTemp)
var arr [][]int32
for i := 0; i < int(n); i++ {
arrRowTemp := strings.Split(strings.TrimRight(readLine(reader)," \t\r\n"), " ")
var arrRow []int32
for _, arrRowItem := range arrRowTemp {
arrItemTemp, err := strconv.ParseInt(arrRowItem, 10, 64)
checkError(err)
arrItem := int32(arrItemTemp)
arrRow = append(arrRow, arrItem)
}
if len(arrRow) != int(n) {
panic("Bad input")
}
arr = append(arr, arrRow)
}
result := diagonalDifference(arr)
fmt.Fprintf(writer, "%d\n", result)
writer.Flush()
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}
func checkError(err error) {
if err != nil {
panic(err)
}
}