Skip to content

Instantly share code, notes, and snippets.

@vitaly-pushkar
Last active January 11, 2018 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitaly-pushkar/885fbd7f718a74136bb3fe9d0cf2b22d to your computer and use it in GitHub Desktop.
Save vitaly-pushkar/885fbd7f718a74136bb3fe9d0cf2b22d to your computer and use it in GitHub Desktop.
Changing money problem solved recursively in Scala with a greedy approach
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