Skip to content

Instantly share code, notes, and snippets.

@ubourdon
Created October 5, 2012 09:24
Show Gist options
  • Save ubourdon/3838903 to your computer and use it in GitHub Desktop.
Save ubourdon/3838903 to your computer and use it in GitHub Desktop.
[COURSERA-1][RECURSION] pascal triangle, count '(', count change money
/**
* Exercise 1
*/
def pascal(c: Int, r: Int): Int = {
if (c == 0 || c == r) 1 // si r == c alors la décomposition en dessous tombe forcement sur pascal(c>r) et c'est impossible
else pascal(c - 1, r - 1) + pascal(c, r - 1)
}
/**
* Exercise 2
*/
def balance(chars: List[Char]): Boolean = count( chars, 0 ) == 0
/**
* Exercise 3
*/
def countChange(money: Int, coins: List[Int]): Int = {
val sortedCoins: List[Int] = coins.sortWith( (x,y) => x < y )
rideTree(money, sortedCoins, List(0))
}
private def rideTree(money: Int, coins: List[Int], branch: List[Int]): Int = {
coins.map {
coin =>
if(coin >= branch.last )
if((branch.sum + coin) < money)
rideTree(money, coins, branch :+ coin )
else if((branch.sum + coin) == money) 1
else 0
else 0
}.sum
}
// !!! ceci va entrainer un stack overflow - voir https://class.coursera.org/progfun-2012-001/lecture/33 pour explication
/*private def fact(n: Int): Int = {
if (n == 0) 1
else n * fact(n - 1)
}*/
private def count(chars: List[Char], state: Int): Int = {
if(chars.isEmpty) state
else if(state < 0) state
else
if(chars.head == '(') count(chars.tail, state + 1)
else if(chars.head == ')') count(chars.tail, state - 1)
else count(chars.tail, state)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment