Created
May 28, 2013 23:44
-
-
Save tinomen/5666990 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<p>Using <a href="http://projecteuler.net/project/names.txt">names.txt</a> (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, | |
begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by | |
its alphabetical position in the list to obtain a name score. | |
</p> | |
<p>For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the | |
938th name in the list. So, COLIN would obtain a score of 938 x 53 = 49714. | |
</p> | |
<p>What is the total of all the name scores in the file?</p> |
aamax
commented
May 29, 2013
@hamiltop because the problem description tells you to :p
um, yeah. the problem calls for sorting the names
Or I can save a few characters with several more lines of monkey patching!
CODES = Hash[(?A..?Z).zip(1..26)]
class Hash
def to_proc
proc { |v| self[v]}
end
end
def name_score(name, pos)
name.chars.map(&CODES).reduce(&:+) * pos
end
require 'csv'
puts "Total: " +
CSV.readlines("names.txt").first.sort.
map.with_index{ |name, i| name_score(name, i+1)}.reduce(&:+).to_s
Seriously though, Ruby should have a default Hash#to_proc
.
I'm shooting for esoteric
require 'csv'
compile_options = RubyVM::InstructionSequence.compile_option.merge(:tailcall_optimization => true)
iseq = RubyVM::InstructionSequence.compile <<SRC, nil, nil, nil, compile_options
CODES = Hash[(?A..?Z).zip(1..26)]
def name_score(pos, name, total=0)
if name.empty?
pos * total
else
name_score pos, name[1..-1], total + CODES[name[0]]
end
end
def calc_total(names, pos=1, total=0)
if names.empty?
total
else
calc_total names[1..-1], pos + 1, total + name_score(pos, names[0])
end
end
puts calc_total(CSV.open("names.txt").readline.sort)
SRC
iseq.eval
@tinomen I missed the "multiply by its alphabet position". Makes sense.
You guys are all nuts. ...I miss you. :-) I need to get out to urug more.
Had I been there, here's my $0.02 of craziness to add to the pile: "proper" (IMO) monkeypatching and a nasty old C trick I used to use for converting letters to their decimal positions:
class Array
def sum
inject :+
end
end
class String
def letter_position
self.ord ^ 64
end
def score
each_char.map(&:letter_position).sum
end
def positional_score(position)
position * score
end
end
require 'csv'
puts CSV.readlines("names.txt").first.sort.map.
with_index(1) {|name, index| name.positional_score index }.sum
...srsly, I need to get out to urug more. :-)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment