Skip to content

Instantly share code, notes, and snippets.

@vznvzn
Created May 6, 2016 02:54
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/6114751ff6feccc0de462516d93119af to your computer and use it in GitHub Desktop.
Save vznvzn/6114751ff6feccc0de462516d93119af to your computer and use it in GitHub Desktop.
def rand1()
return rand() * [-1, 1][rand(2)]
end
def d(s)
c = s.split('').select { |x| x == '1' }.size
d = c.to_f / s.length
return d, (0.5 - d), (0.5 - d).abs, s.length, c, s.size - c
end
def d2(s)
return [0, 0, 0] if (s.length == 0)
d(s)[0..2]
end
def stat(l)
return 0, 0 if (l.empty?)
t = t2 = 0
l.each \
{
|x|
t += x
t2 += x ** 2
}
c = l.size
a = t.to_f / c
z = t2.to_f / c - a ** 2
sd = Math.sqrt(z < 0 ? 0 : z)
return a, sd
end
def metrics(n, j)
s = n.to_s(2)
d1, d2, d3, w, c1, c0 = d(s)
m = s.length / 2
da = d2(s[0...m])
db = d2(s[m..-1])
m1 = w ** 2
m2 = w ** 0.5
asd1 = stat(s.split(/0+/).map { |x| x.length })
asd0 = stat(s.split(/1+/).map { |x| x.length })
l2 = [m1, m2, d1, d2, d3, w, c0, c1]
l2.concat(asd1 + asd0 + da + db)
l2.push(j, j ** 2, j ** 0.5, 1.0, j.to_s(2).length)
return l2
end
def weight(n, l, j)
l2 = metrics(n, j)
t = 0.0
l.each_with_index { |x, i| t += x * l2[i] }
raise(l2.join(' ')) if (t.nan?)
return t
end
def seq(z)
n = z['n']
l = [n]
while (n != 1)
l << n
n = f1(n)
end
return l
end
def f1(n)
n = (n * 3 + 1) / 2 while (n % 2 == 1)
n /= 2 while (n % 2 == 0)
return n
end
def stat2(l, z)
c = 0
m = l[0]
mx = j = 0
l2 = []
(1...l.size).each \
{
|i|
c += 1 if (l[i] < l[i - 1])
if (l[i] < m) then
l2 << i - j
m, j = [l[i], i]
end
mx = [mx, i - j].max
}
r = c.to_f / (l.size + 1)
a, sd = stat(l2)
return {'r' => r, 'mx' => mx, 'c' => l2.size,
'd' => l2.size.to_f / (l.size + 1), 'a' => a, 'sd' => sd,
}.merge(z)
end
def weight2(i, w)
x = Kernel.eval($l[i])
l = seq(x)
j = 0
l2 = l.map { |n| weight(n, w, j += 1) }
return x, l2, l
end
def randw()
(1..23).map { rand1() }
end
def linear(c)
w = randw()
y = 0
(0..99).each \
{
|i|
x, l2 = weight2(i, w)
puts(([i, c] + stat2(l2, x).to_a).flatten.join("\t"))
$stdout.flush
}
puts
$stderr.puts(c)
end
def test()
c = j = 0
(35..64).each \
{
|i|
w = randw() # [0..-6] #
x, l2, l = weight2(i, w)
[l, l2].transpose.each \
{
|x|
puts(([j, c] + x).join("\t"))
j += 1
}
puts
c += 1
}
end
# $stderr.puts(metrics(0, 0).size); exit
$l = File.open('db.txt').readlines
# test(); exit
20.times { |c| linear(c); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment