Skip to content

Instantly share code, notes, and snippets.

@kindkid
Created March 14, 2012 06:13
Show Gist options
  • Save kindkid/2034543 to your computer and use it in GitHub Desktop.
Save kindkid/2034543 to your computer and use it in GitHub Desktop.
def extr(a,x)
q,r,s,t = a
((q.to_r * x + r.to_r) / (s.to_r * x + t.to_r))
end
def comp(a,b)
q,r,s,t = a
u,v,w,x = b
[q*u+r*w, q*v+r*x, s*u+t*w, s*v+t*x]
end
def stream(nxt, safe, prod, cons, init, input)
Enumerator.new do |yielder|
memo = init
next_memo = nxt.call(memo)
input.each do |x|
while safe.call(memo, next_memo)
yielder << next_memo
memo = prod.call(memo, next_memo)
next_memo = nxt.call(memo)
end
memo = cons.call(memo,x)
next_memo = nxt.call(memo)
end
end
end
def process(nxt, prod, cons, init, input)
Enumerator.new do |yielder|
memo = init
input.each do |x|
v = cons.call(memo,x)
y = nxt.call(v)
yielder << y
memo = prod.call(v,y)
end
end
end
pi = stream(
->(z){extr(z,3).to_i}, #nxt
->(z,n){n == extr(z,4).to_i}, #safe
->(z,n){comp([10,-10*n,0,1], z)}, #prod
->(z,z1){comp(z,z1)}, #cons
[1,0,0,1], #init
Enumerator.new{|y| i=0; loop{i+=1; y << [i, 4*i+2, 0, 2*i+1]}} # input
)
piL = stream(
->(a) do #nxt
z,i = a
q,r,s,t = z
x = 2*i-1
((q*x+r) / (s*x+t)).to_i
end,
->(a,n) do #safe
z,i = a
q,r,s,t = z
x = 5*i-2
n == ((q*x+2*r) / (s*x+2*t)).to_i
end,
->(a,n) do #prod
z,i = a
[comp([10,-10*n,0,1],z), i]
end,
->(a,z1) do #cons
z,i = a
[comp(z,z1), i+1]
end,
[[0,4,1,0],1], #init
Enumerator.new{|y| k=0; loop{k+=1; y << [2*k-1, k*k, 1, 0]}} #input
)
# This one doesn't return correct results. But as far as I can see, my port is faithful. Did I miss something?
piG = stream(
->(a) do #nxt
z,i = a
q,r,s,t = z
x = 27*i+15
((q*x+5*r) / (s*x+5*t)).to_i
end,
->(a,n) do #safe
z,i = a
q,r,s,t = z
x = 675*i-216
n == ((q*x+125*r) / (s*x+125*t)).to_i
end,
->(a,n) do #prod
z,i = a
[comp([10,-10*n,0,1],z),i]
end,
->(a,z1) do #cons
z,i = a
[comp(z,z1),i+1]
end,
[[1,0,0,1],1], #init
Enumerator.new{|y| k=0; loop{k+=1; j = 3*(3*k+1)*(3*k+2); y << [k*(2*k-1), j*(5*k-2), 0, j]}} #input
)
piG2 = process(
->(a) do #nxt
z,i = a
q,r,s,t = z
x = 27*i+15
((q*x+5*r) / (s*x+5*t)).to_i
end,
->(a,n) do #prod
z,i = a
[comp([10,-10*n,0,1],z),i]
end,
->(a,z1) do #cons
z,i = a
[comp(z,z1),i+1]
end,
[[1,0,0,1],1], #init
Enumerator.new{|y| k=0; loop{k+=1; j = 3*(3*k+1)*(3*k+2); y << [k*(2*k-1), j*(5*k-2), 0, j]}} #input
)
pi.take(100)
piL.take(100)
#piG.take(100)
piG2.take(100)
piG2.each{|d| $stdout.print d; $stdout.flush}
@marksim
Copy link

marksim commented Mar 14, 2012

Did you do this yourself or did you find it?

@kindkid
Copy link
Author

kindkid commented Mar 14, 2012

I ported the code in the link in the description.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment