[Golang] Names scores - Problem 22 - Project Euler


Problem: [1]

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

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?

Solution:

871198282
22.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"sort"
	"strings"
)

func GetFileContentFromUrl() string {
	resp, err := http.Get("https://projecteuler.net/project/resources/p022_names.txt")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}

	return string(b)
}

func GetAllSortedNames() []string {
	raw := GetFileContentFromUrl()
	raw = raw[1 : len(raw)-1]
	names := strings.Split(raw, `","`)
	sort.Strings(names)
	return names
}

func main() {
	names := GetAllSortedNames()
	totalscores := 0
	for i, name := range names {
		pos := i + 1

		sum := 0
		for i := 0; i < len(name); i++ {
			sum += int(name[i] - byte('A') + 1)
		}

		score := sum * pos
		totalscores += score
	}
	fmt.Println(totalscores)
}

Test on:

  • Ubuntu 18.04, Go 1.11.1

References:

[1]Names scores - Problem 22 - Project Euler
[2][Golang] Sort Words Alphabetically
[3][Golang] Read Lines From URL