How to resolve the algorithm Roman numerals/Decode step by step in the Clojure programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Roman numerals/Decode step by step in the Clojure programming language

Table of Contents

Problem Statement

Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decimal digit and skipping any 0s   (zeroes). 1990 is rendered as   MCMXC     (1000 = M,   900 = CM,   90 = XC)     and 2008 is rendered as   MMVIII       (2000 = MM,   8 = VIII). The Roman numeral for 1666,   MDCLXVI,   uses each letter in descending order.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Roman numerals/Decode step by step in the Clojure programming language

Source code in the clojure programming language

;; Incorporated some improvements from the alternative implementation below
(defn ro2ar [r]
  (->> (reverse (.toUpperCase r))
       (map {\M 1000 \D 500 \C 100 \L 50 \X 10 \V 5 \I 1})
       (partition-by identity)
       (map (partial apply +))
       (reduce #(if (< %1 %2) (+ %1 %2) (- %1 %2)))))

;; alternative
(def numerals { \I 1, \V 5, \X 10, \L 50, \C 100, \D 500, \M 1000})
(defn from-roman [s] 
  (->> s .toUpperCase 
    (map numerals) 
    (reduce (fn [[sum lastv] curr] [(+ sum curr (if (< lastv curr) (* -2 lastv) 0)) curr]) [0,0]) 
    first))


  

You may also check:How to resolve the algorithm Sum of squares step by step in the Euler programming language
You may also check:How to resolve the algorithm Sleep step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Sierpinski carpet step by step in the Factor programming language
You may also check:How to resolve the algorithm Numeric error propagation step by step in the Java programming language
You may also check:How to resolve the algorithm String prepend step by step in the Haskell programming language