Skip to content

Commit

Permalink
...
Browse files Browse the repository at this point in the history
  • Loading branch information
jfallis committed Mar 20, 2024
1 parent f16cbed commit a965b54
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 16 deletions.
Binary file modified collatz.zip
Binary file not shown.
17 changes: 1 addition & 16 deletions pkg/collatz/collatz.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ package collatz
import (
"fmt"
"math/big"
"sync"
)

const (
Expand Down Expand Up @@ -40,7 +39,6 @@ type Collatz struct {
number *big.Int
steps []*big.Int
cache map[string][]*big.Int
mu sync.RWMutex
}

func New(num *big.Int) *Collatz {
Expand All @@ -60,24 +58,11 @@ func (c *Collatz) Calculate() error {
num := new(big.Int).Set(c.number)

for num.Cmp(minimum) != 0 || (counter == 0 && counter <= StepsLimit) {
c.mu.RLock()
cachedSteps, ok := c.cache[num.String()]
c.mu.RUnlock()

if ok {
c.steps = append(c.steps, cachedSteps...)
break
}

c.Sequence(num)
c.steps = append(c.steps, new(big.Int).Set(num))
counter++
}

c.mu.Lock()
c.cache[c.number.String()] = c.steps
c.mu.Unlock()

return nil
}

Expand All @@ -102,5 +87,5 @@ func (c *Collatz) Steps() []*big.Int {
func (c *Collatz) Success() bool {
length := len(c.Steps())

return length != 0 && c.Steps()[length-1].Cmp(big.NewInt(1)) != 0
return length != 0 && c.Steps()[length-1].Cmp(minimum) != 0
}

0 comments on commit a965b54

Please sign in to comment.