From: "Ralf Müller" Date: 2004-06-17T16:48:21+09:00 Subject: Re: Possibly improvable code 11111111111111111111111111111111111111111111111111111111111111 ram@lilith:~/src/ruby$cat rec_pi.rb n = STDIN.gets tot = 0 9.times do |i| c = n.count(i.to_s) tot += c puts "#{i} #{c}" end puts "9 #{n.size - tot}" ram@lilith:~/src/ruby$time ruby rec_pi.rb < pi.out 0 16095 1 16107 2 15965 3 15915 4 15967 5 16169 6 15934 7 16091 8 15999 9 15790 real 0m0.045s user 0m0.040s sys 0m0.000s 22222222222222222222222222222222222222222222222222222222222222222 ram@lilith:~/src/ruby$cat rec_pi_a.rb c={}; $_.each_byte{|b| c[b]||=0; c[b]+=1 }; c.sort.each {|k,v| puts "#{k - ?0} #{v}"} ram@lilith:~/src/ruby$time ruby -n rec_pi_a.rb < pi.out 0 16095 1 16107 2 15965 3 15915 4 15967 5 16169 6 15934 7 16091 8 15999 9 15790 real 0m0.260s user 0m0.240s sys 0m0.010s 3333333333333333333333333333333333333333333333333333333333333333333 ram@lilith:~/src/ruby$cat rec_pi_b.rb num = STDIN.gets; a = Array.new(255,0); num.each_byte {|i| a[i] += 1}; (?0..?9).each {|i| print "#{[i].pack("c")} #{a[i]}\n"}; ram@lilith:~/src/ruby$time ruby rec_pi_b.rb < pi.out 0 16095 1 16107 2 15965 3 15915 4 15967 5 16169 6 15934 7 16091 8 15999 9 15790 real 0m0.194s user 0m0.160s sys 0m0.010s #################################################################### The main difference seems to be using "count" instead of "each_byte". But why is it 5-6x faster to "count" 9.times than "each_byte" only once? Or did i ignore anything? ralf (-,-)Zzz