본문 바로가기

오일러프로젝트

[오일러프로젝트] 42번문제


n
번째 삼각수는 tn = ½ n (n + 1) 이라는 식으로 구할 수 있는데, 처음 10개는 아래와 같습니다.

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

어떤 영어 단어에 대해서, 각 철자의 알파벳 순서(A=1, B=2, ..., Z=26)를 모두 더한 값을 '단어값'이라 부르기로 합니다. 예를 들어 'SKY'의 단어값은 19 + 11 + 25 = 55가 되는데, 이것은 우연히도 t10과 같습니다.
이렇게 어떤 단어의 단어값이 삼각수일 경우에는 이 단어를 '삼각단어'라 부르기로 합니다.

약 16KB의 텍스트 파일 words.txt에는 2000개 정도의 영어 단어가 수록되어 있습니다. 이 중에서 삼각단어는 모두 몇 개입니까?


회사에서 점심먹고 잠시..파이썬으로만 풀었다..

삼각수 공식에 의해서 단어점수의 값을 X라고 하면
2X = n^2 + n이 된다.
n의 범위를 정해야 하는데 sqrt(2X)의 값을 시작점으로 잡으면 적당해보이고
n^2 + n이 2X를 넘으면 삼각수가 아닌 것으로 판별한다.

일단 파이썬만 풀었고..나머지는 이따 집에서..ㅋ


 

Python
sampleFile=open("euler_42_words.txt", "r")
names=sampleFile.readlines()
namesStr=names[0]
namesStr=namesStr.rstrip("\n")
#print (namesStr.replace("\"","").split(","))
nameList = namesStr.replace("\"","").split(",")
#Euler 22
alphaList = [chr(c) for c in range(ord('A'), ord('Z')+1)]
def getNameScore(name):
sum=0
for c in name:
sum=sum+alphaList.index(c)+1
#print("c={0}, score={1}, namescore={2}".format(c, alphaList.index(c)+1, sum))
return sum
import math
def isTriangeNumber(n):
temp_n = n * 2
start_num = int(math.sqrt(temp_n)) - 1
while True:
s = start_num**2 + start_num
if temp_n == s:
return True
if temp_n < s:
return False
start_num += 1
cnt_of_result = 0
for name in nameList:
name_score = getNameScore(name)
if isTriangeNumber(name_score):
cnt_of_result += 1
print (cnt_of_result)
view raw 42.py hosted with ❤ by GitHub

Ruby
def getNameScore(name)
alphaList=Array.new
('A'..'Z').each {|c| alphaList.push(c)}
nameScore=0
name.each_char do
|c|
nameScore = nameScore + alphaList.index(c) + 1
#puts "c=#{c}, score=#{alphaList.index(c)+1}, namescore=#{sum}"
end
return nameScore
end
namesStr=""
File.open("euler_42_words.txt") do |file|
while line = file.gets
namesStr=line
end
end
namesStr = namesStr.gsub(/\"/, "")
namesList = namesStr.split(",")
def isTriangelNumber(n)
temp_n = n * 2
start_num = (Math.sqrt(temp_n) - 1).to_i
while (true)
s = start_num**2 + start_num
if temp_n == s
return true
end
if temp_n < s
return false
end
start_num += 1
end
end
cnt_of_result = 0
namesList.each do |name|
name_score = getNameScore(name)
if isTriangelNumber(name_score)
cnt_of_result += 1
end
end
puts cnt_of_result
view raw 42.rb hosted with ❤ by GitHub

Perl
use strict;
use warnings;
use Math::Complex;
use List::MoreUtils qw(first_index);
open PRB, "euler_42_words.txt";
my $names_str;
while(defined(my $line=)) {
chomp($line);
$names_str = $line;
}
$names_str =~ s/\"//g;
my @names_list=split /,/, $names_str;
my @alpha_list=('A'..'Z');
sub getNameScore {
my ($name) = @_;
my $char_score_sum = 0;
foreach my $byte (split //, $name) {
my $char_score = first_index {$_ eq $byte} @alpha_list;
#print "byte : $byte , char_score : $char_score \n";
$char_score_sum = $char_score_sum + $char_score + 1;
}
return $char_score_sum;
}
sub isTriangleNumber {
my ($n) = @_;
my $temp_n = $n * 2;
my $start_num = int(sqrt($temp_n)) - 1;
while(1) {
my $s = $start_num**2 + $start_num;
if ($temp_n == $s) {
return 1;
}
if ($temp_n < $s) {
return 0;
}
$start_num += 1;
}
}
my $cnt_of_result = 0;
foreach my $name (@names_list) {
my $name_score = getNameScore($name);
#print "$name_score \n";
if (isTriangleNumber($name_score)) {
$cnt_of_result += 1;
}
}
print "$cnt_of_result";
view raw 42.pl hosted with ❤ by GitHub

근데 ruby에서 alphaList를 getNameScore 밖으로 빼면 인식을 못 한다. 이유를 모르겠다 --;;