Scala 作业记录 01

Functional Programming Principles in Scala
by Martin Odersky



package recfun
import scala.util.control.TailCalls._

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()
    }
    println(countChange(14,List(5,4)))
  }

  /**
   * Exercise 1
   */
  def pascal(c: Int, r: Int): Int = {
    def loop(acc:Int, n:Int, c: Int, r: Int ): Int = {
      if (c == 0 || r == c) {
        acc
      } else {
        loop(acc * r / n , n + 1, c - 1, r - 1)
      }
    }
    loop(1, 1, c, r)
  }

  /**
   * Exercise 2
   */
  def balance(chars: List[Char]): Boolean = {
    def loop(bra: Int, rem: List[Char]): Int = {
      if (rem.isEmpty || bra < 0) {
        bra
      } else {
        val new_bra = rem.head match {
          case '(' => bra + 1
          case ')' => bra - 1
          case _ => bra
        }
        loop(new_bra, rem.tail)
      }
    }
    loop(0, chars) == 0
  }

  /**
   * Exercise 3
   */
  def countChange(money: Int, coins: List[Int]): Int = {
    if (money < 0) 0
    else coins match {
      case Nil => if (money == 0) 1 else 0
      case x::xs => countChange(money - x, coins) + countChange(money, xs)
    }
  }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值