Skip to content

Instantly share code, notes, and snippets.

@steelx
Created November 8, 2019 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steelx/dcbf5b2f49a0dc4118821933e7fdf51c to your computer and use it in GitHub Desktop.
Save steelx/dcbf5b2f49a0dc4118821933e7fdf51c to your computer and use it in GitHub Desktop.
Sum of Squares
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
Scanner := bufio.NewScanner(os.Stdin)
var (
sum []int
rowInput int
numOfTestCases int
)
nyanCatInit(rowInput, numOfTestCases, sum, Scanner)
}
func nyanCatInit(iterationRow int, numOfTestCases int, sum []int, Scanner *bufio.Scanner) {
Scanner.Scan()
input := Scanner.Text()
updateTestCasesCount(&numOfTestCases, iterationRow, input)
//get remaining input [1:] from row
rest := strings.Split(input, " ")
//ignore first 2 rows input
if iterationRow > 0 && iterationRow%2 == 0 {
sumSquareOfRow := sumOfSquares(rest)
sum = append(sum, sumSquareOfRow)
}
if numOfTestCases == iterationRow/2 {
printRow(sum) //finally print all & exit
return
}
// else we keep running nyan-cat
iterationRow += 1
nyanCatInit(iterationRow, numOfTestCases, sum, Scanner)
}
func printRow(sum []int) {
fmt.Println(sum[0])
rest := sum[1:]
if len(rest) == 0 {
return
}
printRow(rest)
}
func sumOfSquares(numArr []string) int {
i, err := strconv.Atoi(numArr[0])
checkError(err)
rest := numArr[1:]
square := i * i
// negative & last number
if i < 0 && len(rest) == 0 {
return square
}
// negative & not last number
if i < 0 && len(rest) > 0 {
return sumOfSquares(rest)
}
// last man standing
if i >= 0 && len(rest) == 0 {
return square
}
return square + sumOfSquares(rest)
}
func updateTestCasesCount(testCases *int, iterationRow int, input string) {
if iterationRow == 0 {
firstInput, err := strconv.Atoi(input)
checkError(err)
if firstInput == 0 {
os.Exit(0) //we break if zero
}
*testCases = firstInput
}
}
//Error checking
func checkError(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment