Skip to content

Instantly share code, notes, and snippets.

@vznvzn vznvzn/bitwise25.rb
Created Feb 24, 2019

Embed
What would you like to do?
def f2(n)
return n.odd? ? (n * 3 + 1) / 2 : n / 2
end
def seq(n, c)
l = [n]
loop \
{
return l if (l.size == c)
raise "n = 1" if (n == 1)
n = f2(n)
l << n
}
end
def d(s)
c = s.split('').select { |x| x == '1' }.size
d = c.to_f / s.length
return d
end
def keys(ks2)
ks = []
ksmx = []
ks2.each \
{
|x|
if (x.end_with?('-')) then
x = x.dup
x.chop
else
ksmx << x
end
ks << x
}
return ks, ksmx
end
def order(l, ks2)
l2 = (0...l.size).map { {} }
ks, ksmx = keys(ks2)
ks.each \
{
|k|
l1 = (0...l.size).map { |x| {k => l[x][k], 'i' => x} }
s = ksmx.member?(k) ? -1 : 1
l1.sort_by! { |x| s * x[k] }
(0...l1.size).each { |x| l2[l1[x]['i']][k] = x }
}
l2.each { |x| x['z'] = x.values.inject(0) { |t, x| t + x } }
return (0...l2.size).sort_by { |x| l2[x]['z'] }
end
def out(a, a2 = {}, t = nil)
fn = 'out.txt'
k = a.keys
if ($f1.nil?) then
$f1 = File.open(fn, 'w')
$f1.puts(k.join("\t"))
f2 = File.open('gnuplot.cmd', 'w')
st = t.nil? ? 'unset title; ' : "set title '#{t}'; "
f2.puts("set ytics nomirror; set y2tics; set colors classic; set key top left box opaque; #{st}; plot \\")
(a.keys - ['t']).each \
{
|x|
f2.puts("'#{fn}' using (column('t')):(column('#{x}')) with line title '#{x}' #{a2[x]}, \\")
}
f2.puts
f2.close
end
$f1.puts(a.values_at(*k).join("\t"))
$f1.flush
end
def remove(a, ks)
a = a.dup
ks.each { |x| a.delete(x) }
return a
end
def add(l, ns)
ns2 = seq(ns.to_i(2), ns.length)[ns.length - 1].to_s(2)
d2 = d(ns2)
$t = 0 if ($t.nil?)
$t += 1
x = {'t' => $t, 'ns' => ns, 'd2' => d2, 'd2a' => (d2 - 0.5).abs, 'nw' => ns.length}
l << x
out(remove(x, ['ns']), {'d2' => 'axis x1y2 dt 3', 'd2a' => 'axis x1y2 lw 2 dt 3'}) if ($t % 4 == 0)
p(x) if ($t % 200 == 0)
end
def opt(ks)
add(l = [], '1')
5000.times \
{
l1 = order(l, ks)
i = l1[rand([l1.size, 20].min)]
x = l.delete_at(i)
ns = x['ns']
ns1 = ns.dup
ns1[0, 1] = '10'
ns2 = ns.dup
ns2[0, 1] = '11'
add(l, ns1)
add(l, ns2)
}
p(l)
end
ks = ['nw', 'd2a']
#ks = ['d2a']
opt(ks)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.