Project Euler in PL/SQL: Problem 22

  • by

The difficulty level gets ramped up here in Project Euler’s next problem.

Problem 22:

Name Scores

Using names.txt, 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.

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 × 53 = 49714.

What is the total of all the name scores in the file?

I started by loading the file into a simple, one-column table called names. From there, I created a sub-function to calculate the value of the name and put it all together with a cursor that loops through the names table.

DECLARE
    answer NUMBER := 0;
    i INTEGER := 0;

    CURSOR name_cur
    IS
        SELECT rownum as num, name
        FROM names
        order by name;

    FUNCTION get_name_sum(name_in VARCHAR2) return NUMBER
    IS
        sumz NUMBER := 0;
    BEGIN
        for i IN 1..length(name_in) loop
            sumz := sumz + ascii(substr(name_in,i,1))-64;
        end loop;
        
        return sumz;
    END;
BEGIN

    for name_rec in name_cur loop
     i := i+1;
     answer := answer + (get_name_sum(name_rec.name) * i);
    end loop;
    
    dbms_output.put_line(answer);
END;

--output 871198282

Questions or comments? Feel free to leave them below or reach out to me on Twitter!

Leave a Reply

Your email address will not be published. Required fields are marked *