Skip to content

Commit

Permalink
Merge pull request #938 from vaskoz/day463
Browse files Browse the repository at this point in the history
Day463
  • Loading branch information
vaskoz committed Mar 2, 2020
2 parents 7036c83 + 7646af6 commit c969b2c
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,7 @@ problems from
* [Day 459](https://github.com/vaskoz/dailycodingproblem-go/issues/927)
* [Day 460](https://github.com/vaskoz/dailycodingproblem-go/issues/929)
* [Day 461](https://github.com/vaskoz/dailycodingproblem-go/issues/931)
* [Day 463](https://github.com/vaskoz/dailycodingproblem-go/issues/937)
* [Day 464](https://github.com/vaskoz/dailycodingproblem-go/issues/935)
* [Day 465](https://github.com/vaskoz/dailycodingproblem-go/issues/933)

38 changes: 38 additions & 0 deletions day463/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package day463

// MinimizeQux returns the smallest Qux slice
// possible.
// Runs in O(N*K) where K is the number of elements that can removed.
// Uses O(N) extra space to avoid modifying the input.
func MinimizeQux(input []rune) []rune {
lastLen := 0
copied := make([]rune, len(input))
copy(copied, input)

for len(copied) != lastLen {
lastLen = len(copied)
copied = minimizeQux(copied)
}

return copied
}

func minimizeQux(input []rune) []rune {
min := input

for i := 1; i < len(input); i++ {
if input[i] != input[i-1] {
missing := 'R' + 'G' + 'B' - input[i] - input[i-1]
end := append([]rune{missing}, input[i+1:]...)
candidate := append([]rune{}, input[:i-1]...)
candidate = append(candidate, end...)
candidate = minimizeQux(candidate)

if len(candidate) < len(min) {
min = candidate
}
}
}

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

import (
"reflect"
"testing"
)

// nolint
var testcases = []struct {
input []rune
expected []rune
}{
{[]rune{'R', 'G', 'B', 'G', 'B'}, []rune{'R'}},
{[]rune{'G', 'B', 'G', 'B'}, []rune{'B', 'B'}},
{[]rune{'B', 'B', 'B', 'R', 'G', 'G', 'G'}, []rune{'G', 'G'}},
}

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

for _, tc := range testcases {
if result := MinimizeQux(tc.input); !reflect.DeepEqual(tc.expected, result) {
t.Errorf("Expected %v, got %v", tc.expected, result)
}
}
}

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

0 comments on commit c969b2c

Please sign in to comment.