Fortran Implementation of Problem 22

View source code here on GitHub!

Includes

Problem Solution

integer Problem0022/p0022()
 1! Project Euler Problem 22
 2!
 3! Problem:
 4!
 5! Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
 6! containing over five-thousand first names, begin by sorting it into
 7! alphabetical order. Then working out the alphabetical value for each name,
 8! multiply this value by its alphabetical position in the list to obtain a name
 9! score.
10!
11! For example, when the list is sorted into alphabetical order, COLIN, which is
12! worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
13! obtain a score of 938 × 53 = 49714.
14!
15! What is the total of all the name scores in the file?
16
17module Problem0022
18    use constants
19    use utils
20    implicit none
21    contains
22    integer(i18t) function p0022() result(answer)
23        integer, parameter :: file_size = 2**15 + 2**14
24        integer, parameter :: name_count = 5163
25        integer, parameter :: longest_name = 11
26        character(len=DATA_MAX_NAME_SIZE), parameter :: file_name = "p0022_names.txt"
27        character(len=file_size) :: contents
28        character(len=longest_name), dimension(name_count) :: names
29        character(len=longest_name) :: temp
30        integer(i18t) :: score
31        integer :: ios, unit, i, j, k
32
33        i = 1
34        j = 1
35        k = 1
36        answer = 0
37        names = ''
38        unit = open_data_file(file_name)
39        do
40            read(unit, '(A)', IOSTAT=ios) contents
41            if (ios == -1) then
42                exit
43            elseif (ios /= 0) then
44                stop ERROR_FILE_READ_FAILED
45            end if
46        end do
47        close(unit)
48        do j = 1, len_trim(contents)
49            select case (contents(j:j))
50                case (',')
51                    i = i + 1
52                    k = 1
53                case ('"')
54                    cycle
55                case default
56                    names(i)(k:k) = contents(j:j)
57                    k = k + 1
58            end select
59        end do
60        close(unit)
61        do i = 1, size(names)
62            do j = 1, size(names) - i
63                if (names(j) > names(j + 1)) then
64                    temp = names(j)
65                    names(j) = names(j + 1)
66                    names(j + 1) = temp
67                end if
68            end do
69        end do
70        do i = 1, size(names)
71            score = 0
72            do j = 1, len_trim(names(i))
73                score = score + ichar(names(i)(j:j)) - ichar('A') + 1
74            end do
75            answer = answer + score * i
76        end do
77    end function p0022
78end module Problem0022

Tags: word-problem, sorting, file-io