Skip to content

Instantly share code, notes, and snippets.

@kimonoki
Last active April 16, 2018 01:51
Show Gist options
  • Save kimonoki/c881adba8a1896972020fc492769b031 to your computer and use it in GitHub Desktop.
Save kimonoki/c881adba8a1896972020fc492769b031 to your computer and use it in GitHub Desktop.
Loops without for keyword
package main
import (
"bufio"
"fmt" // A package in the Go standard library.
"os"
"strconv"
"strings"
)
//global vars
var casenum int
var testnum int
var i = 0 //iterator for each case
var j = 0 //iterator for case's number
var sum int = 0 //sum of a case
var result []int //result array
func main() {
readcasenum()
gotocase(casenum)
printresult()
}
func readcasenum() {
fmt.Scan(&casenum)
if casenum > 100 || casenum < 1 {
fmt.Print("the first line of the input will be an integer N (1 <= N <= 100)")
os.Exit(0)
}
}
//go into each test case
func gotocase(casenumber int) {
if j < casenumber {
j++
i = 0
sum = 0
runtest()
gotocase(casenum)
} else {
j = 0
return
}
}
//run test for each case
func runtest() {
testnum = 0
fmt.Scan(&testnum)
if testnum < 0 || testnum > 100 {
fmt.Print("test cases consists of one line containing an integer X (0 < X <= 100)")
os.Exit(0)
}
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
scanner.Text()
var test = scanner.Text()
input := strings.Split(test, " ")
//when X==0, skip the conversion
if testnum != 0 {
convert(input)
}
result = append(result, sum)
}
//calculate each test case's sum of squares
func convert(strarray []string) {
var ctstr int //convert the string array into integers
ctstr, err := strconv.Atoi(strarray[i])
if ctstr < -100 || ctstr > 100 {
fmt.Print("integers should be: (Yn, -100 <= Yn <= 100)")
os.Exit(0)
}
//calculate the sum of squares of the integers excepting negatives
if ctstr > 0 {
sum += ctstr * ctstr //return the square value if it's not negative
}
i++
if err != nil {
panic(err)
}
if i < testnum {
convert(strarray)
} else {
return
}
}
func printresult() {
if j < casenum {
if j+1 == casenum {
//no newline if it's the last number
fmt.Fprintf(os.Stdout, "%d", result[j])
} else {
fmt.Fprintf(os.Stdout, "%d\n", result[j])
}
j++
printresult()
} else {
return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment