Last active
April 20, 2020 07:50
-
-
Save theCoderCat/f08198128a910b0de1fb4967ebef7aa3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// challenge detail: https://thecodercat.com/notes/read/hennge.md | |
package main | |
import ( | |
"bufio" | |
"errors" | |
"fmt" | |
"os" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
var result []int | |
// this is the number of test case | |
reader := bufio.NewReader(os.Stdin) | |
num, err := reader.ReadString('\n') | |
num = strings.Replace(num, "\n", "", -1) | |
check(err) | |
numberOfTest, err := strconv.Atoi(string(num)) | |
check(err) | |
if numberOfTest < 1 || numberOfTest > 100 { | |
check(errors.New("no! give me a number > 0 and <= 100")) | |
} | |
input(&result, numberOfTest, 1) | |
fmt.Println(strings.Trim(strings.Replace(fmt.Sprint(result), " ", "\n", -1), "[]")) | |
} | |
func input(result *[]int, numberOfTest int, currentTest int) { | |
if currentTest <= numberOfTest { | |
// read the number of integer will be input in the next line | |
squareSum := 0 | |
ss := inputTest() | |
calculateSum(&squareSum, 0, ss) | |
currentTest++ | |
*result = append(*result, squareSum) | |
input(result, numberOfTest, currentTest) | |
} | |
} | |
func inputTest() (ss []string) { | |
reader := bufio.NewReader(os.Stdin) | |
num, err := reader.ReadString('\n') | |
check(err) | |
num = strings.Replace(num, "\n", "", -1) | |
count, err := strconv.Atoi(string(num)) | |
if count < 1 || count > 100 { | |
check(errors.New("a number that >= 1 and <= 100 please")) | |
} | |
check(err) | |
intStr, err := reader.ReadString('\n') | |
intStr = strings.Replace(intStr, "\n", "", -1) | |
check(err) | |
ss = strings.Split(intStr, " ") | |
if len(ss) != count { | |
check(errors.New(fmt.Sprintf("no! give me %d numbers", count))) | |
} | |
return | |
} | |
func calculateSum(total *int, fromPos int, str []string) int { | |
if fromPos < len(str) { | |
number, err := strconv.Atoi(str[fromPos]) | |
check(err) | |
if number > 100 || number < -100 { | |
check(errors.New("number out of range")) | |
} | |
if number >= 0 { | |
*total += number * number | |
} | |
fromPos++ | |
calculateSum(total, fromPos, str) | |
} | |
return *total | |
} | |
func check(e error) { | |
if e != nil { | |
panic(e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment