Advertisement
Bobcat77

substring Roman->Number

Oct 25th, 2023
1,917
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 2.08 KB | None | 0 0
  1. ;; Constants
  2. (define MarcusAurelius (cons "I" (cons "V" (cons "X" (cons "L"
  3.                        (cons "C" (cons "D" (cons "M" empty))))))))
  4.  
  5. (define panem_et_circenses (cons 1 (cons 5 (cons 10 (cons 50
  6.                            (cons 100 (cons 500 (cons 1000 empty))))))))
  7.  
  8. (define (pos? input stoic counter) ;my way of thinking about recursion isn't strong, taking the easy way out
  9.   (cond                            ;w/ a counter parameter. Is it really possible to do this with recursion?!
  10.       [(= (string-length input) 0) 0]
  11.       [(string=? (substring input 0 1) (first stoic)) counter]
  12.       [else (pos? input (rest stoic) (add1 counter))]))
  13.  
  14. (define (list-ref?! Arabic pos)
  15.   (cond
  16.     [(empty? Arabic) false]
  17.     [(= pos 0) (first Arabic)]
  18.     [else (list-ref?! (rest Arabic) (- pos 1))]))
  19.  
  20. (define (roman->number rnum)
  21.   (cond
  22.     [(= (string-length rnum) 0) 0]
  23.     [(= (string-length rnum) 1) (list-ref?! panem_et_circenses (pos? rnum MarcusAurelius 0))]
  24.     [else
  25.      (cond
  26.        [(and (< (pos? (substring rnum 0 1) MarcusAurelius 0) (pos? (substring rnum 1 2) MarcusAurelius 0)) ;IV IX XL XC CD CM
  27.              (or (and (= 0 (pos? (substring rnum 0 1) MarcusAurelius 0))
  28.                       (or (= 1 (pos? (substring rnum 1 2) MarcusAurelius 0)) (= 2 (pos? (substring rnum 1 2) MarcusAurelius 0))))
  29.                  (and (= 2 (pos? (substring rnum 0 1) MarcusAurelius 0))
  30.                       (or (= 3 (pos? (substring rnum 1 2) MarcusAurelius 0)) (= 4 (pos? (substring rnum 1 2) MarcusAurelius 0))))
  31.                  (and (= 4 (pos? (substring rnum 0 1) MarcusAurelius 0))
  32.                       (or (= 5 (pos? (substring rnum 1 2) MarcusAurelius 0)) (= 6 (pos? (substring rnum 1 2) MarcusAurelius 0))))))
  33.         (+ (- (list-ref?! panem_et_circenses (pos? (substring rnum 1 2) MarcusAurelius 0))
  34.               (list-ref?! panem_et_circenses (pos? (substring rnum 0 1) MarcusAurelius 0)))
  35.         (roman->number (substring rnum 2)))]
  36.        [else (+ (list-ref?! panem_et_circenses (pos? (substring rnum 0 1) MarcusAurelius 0)) (roman->number (substring rnum 1)))])]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement