Skip to content

Commit

Permalink
Merge pull request #930 from vaskoz/day460
Browse files Browse the repository at this point in the history
Day460
  • Loading branch information
vaskoz committed Feb 25, 2020
2 parents 0af9bd0 + bc59054 commit 93b1af5
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -457,4 +457,5 @@ problems from
* [Day 457](https://github.com/vaskoz/dailycodingproblem-go/issues/923)
* [Day 458](https://github.com/vaskoz/dailycodingproblem-go/issues/925)
* [Day 459](https://github.com/vaskoz/dailycodingproblem-go/issues/927)
* [Day 460](https://github.com/vaskoz/dailycodingproblem-go/issues/929)

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

// FlipsXsBeforeYs returns the minimum number of flips
// required to meet the condition that the result should
// have all X's before Y's.
// Runs in O(N) time and O(1) space.
func FlipsXsBeforeYs(input string) int {
streakX, streakY := true, true

var changeXtoY, changeYtoX int

for forward, backward := 0, len(input)-1; forward < len(input); forward, backward = forward+1, backward-1 {
if streakX && input[forward] != 'x' {
streakX = false
}

if streakY && input[backward] != 'y' {
streakY = false
}

if !streakX && input[forward] == 'x' {
changeXtoY++
}

if !streakY && input[backward] == 'y' {
changeYtoX++
}
}

if changeXtoY < changeYtoX {
return changeXtoY
}

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

import "testing"

// nolint
var testcases = []struct {
input string
flips int
}{
{"xyxxxyxyy", 2},
{"yxxyyyy", 1},
{"yyyxy", 1},
{"yxyxyx", 3},
{"yyyyxyyyxyyyyxx", 4},
{"xxxxxxx", 0},
{"yyyyyyyyyy", 0},
{"xyyyyyyyy", 0},
{"xxxxxxxxyyy", 0},
{"xxxyyxxyyxxyyyyyyyyy", 4},
}

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

for _, tc := range testcases {
if flips := FlipsXsBeforeYs(tc.input); flips != tc.flips {
t.Errorf("Expected %v, got %v", tc.flips, flips)
}
}
}

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

0 comments on commit 93b1af5

Please sign in to comment.