Login
Immutable PageDiscussionInfoAttachments
iz/競技プログラミング/Project Euler 017 Number letter counts

MMA

http://projecteuler.net/problem=17

1から1000までを英語表記にしたとき(one, two, three, ... , one thousand)スペースとハイフン以外の文字は計何文字使われるか。

気合と根性で実装。

   1 #!/usr/bin/env ruby
   2 
   3 @word = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
   4 "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen",
   5 "twenty", "twentyone", "twentytwo", "twentythree", "twentyfour", "twentyfive", "twentysix", "twentyseven", "twentyeight", "twentynine",
   6 "thirty", "thirtyone", "thirtytwo", "thirtythree", "thirtyfour", "thirtyfive", "thirtysix", "thirtyseven", "thirtyeight", "thirtynine",
   7 "forty", "fortyone", "fortytwo", "fortythree", "fortyfour", "fortyfive", "fortysix", "fortyseven", "fortyeight", "fortynine",
   8 "fifty", "fiftyone", "fiftytwo", "fiftythree", "fiftyfour", "fiftyfive", "fiftysix", "fiftyseven", "fiftyeight", "fiftynine",
   9 "sixty", "sixtyone", "sixtytwo", "sixtythree", "sixtyfour", "sixtyfive", "sixtysix", "sixtyseven", "sixtyeight", "sixtynine",
  10 "seventy", "seventyone", "seventytwo", "seventythree", "seventyfour", "seventyfive", "seventysix", "seventyseven", "seventyeight", "seventynine",
  11 "eighty", "eightyone", "eightytwo", "eightythree", "eightyfour", "eightyfive", "eightysix", "eightyseven", "eightyeight", "eightynine",
  12 "ninety", "ninetyone", "ninetytwo", "ninetythree", "ninetyfour", "ninetyfive", "ninetysix", "ninetyseven", "ninetyeight", "ninetynine"]
  13 
  14 def count(n)
  15   if (n < 100)
  16     return @word[n].length
  17   elsif (n < 1000)
  18     p = n / 100 # 百の位の値
  19     q = n % 100 # 下2ケタ
  20     if (q == 0)
  21       return (@word[p] + "hundred").length
  22     else 
  23       return (@word[p] + "hundred" + "and" + @word[q]).length
  24     end
  25   else 
  26     return ("one" + "thousand").length
  27   end
  28 end
  29 
  30 p (1..1000).inject(0) {|acc, n| acc + count(n)}

iz/競技プログラミング/Project Euler 017 Number letter counts (last edited 2012-12-22 09:37:19 by iz)