Remove string operations

This commit is contained in:
Brian Buller 2018-12-05 09:12:29 -06:00
parent 8d07292616
commit 9f64a7e63d

View File

@ -2,26 +2,26 @@ package main
import ( import (
"bufio" "bufio"
"bytes"
"fmt" "fmt"
"log" "log"
"math" "math"
"os" "os"
"strconv" "strconv"
"strings"
) )
func main() { func main() {
inp := StdinToString() inp := []byte(StdinToString())
fmt.Println("= Part 1 =") fmt.Println("= Part 1 =")
fmt.Println(part1(inp)) fmt.Println(part1(inp))
fmt.Println("\n= Part 2 =") fmt.Println("\n= Part 2 =")
fmt.Println(part2(inp)) fmt.Println(part2(inp))
} }
func part1(inp string) int { func part1(inp []byte) int {
last := inp last := inp
curr := react(last) curr := react(last)
for last != curr { for !bytes.Equal(last, curr) {
last = curr last = curr
curr = react(last) curr = react(last)
} }
@ -32,16 +32,16 @@ func part1(inp string) int {
// It reduced _my_ runtime by about 3 minutes, but may fail depending on your input // It reduced _my_ runtime by about 3 minutes, but may fail depending on your input
var useShortest bool var useShortest bool
func part2(inp string) int { func part2(inp []byte) int {
// If yours fails, try setting this to false // If yours fails, try setting this to false
useShortest = true useShortest = true
shortest := len(inp) shortest := len(inp)
var shortestCount int var shortestCount int
var count int var count int
for i := 65; i <= 90; i++ { for i := 65; i <= 90; i++ {
var try string var try []byte
if useShortest { if useShortest {
count = strings.Count(inp, string(i)) count = countByte(inp, byte(i))
if count < shortestCount { if count < shortestCount {
continue continue
} }
@ -50,7 +50,7 @@ func part2(inp string) int {
if int(inp[j]) == i || int(inp[j]) == i+32 { if int(inp[j]) == i || int(inp[j]) == i+32 {
continue continue
} }
try += string(inp[j]) try = append(try, inp[j])
} }
v := part1(try) v := part1(try)
if v < shortest { if v < shortest {
@ -61,14 +61,24 @@ func part2(inp string) int {
return shortest return shortest
} }
func react(v string) string { func countByte(h []byte, n byte) int {
var ret string var ret int
for i := range h {
if h[i] == n {
ret++
}
}
return ret
}
func react(v []byte) []byte {
var ret []byte
for i := 0; i < len(v); i++ { for i := 0; i < len(v); i++ {
if i < len(v)-1 && Abs(v[i], v[i+1]) == 32 { if i < len(v)-1 && Abs(v[i], v[i+1]) == 32 {
i++ i++
continue continue
} }
ret += string(v[i]) ret = append(ret, v[i])
} }
return ret return ret
} }