From 0e9f5569d800b4188bb873474e3f488b2fc5c3f5 Mon Sep 17 00:00:00 2001 From: Vasko Zdravevski Date: Wed, 25 Dec 2019 21:43:18 -0700 Subject: [PATCH 1/2] day 289: can player one force a win. simple xor theorem --- day289/problem.go | 13 +++++++++++++ day289/problem_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 day289/problem.go create mode 100644 day289/problem_test.go diff --git a/day289/problem.go b/day289/problem.go new file mode 100644 index 0000000..f18c801 --- /dev/null +++ b/day289/problem.go @@ -0,0 +1,13 @@ +package day289 + +// CanFirstPlayerForceWinNimGame answers if the first player +// can force a win with the given heap configuration. +func CanFirstPlayerForceWinNimGame(heaps []int) bool { + sum := 0 + + for _, heap := range heaps { + sum ^= heap + } + + return sum != 0 +} diff --git a/day289/problem_test.go b/day289/problem_test.go new file mode 100644 index 0000000..b57990a --- /dev/null +++ b/day289/problem_test.go @@ -0,0 +1,35 @@ +package day289 + +import "testing" + +// nolint +var testcases = []struct { + heaps []int + forcedWin bool +}{ + {[]int{3, 4, 5}, true}, + {[]int{1, 2, 3}, false}, + {[]int{1, 4, 5}, false}, + {[]int{1, 6, 7}, false}, + {[]int{5, 9, 12}, false}, + {[]int{1, 2, 4, 7}, false}, + {[]int{1, 2, 4, 6}, true}, +} + +func TestCanFirstPlayerForceWinNimGame(t *testing.T) { + t.Parallel() + + for _, tc := range testcases { + if res := CanFirstPlayerForceWinNimGame(tc.heaps); res != tc.forcedWin { + t.Errorf("Expected %v, got %v", tc.forcedWin, res) + } + } +} + +func BenchmarkCanFirstPlayerForceWinNimGame(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, tc := range testcases { + CanFirstPlayerForceWinNimGame(tc.heaps) + } + } +} From 214fd2d1e8c4892dcf8b057a217a8a245c0936e1 Mon Sep 17 00:00:00 2001 From: Vasko Zdravevski Date: Wed, 25 Dec 2019 21:44:05 -0700 Subject: [PATCH 2/2] add day 289 to readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index fe4c781..c05c33b 100644 --- a/README.md +++ b/README.md @@ -300,6 +300,7 @@ problems from * [Day 286](https://github.com/vaskoz/dailycodingproblem-go/issues/585) * [Day 287](https://github.com/vaskoz/dailycodingproblem-go/issues/587) * [Day 288](https://github.com/vaskoz/dailycodingproblem-go/issues/590) +* [Day 289](https://github.com/vaskoz/dailycodingproblem-go/issues/593) * [Day 290](https://github.com/vaskoz/dailycodingproblem-go/issues/594) * [Day 291](https://github.com/vaskoz/dailycodingproblem-go/issues/596) * [Day 292](https://github.com/vaskoz/dailycodingproblem-go/issues/598)