add result struct to package one

remove unnecessary assignments in util.splitNumber
This commit is contained in:
onyx-and-iris 2024-12-12 02:53:33 +00:00
parent cf22aff066
commit 2dc1d494af
4 changed files with 42 additions and 16 deletions

View File

@ -0,0 +1,29 @@
package one
import "fmt"
const (
flip = iota
split
multiply
)
type result struct {
kind int
left int
right int
}
func (r result) String() string {
var kindStr string
switch r.kind {
case flip:
kindStr = "flip"
case split:
kindStr = "split"
case multiply:
kindStr = "multiply"
}
return fmt.Sprintf("kind: %s left: %d right: %d", kindStr, r.left, r.right)
}

View File

@ -28,11 +28,14 @@ func Solve(buf []byte) (int, error) {
next := queue.New[int]() next := queue.New[int]()
for !old.IsEmpty() { for !old.IsEmpty() {
n := old.Dequeue() n := old.Dequeue()
left, right, ok := applyRules(n) r := applyRules(n)
if ok { switch r.kind {
next.Enqueue(left) case flip, multiply:
next.Enqueue(r.right)
case split:
next.Enqueue(r.left)
next.Enqueue(r.right)
} }
next.Enqueue(right)
} }
old = next old = next
@ -42,14 +45,14 @@ func Solve(buf []byte) (int, error) {
return old.Len(), nil return old.Len(), nil
} }
func applyRules(num int) (int, int, bool) { func applyRules(num int) result {
switch num := num; { switch num := num; {
case num == 0: case num == 0:
return 0, 1, false return result{flip, 0, 1}
case lenItoa(num)%2 == 0: case lenItoa(num)%2 == 0:
left, right := splitNumber(num) left, right := splitNumber(num)
return left, right, true return result{split, left, right}
default: default:
return 0, num * magic, false return result{multiply, 0, num * magic}
} }
} }

View File

@ -44,10 +44,7 @@ func mustConv(s string) int {
func splitNumber(n int) (int, int) { func splitNumber(n int) (int, int) {
factor := int(math.Pow10(lenItoa(n) / 2)) factor := int(math.Pow10(lenItoa(n) / 2))
right := n % factor return int(n / factor), n % factor
left := int(n / factor)
return left, right
} }
func lenItoa(n int) int { func lenItoa(n int) int {

View File

@ -44,10 +44,7 @@ func mustConv(s string) int {
func splitNumber(n int) (int, int) { func splitNumber(n int) (int, int) {
factor := int(math.Pow10(lenItoa(n) / 2)) factor := int(math.Pow10(lenItoa(n) / 2))
left := int(n / factor) return int(n / factor), n % factor
right := n % factor
return left, right
} }
func lenItoa(n int) int { func lenItoa(n int) int {