Project Euler Problem 22

Another solution, this one is of note because it involves reading from a file and involved the discovery of the “each_with_index” method. This is also the first problem where I learned, the hard way, to “read the sodding question properly” 🙂

def problem22
  names_array = []
  File.open("names.txt").each_line do 
    |s| names_array = s.scan(/\w+/).sort
  end
  
  score = 0

  names_array.each_with_index do |name, index| 
    score += name.alphabet_score * (index+1)
  end
  
  puts score
  
end

module StringHelper

  def alphabet_score
    total = 0
    self.each_byte { |char|
      total += (char - 64)
    }
    total
  end

end


class String 
  include StringHelper
end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s