I am trying to write a test case in my main function for the following code that is used to find the product and sum of a nested array:
package main
import "fmt"
type SpecialArray []interface{}
func ProductSum(array SpecialArray) int {
return helper(array, 1)
}
func helper(array SpecialArray, multiplier int) int {
sum := 0
for _, el := range array {
if cast, ok := el.(SpecialArray); ok {
sum = helper(cast, multiplier 1)
} else if cast, ok := el.(int); ok {
sum = cast
}
}
return sum * multiplier
}
Given a nested array with a mix of ints and arrays, the above code should return the sum of all elements. Elements within a nested array will be summed then multiplied by their depth, i.e.,
[1, [2, 3], 2] = 1 2(2 3) 2 = 13
I am having trouble understanding the SpecialArray []interface{} type. My first attempt was to simply define a nested slice in my main function as follows:
func main() {
SpecialArray := [][]int{1, {2, 3}, 2}
result := ProductSum(SpecialArray)
fmt.Println(result)
}
But this is not working. I'm assuming I need to initalize my SpecialArray interface with values and pass that to my ProductSum function.
CodePudding user response:
You are very close but did not quite get the array literal syntax right:
func main() {
special := SpecialArray{1, SpecialArray{2, 3}, 2}
result := ProductSum(special)
fmt.Println(result)
}
Also your helper
function is fine as is but you might consider using a type switch:
func helper(array SpecialArray, multiplier int) int {
sum := 0
for _, v := range array {
switch v := v.(type) {
case int:
sum = v
case SpecialArray:
sum = helper(v, multiplier 1)
default:
log.Fatalf("Unknown type: %T", v)
}
}
return sum * multiplier
}
BTW the SpecialArray
type is a slice not an array.