Last active
January 11, 2018 09:29
-
-
Save vitaly-pushkar/885fbd7f718a74136bb3fe9d0cf2b22d to your computer and use it in GitHub Desktop.
Changing money problem solved recursively in Scala with a greedy approach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.annotation.tailrec | |
object ChangingMoney extends App { | |
val money = scala.io.StdIn.readInt() | |
// canonical coin system; this algorithm will not work optimally for arbitrary coin systems | |
val coins = List(10, 5, 1) | |
println(changeMoney(money)) | |
def changeMoney(money: Int): Int = { | |
@tailrec | |
def rec(m: Int, n: Int): Int = m match { | |
case 0 => n | |
case x => { | |
val coin = coins.find( x / _ > 0).get | |
rec(x % coin, n + x / coin) | |
} | |
} | |
rec(money, 0) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment