-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path263.go
54 lines (48 loc) · 969 Bytes
/
263.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// UVa 263 - Number Chains
package main
import (
"fmt"
"io"
"os"
"sort"
"strconv"
)
func sortInt(num string, descending bool) int {
d := []byte(num)
if descending {
sort.Slice(d, func(i, j int) bool { return d[i] > d[j] })
} else {
sort.Slice(d, func(i, j int) bool { return d[i] < d[j] })
}
var n int
fmt.Sscanf(string(d), "%d", &n)
return n
}
func solve(out io.Writer, num string) {
fmt.Fprintf(out, "Original number was %s\n", num)
chains := make(map[int]bool)
for {
d, a := sortInt(num, true), sortInt(num, false)
diff := d - a
fmt.Fprintf(out, "%d - %d = %d\n", d, a, diff)
if chains[diff] {
break
}
chains[diff] = true
num = strconv.Itoa(diff)
}
fmt.Fprintf(out, "Chain length %d\n\n", len(chains)+1)
}
func main() {
in, _ := os.Open("263.in")
defer in.Close()
out, _ := os.Create("263.out")
defer out.Close()
var num string
for {
if fmt.Fscanf(in, "%s", &num); num == "0" {
break
}
solve(out, num)
}
}