// 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?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class ProjectEuler_022 {
public static void main(String[] args) {
// 파일에서 이름을 읽어옵니다.
String[] names = readNamesFromFile("src/ProjectEuler/022_Names.txt");
// 이름을 알파벳 순서로 정렬합니다.
Arrays.sort(names);
// 총 점수를 계산합니다.
long totalScore = calculateTotalScore(names);
// 결과를 출력합니다.
System.out.println("Total Score: " + totalScore);
}
// 파일에서 이름을 읽어와 배열로 반환하는 메서드
static String[] readNamesFromFile(String fileName){
try(BufferedReader br = new BufferedReader(new FileReader(fileName))){
String line = br.readLine();
// 큰따옴표 제거
line = line.replaceAll("\"", "");
return line.split(",");
} catch (IOException e){
e.printStackTrace();
return new String[0];
}
}
// 이름의 알파벳 값 계산하는 메서드
static int calculateAlphabetValue(String name) {
int alphabetValue = 0;
for (char c : name.toCharArray()) {
alphabetValue += c - 'A' + 1;
}
return alphabetValue;
}
// 모든 이름의 총 점수를 계산하는 메서드
static long calculateTotalScore(String[] names){
long totalScore = 0;
for (int i = 0; i < names.length; i++){
int alphabetValue = calculateAlphabetValue(names[i]);
int nameScore = alphabetValue * (i + 1);
totalScore += nameScore;
}
return totalScore;
}
}
긴 text file을 불러와서, 배열화 시킨 후,
text의 alphabet value와 배열 index를 연산하여 최종 합을 구하는 문제.
작업이 좀 필요할 뿐, 어려운 문제는 아니다.
'잡다한 코딩 > Project Euler (Java)' 카테고리의 다른 글
| (Java) Project Euler 024 - Lexicographic Permutations (0) | 2024.01.02 |
|---|---|
| (Java) Project Euler 023 - Non-Abundant Numbers (0) | 2024.01.01 |
| (Java) Project Euler 021 - Amicable Numbers (0) | 2023.12.30 |
| (Java) Project Euler 020 - Factorial Digit Sum (0) | 2023.12.29 |
| (Java) Project Euler 019 - Counting Sundays (0) | 2023.12.28 |