SonOfLilit
4/29/2007 1:42:00 PM
Sorry for the triple post, but I've read the article and propose a
completely different approach to the problem you present (also in a
comment there with typos):
h = {}
open('input.txt').each_line{|l| h[l[0..0]] += l[2..-1].split('
').inject(0) {|c,x| c+=x.to_i; c}}}
p h.map{|k,v| {k => v}} # to turn {"a" => 80, "b" => 60} into [{"a" =>
80}, {b => 60}]
# which is a pretty weird data structure IMHO, but I'll play by your rules
Let's look at your code:
#############
input = Set.new open('input.txt').readlines.map{|e| e.chomp}
groups = input.divide {|x,y| x.map[0][0] == y.map[0][0] } # what's map for?
#build the array of hashes
p groups.map.inject([]) {|a,g| # what's map for?
#build the hashes for the number sequences with same letters
a << g.map.inject(Hash.new(0)) {|h,v|
#for every sequence, sum the numbers it contains
h[v[0..0]] += v[2..-1].split(' ').inject(0) {|c,x|
c+=x.to_i; c}; h
}; a
}
#############
divide() seems redundant in your code. You both 1) divide(); and 2)
implement divide on your own; in the same code. You do four passes on
the lines (and maybe more in the map() calls, I can't figure those
out), in one of them passing twice on each line's content, forcing the
data to stay all in memory the whole time.
My code, which isn't debugged but shows my idea, passes once on the
lines, and in that pass twice on each line's contents. It doesn't keep
the data in memory.
BTW I couldn't understand the use of map() without a block. Mind explaining?
Aur Saraf