プロジェクト

全般

プロフィール

Problem 17 » 履歴 » バージョン 2

Noppi, 2023/12/31 02:37

1 1 Noppi
[ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]]
2
# [[Problem 17]]
3
4
## Number Letter Counts
5
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.
6
If all the numbers from $1$ to $1000$ (one thousand) inclusive were written out in words, how many letters would be used?
7
**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.
8
9
## 数字の文字数
10
1 から 5 までの数字を英単語で書けば one, two, three, four, five であり, 全部で 3 + 3 + 5 + 4 + 4 = 19 の文字が使われている.
11
では 1 から 1000 (one thousand) までの数字をすべて英単語で書けば, 全部で何文字になるか.
12
注: 空白文字やハイフンを数えないこと. 例えば, 342 (three hundred and forty-two) は 23 文字, 115 (one hundred and fifteen) は20文字と数える. なお, "and" を使用するのは英国の慣習.
13
14
```scheme
15 2 Noppi
#!r6rs
16
#!chezscheme
17
18
(import (chezscheme))
19
20
(define (number-letter num)
21
  (assert (and (<= 1 num) (<= num 1000)))
22
  (case num
23
    [1 "one"]
24
    [2 "two"]
25
    [3 "three"]
26
    [4 "four"]
27
    [5 "five"]
28
    [6 "six"]
29
    [7 "seven"]
30
    [8 "eight"]
31
    [9 "nine"]
32
    [10 "ten"]
33
    [11 "eleven"]
34
    [12 "twelve"]
35
    [13 "thirteen"]
36
    [14 "fourteen"]
37
    [15 "fifteen"]
38
    [16 "sixteen"]
39
    [17 "seventeen"]
40
    [18 "eighteen"]
41
    [19 "nineteen"]
42
    [20 "twenty"]
43
    [30 "thirty"]
44
    [40 "forty"]
45
    [50 "fifty"]
46
    [60 "sixty"]
47
    [70 "seventy"]
48
    [80 "eighty"]
49
    [90 "ninety"]
50
    [1000 "one thousand"]
51
    [else
52
      (if (< num 100)
53
        ; 2桁(10の位と1の位に分けて処理)
54
        (let-values ([(upper lower) (div-and-mod num 10)])
55
          (format "~D-~D" (number-letter (* upper 10)) (number-letter lower)))
56
        ; 3桁(100の位と残り2桁に分けて処理)
57
        (let-values ([(upper lower) (div-and-mod num 100)])
58
          (if (zero? lower)
59
            (format "~D hundred" (number-letter upper))
60
            (format "~D hundred and ~D"
61
                    (number-letter upper)
62
                    (number-letter lower)))))]))
63
64
(define all-number-letters
65
  (map number-letter (cdr (iota 1001))))
66
67
(define concatenate-all-number-letters
68
  (fold-left
69
    (lambda (result letter)
70
      (string-append result letter))
71
    ""
72
    all-number-letters))
73
74
(define (erase-space-hyphen str)
75
  (list->string
76
    (filter
77
      (lambda (char)
78
        (case char
79
          [(#\space #\-) #f]
80
          [else #t]))
81
      (string->list str))))
82
83
(define answer-17
84
  (string-length (erase-space-hyphen concatenate-all-number-letters)))
85
86
(printf "17: ~D~%" answer-17)
87 1 Noppi
```