-
Notifications
You must be signed in to change notification settings - Fork 7
/
112 Bouncy numbers.sf
148 lines (101 loc) · 2.74 KB
/
112 Bouncy numbers.sf
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#!/usr/bin/ruby
# Author: Trizen
# Date: 12 April 2023
# https://github.com/trizen
# Generate numbers with increasing and decreasing digits, in a given base.
# See also:
# https://projecteuler.net/problem=112
# Runtime: 1 minute, 19 seconds.
func increasing_numbers(limit, base=10) {
func f(n, min_d) {
var seq = [n]
for d in (min_d ..^ base) {
var v = (n*base + d)
v <= limit || break
seq << __FUNC__(v, d)...
}
return seq
}
map(1..min(limit,base-1), {|d| f(d, d) }).flat.sort
}
func decreasing_numbers(limit, base=10) {
func f(n, max_d) {
var seq = [n]
for d in (0 .. max_d) {
var v = (n*base + d)
v <= limit || break
seq << __FUNC__(v, d)...
}
return seq
}
map(1..min(limit,base-1), {|d| f(d, d) }).flat.sort
}
func increasing_numbers_count(limit, base=10) {
func f(n, min_d) {
var count = 1
for d in (min_d ..^ base) {
var v = (n*base + d)
v <= limit || break
count += __FUNC__(v, d)
}
return count
}
sum(1..min(limit,base-1), {|d| f(d,d) })
}
func decreasing_numbers_count(limit, base=10) {
func f(n, max_d) {
var count = 1
for d in (0 .. max_d) {
var v = (n*base + d)
v <= limit || break
count += __FUNC__(v, d)
}
return count
}
sum(1..min(limit,base-1), {|d| f(d,d) })
}
func non_bouncy_count_slow(limit, base=10) {
increasing_numbers(limit, base) + decreasing_numbers(limit, base) -> uniq.len
}
func non_bouncy_count(limit, base=10) {
if (limit < base) {
return max(0, limit)
}
var t = (increasing_numbers_count(limit, base) + decreasing_numbers_count(limit, base))
t -= ((base-1) * (limit.len(base)-1))
var r = (base**limit.len(base) - 1)/(base-1)
for d in (1 ..^ base) {
r*d > limit && break
--t
}
return t
}
assert_eq(
2e2.of(non_bouncy_count),
2e2.of(non_bouncy_count_slow)
)
assert_eq(
non_bouncy_count_slow(1e3),
non_bouncy_count(1e3),
)
assert_eq(
non_bouncy_count_slow(23870),
non_bouncy_count(23870)
)
var target = 0.99
say ":: Searching for an upper-bound, using binary search..."
var upper_bound = {|k|
(1 - non_bouncy_count(k)/k) <=> target
}.bsearch(100)
say ":: Upper-bound: #{upper_bound}"
var non_bouncy = Set(increasing_numbers(upper_bound)+decreasing_numbers(upper_bound) -> sort.uniq...)
var nbc = non_bouncy.len
assert_eq(nbc, non_bouncy_count(upper_bound))
for (var k = upper_bound; k > 1; --k) {
if ((1 - nbc/k) == target) {
say ":: Candidate: #{k}"
}
if (non_bouncy.has(k)) {
--nbc
}
}