Skip to content

Instantly share code, notes, and snippets.

@vznvzn
Created March 30, 2019 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vznvzn/546d6eff36b8d6f85c13e4b54cf90194 to your computer and use it in GitHub Desktop.
Save vznvzn/546d6eff36b8d6f85c13e4b54cf90194 to your computer and use it in GitHub Desktop.
def f2(n)
return n.odd? ? (n * 3 + 1) / 2 : n / 2
end
def dense(w, d)
w2 = w - 1
a = (0...w2).to_a
s = '0' * w2
(1..(d * w - 1)).map { a.delete_at(rand(a.size)) }.each { |x| s[x, 1] = '1' }
return ('1' + s)
end
def lenx(ns, p)
l = ns.split(p)
l = [] if (l.nil?)
l.shift if (l[0] == '')
return l.map { |x| x.length }
end
def len01x(ns)
return lenx(ns, /0+/), lenx(ns, /1+/)
end
def mx01x(ns)
l1, l0 = len01x(ns)
return (l1 + l0).max
end
def add(l, mxp, n, x)
p = (n % 2).to_s + x['p']
return if (mx01x(p) >= mxp)
w = n.to_s(2).length
l1 = [n] + x['l']
c = x['c'] + (n.even? ? 1 : 0)
l << {'n' => n,
'p' => p,
'w' => n.to_s(2).length,
'r' => c.to_f / w,
'l' => l1,
'c' => c}
end
def back(ns)
mxp = 4
add(l = [], mxp, ns.to_i(2), {'p' => '', 'l' => [], 'c' => 0})
mx = nil
k = 'r'
t = 0
e = 2
loop \
{
return if (l.empty?)
break if (!mx.nil? && mx[k] >= e)
l.sort_by! { |x| -x[k] }
mx = [l[0], mx].compact.max_by { |x| x[k] }
x = l.delete_at(rand([l.size, 50].min))
$stderr.puts([t, x[k]].join("\t")) if (t % 100 == 0)
n = x['n']
add(l, mxp, (n - 1) / 3, x) if ((n - 1) % 3 == 0 && ((n - 1) / 3).odd?)
add(l, mxp, n * 2, x)
t += 1
}
return mx
end
def seq(n)
l = [n]
while (n != 1)
n = f2(n)
l << n
end
return l
end
def out(l, c)
l.each_with_index \
{
|x, j|
puts([j, x.to_s(2).length, c].join("\t"))
}
puts
end
def construct(b)
x = nil
begin
ns = dense(100, 0.5)
ns[49, 50] = b * 50
x = back(ns)
end while (x.nil?)
x.delete('l')
$stderr.puts(x.inspect)
n = x['n']
ns = n.to_s(2)
ns = '1' + ns
ns2 = ns.dup
ns2[0, 2] = '10'
out(seq(n), 1)
out(seq(ns.to_i(2)), 2)
out(seq(ns2.to_i(2)), 3)
end
construct('1')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment