Project Euler Problem 17
1 から 5 までの数字を英単語で書けば one, two, three, four, five であり、全部で 3 + 3 + 4 + 4 + 5 = 19 の文字が使われている。
では 1 から 1000 (one thousand) までの数字をすべて英単語で書けば、全部で何文字になるか。
注: 空白文字やハイフンを数えないこと。例えば、342 (three hundred and forty-two) は 23 文字、115 (one hundred and fifteen) は20文字と数える。なお、"and" を使用するのは英国の慣習。
綴りのミスで何度か計算間違いをした.ハッシュを利用した方が絶対に簡単だよなぁ.うーむ.
a1 <- c(1:1000) c1 <- numeric() for(i in 1:999){ b100 <- floor(a1[i]/100) if(b100==9){ b100_2 <- "ninehundredand" } else if(b100==8){ b100_2 <- "eighthundredand" } else if(b100==7){ b100_2 <- "sevenhundredand" } else if(b100==6){ b100_2 <- "sixhundredand" } else if(b100==5){ b100_2 <- "fivehundredand" } else if(b100==4){ b100_2 <- "fourhundredand" } else if(b100==3){ b100_2 <- "threehundredand" } else if(b100==2){ b100_2 <- "twohundredand" } else if(b100==1){ b100_2 <- "onehundredand" } else { b100_2 <- "" } b99 <- a1[i] - b100*100 if(b99 > 19){ b10 <- floor(b99 / 10) if(b10==9){ b10_2 <- "ninety" } else if(b10==8){ b10_2 <- "eighty" } else if(b10==7){ b10_2 <- "seventy" } else if(b10==6){ b10_2 <- "sixty" } else if(b10==5){ b10_2 <- "fifty" } else if(b10==4){ b10_2 <- "forty" } else if(b10==3){ b10_2 <- "thirty" } else{ b10_2 <- "twenty" } b1 <- b99 - b10*10 if(b1==9){ b1_2 <- "nine" } else if(b1==8){ b1_2 <- "eight" } else if(b1==7){ b1_2 <- "seven" } else if(b1==6){ b1_2 <- "six" } else if(b1==5){ b1_2 <- "five" } else if(b1==4){ b1_2 <- "four" } else if(b1==3){ b1_2 <- "three" } else if(b1==2){ b1_2 <- "two" } else if(b1==1){ b1_2 <- "one" } else{ b1_2 <- "" } c1[i] <- paste(b100_2,b10_2,b1_2,sep="") } else{ b10 <- b99 b10 <- sub("19","nineteen",b10) b10 <- sub("18","eighteen",b10) b10 <- sub("17","seventeen",b10) b10 <- sub("16","sixteen",b10) b10 <- sub("15","fifteen",b10) b10 <- sub("14","fourteen",b10) b10 <- sub("13","thirteen",b10) b10 <- sub("12","twelve",b10) b10 <- sub("11","eleven",b10) b10 <- sub("10","ten",b10) b10 <- sub("9","nine",b10) b10 <- sub("8","eight",b10) b10 <- sub("7","seven",b10) b10 <- sub("6","six",b10) b10 <- sub("5","five",b10) b10 <- sub("4","four",b10) b10 <- sub("3","three",b10) b10 <- sub("2","two",b10) b10 <- sub("1","one",b10) b10 <- sub("0","",b10) c1[i] <- paste(b100_2,b10,sep="") } } c1[100] <- "onehundred" c1[200] <- "twohundred" c1[300] <- "threehundred" c1[400] <- "fourhundred" c1[500] <- "fivehundred" c1[600] <- "sixhundred" c1[700] <- "sevenhundred" c1[800] <- "eighthundred" c1[900] <- "ninehundred" c1[1000] <-"onethousand" sum(nchar(c1))