Skip to content

Instantly share code, notes, and snippets.

@tinomen
Created May 28, 2013 23:44
Show Gist options
  • Save tinomen/5666990 to your computer and use it in GitHub Desktop.
Save tinomen/5666990 to your computer and use it in GitHub Desktop.
<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>
@dbrady
Copy link

dbrady commented Jun 3, 2013

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