裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

英語で数を読む

2015年03月16日 | ブログラミング

符号付き 32 ビット整数を英語で読めとのお達しで...

o1 = c("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven",
  "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
o2 = c("", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
o3 = "Hundred"
o4 = c("Thousand", "Million", "Billion")
count = function(n) {
  cat("n =", n, "\n")
  ans = NULL
  if (0 > n) {
    ans = "Negative"
    n = -n
  }
  s = unlist(strsplit(as.character(abs(n)), ""))
  ns = length(s)
  if (12 > ns) s = c(rep(0, 12 - ns), s)
  s = matrix(as.numeric(s), ncol = 3, byrow = TRUE)
  if (all(s == 0)) ans = "Zero"
  for (i in 1:4) {
    if (any(s[i, ] != 0)) {
      if (s[i, 1] > 0) ans = c(ans, o1[s[i, 1]], o3)
      if (s[i, 2] >= 2) {
        ans = c(ans, o2[s[i, 2]])
        if (s[i, 3] != 0) ans = c(ans, o1[s[i, 3]])
      }
      if (1 >= s[i, 2] && (s[i, 2] + s[i, 3] != 0)) ans = c(ans, o1[s[i, 2] * 10 + s[i, 3]])
      if (3 >= i) ans = c(ans, o4[4 - i])
    }
  }
  paste(ans, collapse = " ")
}
# テストデータ
q = c(7, 123, 4567, 89012, 0, -34, -5678901, 1111111111)
ans = c("Seven", "One Hundred Twenty Three", "Four Thousand Five Hundred Sixty Seven", "Eighty Nine Thousand Twelve",
  "Zero", "Negative Thirty Four", "Negative Five Million Six Hundred Seventy Eight Thousand Nine Hundred One",
  "One Billion One Hundred Eleven Million One Hundred Eleven Thousand One Hundred Eleven")
for (i in seq_along(q)) {
  a = count(q[i])
  cat("a: ", a, "\n")
  cat("b: ", ans[i], "\n")
  if (a != ans[i]) cat("Wrong!!\n\n")
}

結果は一応 OK

n = 7
a:  Seven
b:  Seven

n = 123
a:  One Hundred Twenty Three
b:  One Hundred Twenty Three

n = 4567
a:  Four Thousand Five Hundred Sixty Seven
b:  Four Thousand Five Hundred Sixty Seven

n = 89012
a:  Eighty Nine Thousand Twelve
b:  Eighty Nine Thousand Twelve

n = 0
a:  Zero
b:  Zero

n = -34
a:  Negative Thirty Four
b:  Negative Thirty Four

n = -5678901
a:  Negative Five Million Six Hundred Seventy Eight Thousand Nine Hundred One
b:  Negative Five Million Six Hundred Seventy Eight Thousand Nine Hundred One

n = 1111111111
a:  One Billion One Hundred Eleven Million One Hundred Eleven Thousand One Hundred Eleven
b:  One Billion One Hundred Eleven Million One Hundred Eleven Thousand One Hundred Eleven

コメント    この記事についてブログを書く
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする
« カプレカ数(その2) | トップ | sample 関数 »
最新の画像もっと見る

コメントを投稿

ブログラミング」カテゴリの最新記事