-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Problem22.java
85 lines (68 loc) · 2.09 KB
/
Problem22.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* File: Problem22.java
* ----------------------
* Finds the point value of a list of names.
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
public class Problem22 {
static HashMap<Character, Integer> values = new HashMap<>();
public static String fileName = "Problem22Text.txt";
static ArrayList<String> names = new ArrayList<>();
public static void main(String[] args) {
// to calculate runtime of different methods
double startTime = System.nanoTime();
// Text file is all in uppercase
String temp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char alphabet[] = temp.toCharArray();
int number = 1;
for (char letter : alphabet) {
values.put(letter, number);
number++;
}
long totalScore = 0;
int rank = 1;
try {
organizeNames();
Collections.sort(names); // Alphabetically orders the names
for (String name : names) {
totalScore += getNameValue(name, rank);
rank++;
}
} catch (Exception ex) {
System.out.println("There was an error: " + ex);
}
System.out.println(totalScore);
double duration = (System.nanoTime() - startTime) / 1000000000;
System.out.println(duration + " seconds");
}
public static long getNameValue(String name, int rank) {
long score = 0;
char characters[] = name.toCharArray();
for (char letter : characters) {
score += values.get(letter);
}
return (score * rank);
}
// Removes non-name characters
public static void organizeNames() {
try {
BufferedReader scanner = new BufferedReader(new FileReader(fileName));
String line = scanner.readLine();
// Splits based on where the comma separates the names
String[] namesList = line.split(",");
for (String name : namesList) {
// Removes double quotes
name = name.substring(1, name.length() - 1);
names.add(name);
}
scanner.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}