Skip to content

Commit

Permalink
Merge 3c86651 into 2eeba64
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Oct 26, 2019
2 parents 2eeba64 + 3c86651 commit ee7c8ca
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ problems from
* [Day 331](https://github.com/vaskoz/dailycodingproblem-go/issues/666)
* [Day 332](https://github.com/vaskoz/dailycodingproblem-go/issues/669)
* [Day 333](https://github.com/vaskoz/dailycodingproblem-go/issues/668)
* [Day 334](https://github.com/vaskoz/dailycodingproblem-go/issues/670)
* [Day 337](https://github.com/vaskoz/dailycodingproblem-go/issues/674)
* [Day 338](https://github.com/vaskoz/dailycodingproblem-go/issues/675)
* [Day 339](https://github.com/vaskoz/dailycodingproblem-go/issues/676)
Expand Down
42 changes: 42 additions & 0 deletions day334/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package day334

const goal = 24

// TwentyFourGame returns true if the game of 24
// is possible given this input.
// Operators used are: +, -, *, and /
func TwentyFourGame(digits []int) bool {
if len(digits) == 1 {
return digits[0] == goal
}

for i := 0; i < len(digits)-1; i++ {
for _, op := range []rune{'+', '-', '*', '/'} {
var next []int
next = append(next, digits[:i]...)

switch op {
case '+':
next = append(next, digits[i]+digits[i+1])
case '-':
next = append(next, digits[i]-digits[i+1])
case '*':
next = append(next, digits[i]*digits[i+1])
case '/':
if digits[i+1] == 0 {
continue
}

next = append(next, digits[i]/digits[i+1])
}

next = append(next, digits[i+2:]...)

if TwentyFourGame(next) {
return true
}
}
}

return false
}
32 changes: 32 additions & 0 deletions day334/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package day334

import "testing"

// nolint
var testcases = []struct {
digits []int
expected bool
}{
{[]int{5, 2, 7, 8}, true},
{[]int{100, 100, 100, 100, 100}, false},
{[]int{2, 2, 2, 2, 2, 2, 2, 2, 2}, true},
{[]int{5760000, 10, 30, 40, 20}, true},
}

func TestTwentyFourGame(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if result := TwentyFourGame(tc.digits); result != tc.expected {
t.Errorf("Given %v, expected %v, got %v", tc.digits, tc.expected, result)
}
}
}

func BenchmarkTwentyFourGame(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
TwentyFourGame(tc.digits)
}
}
}

0 comments on commit ee7c8ca

Please sign in to comment.