Entries from 2007-01-01 to 1 month

Constrained Cartesian Product

def product_with(base, *rest, &constraint) return base.map{|a|a} if rest.empty? rest = product_with(*rest, &constraint) base.inject([]){|rs, a| rest.inject(rs){|rs, b| if constraint.call a, b.kind_of?(Array)? b[0]: b rs<<[a, *b] else rs en…

Pascal Triangle Numbers

Using the list shifting and zipping together def ptn n (1..n).inject([1])do |s,k| yield s (s+[0]).zip([0]+s).map{|e| e[0]+e[1]} end end ptn 10, &proc{|s| puts s.join(" ")} 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21…

Cartesian product of lists

def allpairs xs, ys result = [] xs.each {|x| ys.each {|y| result << yield(x, y) }} result end p allpairs(['h','o','t'], ['d','o','g']){|x,y| x + y} p allpairs([1, 2, 3, 5], [7, 11, 13]){|x,y| x * y} ["hd", "ho", "hg", "od", "oo", "og", "td…

Collatz Numbers

# Collatz numbers def collatz(n) while n > 1 yield n if n%2 == 0 then n = n/2 else n = 3*n + 1 end end yield 1 end (1..128).each {|n| count = 0 collatz(n) {|i| count += 1} printf "#{n}:#{count} " } Note the shortest periods at n = 2^k and …

Knuth's Monotonic Squares

non-decreasing squares have infinite patterns # Knuth's Monotonic Squares # n and n^2 have non-decreasing digits def digit(n, i) (n/10**i)%10 end def nondec?(n) i = n.to_s.length - 1 i == 0 || digit(n, i) <= digit(n, i-1) && nondec?(n%10**…

Benchmark - Twin Primes

lazy # Twin primes benchmark ps = [2] n = 3 loop do if !ps.find{|p| n%p == 0} p [ps[-1], n] if ps[-1]+2 == n ps << n end n += 2 end benchmark require 'benchmark' max = 10000 Benchmark.bm do |x| x.report do r = (2..max*2) primes = r.inject(…

Toys - Prime Number Neighbors

# Prime number neighbors r = (2...100) # Nick Chapman 10/10/2006 primes = r.inject(r){|p, i| p.select{|n| n==i || n%i!=0}} twin_primes = primes.inject([]) do |t, n| n+2 == primes[primes.index(n)+1] ? t<<[n,n+2] : t end triplet_primes = pri…

Code Golf - ASCII Art

a=(' '*80+"\n")*40 (x,y,c=split;a[y.to_i*81+x.to_i]=c.to_i)while gets a.each{|$_|puts$~if~/.*\S/} See Code Golf