PamGau
Web周り、サッカーの話、ときどきヌコ

RubyでProject Euler - Problem 17

Problem 17 (Project Euler) [和訳])

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

スペルミスにはくれぐれもご注意。私などは"tweleve"とやっているのに気づかなくて時間を喰いました。

コード量が、比較的短くて済んだので載せておきます。

  begin_time = Time.now

  num_hash = {0 => "", 1 => "one", 2 => "two", 3 => "three", 4 => "four",
    5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine",
    10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen",
    14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen",
    18 => "eighteen", 19 => "nineteen", 20 => "twenty", 30 => "thirty",
    40 => "forty", 50 => "fifty", 60 => "sixty", 70 => "seventy",
    80 => "eighty", 90 => "ninety", 100 =>"hundred"}

  sum = "one".length + "thousand".length

  (1..999).each do |i|
    h = (i / 100).floor # 100の位の数
    o = i % 10  # 1の位の数
    t = i % 100 - o  # 10の位の数*10
    if h > 0
      sum += num_hash[h].length + num_hash[100].length
      sum += "and".length unless t == 0 && o == 0
    end

    if t < 20
      sum += num_hash[t+o].length
    else
      sum += num_hash[t].length + num_hash[o].length
    end
  end

  puts "Char Num : #{sum}"
  puts " -- #{Time.now - begin_time}sec"

"RubyでProject Euler - Problem 16" « Home » "RubyでProject Euler - Problem 18"

TrackBack

ご注意
当分の間、トラックバックの受信を行わないことといたしました。過去に戴いたトラックバックのリストについてはそのまま保持いたします。
トラックバックはありません

Comments

コメントはありません。
ご注意
当分の間、JavaScript が有効でないとコメント投稿できないようにします。スパム対策であって、投稿される方の個人情報を取得する目的ではありません。悪しからずご了承ください。
Recent Entries
京都御苑の「自転車道」
Googleの左サイドバーを消すユーザスタイルシート for Firefox , Opera
"Ruby Way"章頭の言葉
"The worst feelings in life"より
裸の英会話
RubyでProject Euler - Problem 59
RubyでProject Euler - Problem 58
RubyでProject Euler - Problem 57
RubyでProject Euler - Problem 55, 56
RubyでProject Euler - Problem 54
Links
PamGau 系
PamGau::Memo
PamGau::Dust
PamgauSigh Wiki
はてなブックマーク
パンパでガウチョ
kyorecobaのdel.icio.us
BLOGNAVI
XREA.COM
VALUE-DOMAIN
PHP ver 4.4.2
Powered by Nucleus CMS Creative Commons
feedberner banner この日記のはてなブックマーク数
BlogPeople
あわせて読みたい