Entries from 2007-01-01 to 1 year

Code Golf - Grid Computing

Code Golf in Dec 2007 _=Array.new(11,0) $<.map{|$_|r=0 (0..9).map{|i|v=$_[3*i..3*i+1].to_i;_[i]+=v;r+=v} _[10]=r if r>_[10]} p _.max size: 116 entry date: 12/24/2007

matlab (octave) "hist" idiom

matlab (and octave) has histogram and 2D data indexing: data = [1, 2, 3, 4; 2, 4, 6, 8; 3, 6, 9, 12; 5, 10, 15, 20]; dmin = min(data(:)) dmax = max(data(:)) his = hist(data(:), (dmin:dmax)); num = sum(his) mean = sum(his .* dmin:dmax) / nu…

C "strtok" idiom in Ruby

In C, "strtok" destructively change a string into a series of strings: char str[] = "begin space tab\t\tcarrige-return\ncomma, period. end"; char delim[] = " \t\n,."; for (char* p = strtok(str,delim); p && printf("%s\n", p); p = strtok(0, …

File Dependency graph and RGL

RGL provides easy manipulation of graph: require 'rgl/adjacency' g = RGL::DirectedAdjacencyGraph.new IO.foreach(ARGV.shift) {|line| if line =~ /\s*([^\"]+)[\"\s]*->[\"\s]*([^\"\[\;]+)/ g.add_edge $1, $2 end } p "vertices: #{g.num_vertices}…

File Dependency in "Graphviz dot"

The visualization tool "dot" turns file dependency in a diagram. Given root file(s) , a ruby script below visits dependency files to put directed edges in a "dot" form: out = Array.new while path = ARGV.shift File::open(path) {|file| while…

"irb" for Windows Me

My old Windows Me does not like the installed "irb.bat" script. Work around is to copy it to "irb" and edit to remove several top and bottom lines as below: 1,4d0 < @echo off < goto endofruby < #!/bin/ruby < # 24,26d19 < __END__ < :endofru…

ColdeGolf - Tower of Hanoi

Size: 262 (v4) submitted on 4/14/2007 def f(d)(0..2).find{|i|$a[i]&&$a[i][d.to_s]}end def m d,i,j k=(0..2).find{|k|k!=i&&k!=j} m(d-1,i,k)if d>1 puts"#{d} to #{"ABC"[j,1]}" m(d-1,k,j)if d>1 end $a=[];n=0 ($a<

Rinda Primer

[1] Launch a Rinda TupleSpace require 'rinda/tuplespace' DRb.start_service 'druby://:12345', Rinda::TupleSpace.new p DRb.uri DRb.thread.join Output provides URI of which machine/port the TupleSpace communicates with.[2] Start a server - in…

GLAT Google Lab Aptitude Test

GLAT Question 17: "Consider a function which, for a given whole number n, returns the number of ones required when writing out all numbers between 0 and n. For example, f(13)=6. Notice that f(1)=1. What is the next largest n such that f(n)…

'Perplexing Puzzlers' for April Fool's Day

NPR Weekend Edition Sunday, April 1, 2007 Puzzle master Will Shortz quizzes:Take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two other U.S. States. What states are these? A Ruby solu…

Matz' TkLife Resurrected

Original: tklifegame.rb in "O-O Script Language Ruby," by Matz, ASCII 1999 Modifications to run on ruby 1.8: [1] hash clean up (ruby 1.8), "hash[key] = nil" --> "hash.delete key" [2] reduced screen size, 480x480 (tile size 6) --> 400x400 (…

Machine Epsilon - Really?

Function zeros do not necessarily fall on the discretely desirable points. For example, the Colinear checking function shows a pattern of zeros in yellow, positives in red, and negatives in blue. require 'tk' root = TkRoot.new $canvas = Tk…

Quaternary Tree

# "Spatial Tessellations: Concepts and Applications of Voronoi Diagrams," 2nd Ed. # A. Okabe, B. Boots, K, Sugihara, S.N. Chiu, Wiley 2000 # p.245 Algorithm 4.3.1, Ch4 Algorithms for Computing Voronoi Diagram # Given randomly generated 2D …

Euler's Totient Function

Euler's phi function: number of coprimes of an integer m phi(m) = m*Prod(1-1/p) [where p: prime number and p|m] def phi(m) r = (2..m) primes = r.inject(r){|p, i| p.select{|n| n==i || n%i!=0}} primes.inject(m){|e, p| e%p==0 ? e/p*(p-1) : e}…

Symbol Golf - Musical Score 2

Thanks to 記号ゴルファーΩ, code I posted on Musical Score reduces its size to 234: _='' $<.map{|$_|_<<chomp} k=a.size/12 (0...k).map{|i|$_=' '*12 (0..11).map{|j|$_[j]=_[k*j+i]} ($-=(~/\|/);$><<"FEDCBAGFE"[$_.index('o')-3,1])if i%4==0 $><<(~/\\{3}/?"/32":~/\\{2}/?"/16":~/\\{1}/?"/8":$-?"/4":'')+' 'if i%4==1…</chomp}>

Code Golf - Musical Score

Code Golf http://codegolf.com/musical-score a='' a=a+chomp while gets k=a.size/12 b=' '*12*k for i in 0...k for j in 0...12 b[12*i+j]=a[k*j+i] end $_=b[12*i...12*(i+1)] if i%4==0 print " FEDCBAGFE"[$_.index('o'),1] f=(~/\|/) end if i%4==1 …

Carmichael Numbers

A Carmichael number is an odd composite number n which satisfies Fermat's little theorem a^(n-1)-1=0 (mod n) for every choice of a satisfying (a,n)==1 (i.e., a and n are relatively prime) with 1 r = (2..101) primes = r.inject(r){|p, i| p.s…

Maximum Distance Bisector

about 500 lines of tk codes for Bisector CRUD #!/usr/bin/env ruby require 'tk' PntRad = 3 # Point radius of TkcOval ScrHgt = 600 # Screen Hight class Geom Infinity = 10*ScrHgt @@canvas = Hash.new attr_accessor :g def initialize @g = nil en…

Power Set

class Array def power inject([[]]){|ps, e| ps + ps.map{|s| s + [e]}} end end p [1,2,3].power [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Counting Path of Robot Motion

Given a 8 by 8 grid and a robot that moves from the left bottom corner (0, 0) to the right top corner (7, 7) by stepping either right (East) or upward (North) in total 14 steps, find all possible paths.A sample solution: def C(i, j) if i =…

tk Colors

require 'tk' root = TkRoot.new $canvas = TkCanvas.new(root) { width 360 height 60 } $canvas.pack colors = ['00', '33', '66', '99', 'cc', 'ff'] d = 10 for i in 0..5 for j in 0..5 for k in 0..5 c = '#' + colors[i] + colors[j] + colors[k] x =…

Code Golf - Roman Numerals

gets chomp h=Hash['I',1,'V',5,'X',10,'L',50,'C',100,'D',500,'M',1000] s=u=0 split(//).each{|r|v=h[r] s+=u

Hamming Numbers

module Enumerable def bop(op, m) map {|i| m.send(op, i)} end end class Array def | other return self + other if empty? or other.empty? case first <=> other.first when -1, 0; e = shift when 0, 1; e = other.shift end return (self | other).un…

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…