'Executing function upon required number of times
calculate the sum of squares of given integers, excluding any negatives. The first line of the input will be an integer N (1 <= N <= 100), indicating the number of test cases to follow. Each of the test cases will consist of a line with an integer X (0 < X <= 100), followed by another line consisting of X number of space-separated integers Yn (-100 <= Yn <= 100). For each test case, calculate the sum of squares of the integers, excluding any negatives, and print the calculated sum in the output.
Note: There should be no output until all the input has been received. Note 2: Do not put blank lines between test cases solutions. Note 3: Take input from standard input, and output to standard output.
Rules Write your solution using Go Programming Language Your source code must be a single file (package main) Do not use any for statement You may only use standard library packages
"Problem which I am facing" 'square' function below is not getting executed the required number of times according to the input test cases. To meet specific requirements I wasn't allowed to use the 'for' statement. Please help me out. Language is Go.
package main
import "fmt"
var s []int
func square(l int) {
i := 0
sum := 0
Square:
if l > 0 {
s[i] = s[i] * s[i]
sum = sum + s[i]
i++
l--
goto Square
}
fmt.Println(sum)
}
func myfunc(a int) {
Here:
if a > 0 {
var b int
fmt.Scanln(&b)
if b > 0 {
s = append(s, b)
}
a--
goto Here
}
}
func main() {
var a int
fmt.Scanln(&a)
TestCases:
if a > 0 {
var T int
fmt.Scanln(&T)
myfunc(T)
a--
goto TestCases
}
square(len(s))
}
Solution 1:[1]
Here is an implementation using recursion:
package main
import "fmt"
func testCase(N int) {
if N <= 0 {
return
}
var X int
fmt.Scanf("%d", &X)
fmt.Println(sumOfSquare(X))
testCase(N-1)
}
func sumOfSquare(X int) int {
if X == 0 {
return 0
}
var Y int
fmt.Scanf("%d", &Y)
if Y > 0 {
return Y*Y + sumOfSquare(X-1)
}
return sumOfSquare(X-1)
}
func main() {
var N int
fmt.Scanf("%d", &N)
testCase(N)
}
Here is an example output:
$ go run main.go
2 4 3 -1 1 14 5 9 6 -53 32 16
206
1397
Solution 2:[2]
I have this program in python using recursion, but not in go-lang. Here is the code
def squaresum(counter,alist):
if counter==0:
return 0
else:
if int(alist[counter-1])<0:
return 0 + squaresum(counter-1, alist)
else:
return int(alist[counter-1])**2 + squaresum(counter-1,alist)
def testcase(a):
if a==0:
return
terms = int(input())
nums = input()
list1 = nums.split()
print(squaresum(terms,list1))
testcase(a-1)
if __name__=='__main__':
casecount = int(input())
testcase(casecount)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | rekxspein |