diff --git a/README.md b/README.md index 53e3c0f..4c01982 100644 --- a/README.md +++ b/README.md @@ -197,3 +197,4 @@ problems from * [Day 184](https://github.com/vaskoz/dailycodingproblem-go/issues/378) * [Day 185](https://github.com/vaskoz/dailycodingproblem-go/issues/381) * [Day 186](https://github.com/vaskoz/dailycodingproblem-go/issues/382) +* [Day 188](https://github.com/vaskoz/dailycodingproblem-go/issues/388) diff --git a/day188/problem.go b/day188/problem.go new file mode 100644 index 0000000..be43a93 --- /dev/null +++ b/day188/problem.go @@ -0,0 +1,25 @@ +package day188 + +// MakeFunctionsOriginal is the problem version. +func MakeFunctionsOriginal() []func() int { + var funcList []func() int + for _, i := range []int{1, 2, 3} { + funcList = append(funcList, func() int { + return i + }) + } + return funcList +} + +// MakeFunctionsCorrect is the corrected version. +func MakeFunctionsCorrect() []func() int { + var funcList []func() int + for _, i := range []int{1, 2, 3} { + funcList = append(funcList, func(i int) func() int { + return func() int { + return i + } + }(i)) + } + return funcList +} diff --git a/day188/problem.py b/day188/problem.py new file mode 100644 index 0000000..21b50d4 --- /dev/null +++ b/day188/problem.py @@ -0,0 +1,13 @@ +def make_functions(): + flist = [] + + for i in [1, 2, 3]: + def print_i(): + print(i) + flist.append(print_i) + + return flist + +functions = make_functions() +for f in functions: + f() diff --git a/day188/problem_correct.py b/day188/problem_correct.py new file mode 100644 index 0000000..59b0407 --- /dev/null +++ b/day188/problem_correct.py @@ -0,0 +1,15 @@ +def make_functions(): + flist = [] + + for i in [1, 2, 3]: + def build_print_i(i): + def print_i(): + print(i) + return print_i + flist.append(build_print_i(i)) + + return flist + +functions = make_functions() +for f in functions: + f() diff --git a/day188/problem_test.go b/day188/problem_test.go new file mode 100644 index 0000000..0b5dd58 --- /dev/null +++ b/day188/problem_test.go @@ -0,0 +1,23 @@ +package day188 + +import "testing" + +func TestMakeFunctionsOriginal(t *testing.T) { + t.Parallel() + funcs := MakeFunctionsOriginal() + for _, f := range funcs { + if result := f(); result != 3 { + t.Errorf("Expected every response to be 3. Got %v", result) + } + } +} + +func TestMakeFunctionsCorrect(t *testing.T) { + t.Parallel() + funcs := MakeFunctionsCorrect() + for i, f := range funcs { + if result := f(); result != i+1 { + t.Errorf("Expected %v, got %v", i+1, result) + } + } +}