SCALA 연습중.... SCALS coursera 첫주 과제

하안참 늦었지만 풀어보는중...


https://class.coursera.org/progfun-2012-001/assignment/view?assignment_id=4




package recfun
import common._

object Main {
  def main(args: Array[String]) {
    println("Pascal's Triangle")
    for (row <- 0 to 10) {
      for (col <- 0 to row)
        print(pascal(col, row) + " ")
      println()
    }
  }

  --*
   * Exercise 1   -- 이건 맞는듯
   --
  def pascal(c: Int, r: Int): Int =
    if (c == 0 || r == 0 || c == r) 1
    else pascal(c - 1, r - 1) + pascal(c, r - 1) //> pascal: (c: Int, r: Int)Int


  --*
   * Exercise 2  -- 이것도 대충 맞는것 같은데.......
   --
  def balance(chars: List[Char]): Boolean = {

    def balance_cnt(chars: List[Char], cnt: Int): Int =
      if (chars.isEmpty) cnt
      else {
        if (chars.head == '(') balance_cnt(chars.tail, cnt + 1)
        else {
          if (chars.head == ')') balance_cnt(chars.tail, cnt - 1)
          else balance_cnt(chars.tail, cnt)
        }
      }

    def cnt = balance_cnt(chars, 0)

    cnt == 0
  }

  --*
   * Exercise 3  -- 아짓 못 풀었음. -_-
   --
  def countChange(money: Int, coins: List[Int]): Int = {
    def cnt = 0

    def sum(curcoins: List[Int]): Int =
      if (curcoins.isEmpty) 0
      else curcoins.head + sum(curcoins.tail)

    def countChange_kind(curcoins: Int, tail_coins: List[Int], count: Int): Int = {
      if (curcoins == money) count + 1
      else {
        if (curcoins > money) count
        else countChange_kind(curcoins + tail_coins.head, tail_coins, count)
      }
    }
   
    def countChange_kind2(curcoins: Int, tail_coins: List[Int], count : Int): Int = {
      if( tail_coins.isEmpty ) count
      else {
        def count2 = countChange_kind(curcoins, tail_coins, count)
        countChange_kind2(curcoins , tail_coins.tail, count2 )
      }
    }

    countChange_kind2(0, coins, 0)
  }
}




구글애드