Decimal to roman numeral converter in scala

Scala program for Decimal to roman numeral converter. Here mentioned other language solution.

//  Scala program for
//  Conversion from Decimal to roman number
class Perform ()
{
    // Display roman value of n
    def show(n : Int) : Unit=
    {
        if (n==1)
        {
            print("I")
        }
      	else if(n==4)
        {
            print("IV")
        }
        else if(n==5)
        {
            print("V")
        }
        else if(n==9)
        {
            print("IX")
        }
        else if(n==10)
        {
            print("X")
        }
        else if(n==40)
        {
            print("XL")
        }
        else if(n==50)
        {
            print("L")
        }
        else if(n==90)
        {
            print("XC")
        }
        else if(n==100)
        {
            print("C")
        }
        else if(n==400)
        {
            print("CD")
        }
        else if(n==500)
        {
            print("D")
        }
        else if(n==900)
        {
            print("DM")
        }
        else if(n==1000)
        {
            print("M")
        }
    }
    def select(number : Long, 
               collection : Array[Int], size : Int) : Long=
    {
        var n = 1
        var i = 0
        while (i < size)
        {
            if (number >= collection(i))
            {
                n = collection(i)
            }
            else
            {
                i = size;
            }
            i += 1
        }
        show(n)
        // Reduce the value of number
        return number - n
    }
    def roman(num : Long) : Unit=
    {
      	var number = num;
        if (number <= 0)
        {
            // When is not a natural number
            return
        }
        // Base case collection
        var collection =
        Array(1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000)
        // Get the size of collection
        var size = collection.length
        print(" " + number + " : ")
        while (number > 0)
        {
            number = select(number, collection, size)
        }
        println()
    }
}

object Main 
{
	def main(args : Array[String]) : Unit=
    {
        var task = new Perform()
        // Test Case
        task.roman(10)
        task.roman(18)
        task.roman(189)
        task.roman(604)
        task.roman(982)
        task.roman(3000)
    }
}

Output

 10 : X
 18 : XVIII
 189 : CLXXXIX
 604 : DCIV
 982 : DMLXXXII
 3000 : MMM



Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2022, kalkicode.com, All rights reserved