Skip to content

Instantly share code, notes, and snippets.

@davidlukac
Created April 30, 2016 09:44
Show Gist options
  • Save davidlukac/a5fc856cb3e914059f4c7ec774cbd438 to your computer and use it in GitHub Desktop.
Save davidlukac/a5fc856cb3e914059f4c7ec774cbd438 to your computer and use it in GitHub Desktop.
Learning Scala / Scala snippets
package com.davidlukac.learn.scala
/**
* Created by davidlukac on 30/04/16.
*/
class Coins {
def countChange(money: Int, coins: List[Int]): Int = {
// Just for the sake of algorithm logic, sort the coins from highest value, to smallest value.
val sortedCoins = coins.sorted.reverse
/**
* Recursive function that counts number of ways to split given amount of money with given coins.
* E.g.:
* 10GBP can by split using coins 1, 2 and 5 in following ways:
* - 01: 5 + 5
* - 02: 5 + 2 + 2 + 1
* - 03: 5 + 2 + 1 + 1 + 1
* - ...
* - Nm: 2 + 2 + 2 + 2 + 2
* - Nm+1: 2 + 2 + 2 + 2 + 1 + 1
* - ...
* - 10: 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
* @param money Sum to split.
* @param coins List of coins.
* @return Number of way we can split the sum.
*/
def countChangeRec(money: Int, coins: List[Int]): Int = {
// We have successfully subtracted the sum of money using given coins to zero - count as positive result.
if (money == 0) 1
// If the subtraction got us below zero, we can't use this combination of coins,
// also if there are no coin combinations left and we still didn't reach zero, this can't be counted as
// successful coin change.
else if (money < 0 || coins.isEmpty) 0
// Recursively try to find out number of ways to get the change, with remainder of sum and remainder of coins.
else countChangeRec(money - coins.head, coins) + countChangeRec(money, coins.tail)
}
countChangeRec(money, sortedCoins)
}
}
object Coins {
def main(args: Array[String]) {
val c = new Coins
// Expected result - 293.
println(c.countChange(100, List(1, 5, 10 , 25, 50, 100)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment