Array#productを使って^ ^;
与えられた7桁の電話番号に対する、各数字に割り当てられたアルファベットでの全組み合わせ。
#!/usr/bin/env ruby
TEL_TABLE = {
0 => 0,
1 => 1,
2 => :abc,
3 => :def,
4 => :ghi,
5 => :jkl,
6 => :mno,
7 => :pqrs,
8 => :tuv,
9 => :wxyz
}
TABLE = TEL_TABLE.inject({}) { |h, (k, v)| h[k] = v.to_s.split(//); h }
def all_combinations(digits)
top, *remains = digits.map { |d| TABLE[d] }
top.product(*remains).map(&:join).sort
end
ARGF.lines do |line|
digits = line.scan(/\d/).map(&:to_i)
puts all_combinations(digits).join(',')
end
Enumerable#chunkでsetを分けてArray#combinationで。
与えられた複数の座標間の最短を求める。
#!/usr/bin/env ruby
def extract_data_set(lines)
lines.chunk { |line| line.scan(/\d+/).size==2 || nil }.map(&:last)
end
def parse_points(set)
set.map { |str| str.scan(/\d+/).map(&:to_i) }
end
def shortest_root(points)
dis = points.combination(2).map { |a, b| dd(a, b) }.min
dis > 10000 ? :INFINITY : round(dis)
end
def dd(a, b)
Math.sqrt( (a[0] - b[0])**2 + (a[1] - b[1])**2 )
end
def round(f, n=4)
(f*10**n).to_i.to_f/10**n
end
sets = extract_data_set(ARGF)
puts sets.map { |set| shortest_root parse_points(set) }