Index finite lists of positive integers: Difference between revisions
Content added Content deleted
m (fixed an HTML tag.) |
(→{{header|Go}}: cleanups. handle empty list, return errors rather than panic, add output showing empty list and errors.) |
||
Line 58:
)
//
// Unfortunately base 11 is a little awkward with big.Int, so just treat it
// as base 16.
func rank(l []big.Int)
if len(l) == 0 {
}▼
s := make([]string, len(l))
for i, n := range l {
if ns[0] == '-' {
▲ }
return r, fmt.Errorf("negative integers not mapped")
i, ok := new(big.Int).SetString(strings.Join(s, "a"), 16)▼
}
return
}
// Split the base 16 representation at "a", recover the base 10 numbers.
func unrank(r
switch {
case s16 == "0":
return nil, nil // empty list
case s16[0] != 'a':
return nil, fmt.Errorf("unrank not bijective")
}
s := strings.Split(s16[1:], "a")
l := make([]big.Int, len(s))
for i, s1 := range s {
if _, ok := l[i].SetString(s1, 10); !ok {
return nil, fmt.Errorf("unrank not bijective")
▲ if !ok {
}
}
return l, nil
}
func main() {
var l []big.Int
fmt.Println("List:")▼
r, _ := rank(l)▼
u, _ := unrank(r)▼
fmt.Println("Empty list:", l, &r, u)
// show random list
l = random()
r, _ = rank(l)
u, _ = unrank(r)
for _, n := range l {
fmt.Println(" ", &n)
}
▲ r := rank(l)
fmt.Println("Rank:")
fmt.Println(" ", &r)
▲ u := unrank(r)
fmt.Println("Unranked:")
for _, n := range u {
fmt.Println(" ", &n)
}
// show error with list containing negative
var n big.Int
n.SetInt64(-5)
_, err := rank([]big.Int{n})
fmt.Println("\nList element:", &n, err)
// show technique is not bijective
n.SetInt64(1)
_, err = unrank(n)
fmt.Println("Rank:", &n, err)
}
// returns
func random() []big.Int {
r := rand.New(rand.NewSource(time.Now().Unix()))
l := make([]big.Int,
one := big.NewInt(1)
max := new(big.Int).Lsh(one, 100)
Line 114 ⟶ 143:
{{out}}
<pre>
Empty list: [] 0 []
List:
170245492534662309353778826165
82227712638678862510272817700
Rank:
17827272030291729487097780664374477811820701746650470453292650775464474368
Unranked:
170245492534662309353778826165
82227712638678862510272817700
List element: -5 negative integers not handled
Rank: 1 unrank not bijective
</pre>
|