我目前正在处理 Project Euler problem 22它有以下挑战:
使用 names.txt(右键单击并“将链接/目标另存为...”),这是一个包含五千多个名字的 46K 文本文件,首先按字母顺序对其进行排序。然后计算出每个姓名的字母顺序值,将该值乘以其在列表中的字母顺序位置以获得姓名分数。
例如,当列表按字母顺序排序时,值 3 + 15 + 12 + 9 + 14 = 53 的 COLIN 是列表中的第 938 个名称。因此,COLIN 将获得 938 × 53 = 49714 的分数。
文件中所有名称分数的总和是多少?
该文件可以使用上面的链接下载。我写了下面的代码来解决这个问题:
rm(list=ls())
library(splitstackshape)
#read in data from http://projecteuler.net/problem=22
names=sort(t(read.table("names.txt",sep=",")))
#letters to numbers conversion vectors
from=LETTERS[seq(1,26)]
to=as.character(seq(1,26))
#function to replace all letters with corresponding numbers
gsub2 = function(pattern, replacement, x, ...){
for(i in 1:length(pattern))
x = gsub(pattern[i],paste(replacement[i]," ",sep=""), x, ...)
x
}
#create df, run function, create row number var for later calculation
df=data.frame(names=names)
df$name.num = gsub2(from,to,df$names)
df$rownum=seq(1,nrow(df))
#split letter values, add across rows, multiply by row number to get name score and sum
df=concat.split(df,"name.num"," ")
df$name.sum=rowSums(df[,4:15],na.rm=TRUE)
df$name.score=df$name.sum*df$rownum
print(sum(df$name.score,na.rm=TRUE))
我的结果似乎是 158,055(我得到
871040227
应该是 871198282
)。我已经抽查了其中的部分内容,似乎名称列表排序正确,并且名称分数编译正确(例如,我也得到了 COLIN=49174
)。我还在 SO 上阅读了其他线程来解决这个问题,但它们主要是在 Python 中,而且问题似乎与我的不同。我的怀疑是 names.txt
文件不知何故没有被正确读取,或者可能是我使用的方法(来自 concat.split
包的 splitstackshape
)来拆分 df$name.num
不正确,尽管它似乎工作正常。有任何想法吗?
此外,我们非常欢迎有关如何改进/简化我的代码的任何建议!
最佳答案
我曾经在 R 中解决欧拉问题很有趣。这是我对 22 的解决方案。
namesscore<-function(name) {
score<-0;
for(s in 1:nchar(name)) {
score<-score + which(substr(name,s,s)==LETTERS[1:26])
}
score
}
names<-scan("prob022.txt", "character", sep=",", quote="\"", na.strings="")
name.pos <- rank(names)
name.val <- sapply(names,namesscore)
sum(name.pos*name.val)
# [1] 871198282
列表中有一个名称“NA”可能会给您带来问题。
关于r - Project Euler #22, 由 158,055 关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23787117/