Could golang implement this interview question of getting array summary without for/while if/else?

Viewed 86

I'm looking into an interesting interview question, and try to implement it with go.

(1) Input an integer number, say i

(2) Calculate the summary of 1+2+...+i, output the summary

(3) Requirement: don't use multiply, don't use loop(for/while), and don't use if/else

Well, in c++ or java this is pretty easy. We can use static variable to initialize an object array, while the objects's constructor function calculate this summary. Like this:

#include <iostream>
struct s {
    static int count;
    static int sum;
    s() {++count; sum += count;}
};
int s::count = 0;
int s::sum = 0;
 
int main(int argc, char *argv[]) {
   s obj[10];
   std::cout << s::sum << std::endl; // 55, ok
   return 0;
}

(2) in c++ we could also use template type deduction to do this. Plenty samples on the internet.

But, can we achieve this with go language?

I know that golang has neither constructor function, nor it supports static variable. And it doesn't have any template syntax. Plus, using recursive function still requires if branches in the code.

So is this possible to do same thing in go? (no for loop, no if else). Thanks.

1 Answers

Here's a language-neutral solution that uses no multiplication, no for and no if.

It's kind of like a recursive solution, where the if is substituted with a function map, having functions for the true and false branches:

fs := map[bool]func(int) int{}
fs[false] = func(int) int { return 0 }
fs[true] = func(i int) int { return i + fs[i > 1](i-1) }

var i int
fmt.Scanln(&i)

fmt.Println("sum:", fs[i > 0](i))

Inputting 10, the output is (try it on the Go Playground):

sum: 55
Related