2008-04-01から1日間の記事一覧
19:30ごろ帰りました。
require 'enumerator' module Enumerable def sum inject(0) {|a, n| a + n } end end class Integer def to_digit_ary to_s.enum_for(:each_byte).map {|c| c - ?0 } end end def f(n, m) (n ** m).to_digit_ary.sum end p f(2, 15) p f(2, 1000)
def collatz(cache, n) len = 1 while n != 1 if n < cache.size and cache[n] len += cache[n] break end d, r = n.divmod(2) n = r.zero? ? d : 3 * n + 1 len += 1 end len end def f(upper) max_n, max_len = 0, 0 cache = Array.new(upper + 1) (1 .. u…
module Enumerable def sum inject(0) {|a, n| a + n } end end class String def lines(limit = 0) split(/\n/, limit) end end src = <
require 'enumerator' module Enumerable def product inject(1) {|a, n| a * n } end end class String def lines(limit = 0) split(/\n/, limit) end def words scan(/\w+/) end end def product_max(data) data.map do |line| line.enum_cons(4).map {|a|…