-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #930 from vaskoz/day460
Day460
- Loading branch information
Showing
3 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |