Skip to content

Instantly share code, notes, and snippets.

@vznvzn
Created November 9, 2015 17:09
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/ccbd184c5e6f0458527d to your computer and use it in GitHub Desktop.
Save vznvzn/ccbd184c5e6f0458527d to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby1.8
def fs()
lo = [lambda { |n| n * 3 + 1 }, lambda { |n| (n * 3 + 1) / 2 },
lambda { |n| n = (n * 3 + 1) / 2 while (n.odd?); n }]
le = [lambda { |n| n / 2 }, lambda { |n| n /= 2 while (n.even?); n }]
l = []
lo.each \
{
|o, i|
le.each \
{
|e, j|
next if (o == lo.first && e == le.last)
l << lambda \
{
|n|
n = o.call(n) if (n.odd?)
n = e.call(n) if (n.even?)
n
}
}
}
return l
end
def dense(n)
s = n.to_s(2)
c = 0
s.length.times \
{
|i|
c += s[i, 1].to_i
}
return c.to_f / s.length
end
def widthdiff(x, y)
x.to_s(2).length - y.to_s(2).length
end
def widthratio(x, y)
x.to_s(2).length.to_f / y.to_s(2).length
end
def f(n, w)
n1 = n
c = 0
l = [n]
cg = nil
while (n != 1)
n = $f.call(n)
l << n
c += 1
cg = c if (cg.nil? && n < n1)
break if (!cg.nil? && w != 'c')
end
cm = (0...l.size).max_by { |x| l[x] }
return {'cm' => cm,
'cg' => cg.nil? ? 0 : cg,
'm' => l[cm].to_s(2).length,
'w' => widthdiff(l[cm], n1),
'r' => widthratio(l[cm], n1),
'c' => l.size,
'd' => (0.5 - dense(n1)).abs}
end
def long(m, w)
return {'n' => rand(2 ** m) | 1 } if (w == 'z')
l = [{'n' => 1, 'p' => 0}.merge(f(1, w))]
t = 0
e = 2000
loop \
{
l = l.sort_by { |x| [x[w], -x['d']] }.reverse
x = l.delete_at(rand([l.size, 20].min))
p2 = x['p'] + 1
n2 = x['n'] + 2 ** p2
x1 = x.dup
x1['p'] = p2
l << x1
x2 = {'n' => n2, 'p' => p2}.merge(f(n2, w))
l << x2
t += 1
w2 = w
if (w == 'r') then
z = l.sort_by { |x| x['n'] }.reverse[0...100].max_by { |x| x['r'] }
w2 = 's'
else
z = l.max_by { |x| x[w] }
end
z.merge!({ 't' => t, 's' => t.to_f / e })
return z if (z[w2] >= m)
return if (t >= e)
}
end
def run1(p, k, m, j)
r = p[k]
a, b = r
x = a + m * (b - a)
z = long(x, k)
s = ns = nil
if (!z.nil?) then
s = z['s']
ns = z['n'].to_s(2).length
end
$stderr.puts([k, j, r3(m), r3(x), r3(s), ns].inspect)
return if (z.nil?)
z['x'] = x
return z
end
def r3(x)
x.nil? ? nil : sprintf("%.3f", x).to_f
end
def test(p, k, j)
$f = $fs[j]
y = -10
w = 0.25
i = 0
x = nil
loop \
{
z = run1(p, k, w, j)
if (z.nil? || w > 2.0) then
$stderr.puts('***')
if (i - y < 10 || w > 2.0) then
p([k, j, r3(w), r3(x)])
return
end
y = i
else
x = z['x']
end
w += 0.01
i += 1
}
end
p = {'p' => [0, 350],
'c' => [0, 1200],
'w' => [0, 75],
'm' => [0, 350],
'cg' => [0, 350],
'cm' => [0, 200],
'r' => [0.0, 1.0],
'z' => [0, 1000]
}
$fs = fs()
p.keys[0...-2].each { |k| $fs.size.times { |j| test(p, k, j) }; puts; $stdout.flush; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment