samedi 27 juin 2015

Project Euler 022 'Names scores'

My solution to Project Euler 022 is running incorrectly and I can't see why:

$scores = {
    "A" => 1,
    "B" => 2,
    "C" => 3,
    ...
    "Z" => 26
}

def alphabetScore(name)
    nameScore = 0
    array = name.split(//)
    array.each { |n| nameScore += $scores[n] }
    return nameScore
end

file = File.read("p022_names.txt").split(",")
file.map! { |n| n.tr('^A-Za-z0-9','') }

totalScore = 0

file.each do |findScore|
    nameScore = alphabetScore(findScore)
    totalScore += nameScore
end

p totalScore
# p file # to check that 'file' is indeed an array of strings

Testing individual names e.g p alphabetScore("AGNES") returns the correct value but when totaling the score of every name I get 324536, which is incorrect (the correct answer is 871198282). My only guess as to why this isn't working is that one of the names (presumably the one which would cause totalScore to exceed 324536) is broken in some way.

Aucun commentaire:

Enregistrer un commentaire