Skip to content

Instantly share code, notes, and snippets.

@vznvzn
Created October 24, 2018 02:59
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/0277ab97a5a7a3fec49c6fb0547ce5d1 to your computer and use it in GitHub Desktop.
Save vznvzn/0277ab97a5a7a3fec49c6fb0547ce5d1 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).to_i - 1)).map { a.delete_at(rand(a.size)) }.each { |x| s[x, 1] = '1' }
return ('1' + s)
end
def d(s)
c = s.split('').select { |x| x == '1' }.size
d = c.to_f / s.length
return d
end
def len01(ns)
nl = ns.length
l1 = ns.split(/0+/).map { |x| x.length }
l2 = ns.split(/1+/)[1..-1]
l2 = [''] if (l2.nil?)
l0 = l2.map { |x| x.length }
return l0, l1
end
def mx01(ns)
len01(ns).flatten.max
end
def crossover(n)
n1 = n
l1 = [d(n1.to_s(2)) - 0.5]
i = 0
while (n != 1)
n = f2(n)
l1 << d(n.to_s(2)) - 0.5
l1.shift if (l1.size == 3)
break if (l1[0] * l1[1] < 0)
i += 1
end
return i
end
def sample(c)
$n = 0 if ($n.nil?)
$stderr.puts($n += 1)
l = []
c.times \
{
|i|
d = i.to_f / (c - 1)
ns = dense(c, d)
ns2 = f2(n = ns.to_i(2)).to_s(2)
l << {'d' => d,
'd2' => d(ns2),
'mx1' => mx01(ns),
'mx2' => mx01(ns2),
'co' => crossover(n)}
}
return l
end
def sum(l)
t = 0.0
l.each { |x| t += x }
return t
end
def avg(l)
return nil if (l.empty?)
return sum(l) / l.size
end
def avgs(l)
ks = l[0][0].keys
l1 = []
l[0].size.times \
{
|i|
l1[i] = Hash[[ks, ks.map { |k| avg(l.map { |x| x[i][k] }) }].transpose]
}
return l1
end
l = avgs((1..10).map { sample(1000) })
f = File.open('gnuplot.cmd', 'w')
f.puts('$dat << eof')
f.puts(l[0].keys.join("\t"))
l.each { |x| f.puts(x.values.join("\t")) }
f.puts('eof')
f.puts('set key top center; set ytics nomirror; set y2tics; plot \\')
a = {'d2' => 'axes x1y2'}
(l[0].keys - ['d']).each { |x| f.puts("$dat using (column('d')):(column('#{x}')) title '#{x}' with line #{a.fetch(x, '')},\\") }
f.puts
f.puts('pause -1')
f.puts("plot $dat using (column('d')):(log(column('mx1'))) title 'log mx1' with line,$dat using (column('d')):(log(column('co'))) title 'log co' with line")
f.puts('pause -1')
f.puts("set key top left; unset y2tics; plot 0 lw 2,$dat using (column('d')):(column('mx2')-column('mx1')) title 'mx2 - mx1' with line")
f.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment