Skip to content

Commit

Permalink
prefix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
erhant committed Jul 2, 2023
1 parent e0630c5 commit 2db35db
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
4 changes: 2 additions & 2 deletions collatz/prefix.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ func PrefixIterate(n *big.Int, pf []uint) *big.Int {
n = Copy(n)

// R_0 function
n.Div(n, new(big.Int).Rsh(ONE, pf[0]))
n.Div(n, new(big.Int).Lsh(ONE, pf[0]))

// R function
for i := 1; i < len(pf); i++ {
n.Mul(n, THREE).Add(n, ONE)
n.Div(n, new(big.Int).Rsh(ONE, pf[i]-pf[i-1]))
n.Div(n, new(big.Int).Lsh(ONE, pf[i]-pf[i-1]))
}
return n
}
Expand Down
50 changes: 50 additions & 0 deletions collatz/prefix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,57 @@ import (
"testing"
)

// Find Prefix by simply comparing the ECFs
func prefixBrute(a []uint, b []uint) []uint {
// get the minimum length
l := len(a)
if len(b) < l {
l = len(b)
}

ans := make([]uint, 0)
for i := 0; i < l; i++ {
if a[i] == b[i] {
ans = append(ans, a[i])
} else {
break
}
}

return ans
}

func TestPrefix(t *testing.T) {
cases := []struct {
n *big.Int
m *big.Int
}{
{big.NewInt(1), big.NewInt(2)},
{big.NewInt(3), big.NewInt(12)},
{big.NewInt(8), big.NewInt(16)},
{big.NewInt(27), big.NewInt(37)},
}

for _, test := range cases {
// expected prefix found via ECFs
pf := prefixBrute(CollatzECF(test.n), CollatzECF(test.m))

if !EqualUints(pf, PrefixFind(test.n, test.m)) {
t.Errorf("Prefix is wrong.")
}

if !EqualUints(pf, PrefixFind(test.m, test.n)) {
t.Errorf("PrefixFind should be commutative.")
}

// test both numbers for ECF iteration
if PrefixIterate(test.n, CollatzECF(test.n)).Cmp(big.NewInt(1)) != 0 {
t.Errorf("Iterating over ECF should result in 1.")
}
if PrefixIterate(test.m, CollatzECF(test.m)).Cmp(big.NewInt(1)) != 0 {
t.Errorf("Iterating over ECF should result in 1.")
}
}
}

func TestPrefixAdd(t *testing.T) {
Expand All @@ -22,6 +71,7 @@ func TestPrefixAdd(t *testing.T) {
{[]uint{1}, nil, []uint{1}},
// normal cases
{[]uint{2, 4}, []uint{4}, []uint{2, 8}},
{[]uint{4}, []uint{2, 4}, []uint{6, 8}},
{[]uint{0, 1, 5}, []uint{0, 1, 3}, []uint{0, 1, 5, 6, 8}},
}

Expand Down

0 comments on commit 2db35db

Please sign in to comment.