编程之美中烙饼排序的scala实现

最近看了《编程之美》,书中讲了很多有趣的小例子,突然发现生活中有很多事情都可以和编程结合起来分析,感觉自己之前的思路真是太窄了,正好目前主要使用的编程语言是scala,于是选取几个例子,动手使用scala实现一遍,有感兴趣的朋友看看就好啦。

代码如下:

object CookieSort{

  var cakeArray: Array[Int] = Array.empty  //炊饼数组
  var cakeNum: Int = -1    //炊饼个数
  var maxSwapCount: Int = -1   //最多交换次数

  var curSearchCount: Int = 0  //当前搜索次数
  var processingSwapArray: Array[Int] = Array.empty //搜索过程中的交换数组
  var finalSwapArray: Array[Int] = Array.empty   //搜索完成的交换数组

  def main(args: Array[String]) {
    run(Array(3,2,1,6,5,4,9,8,7,0))
    println(s"search $curSearchCount times, the max swap step is $maxSwapCount , there are ${finalSwapArray.take(maxSwapCount).mkString(",")}")
  }

  def run(arr: Array[Int]): Unit ={
    init(arr)
    search(0)
  }

  def init(arr: Array[Int]): Unit ={
    assert(arr != null)
    assert(arr.length > 0)
    cakeArray = arr
    cakeNum = arr.length
    maxSwapCount = upperBound(cakeNum)
    processingSwapArray = new Array[Int](maxSwapCount)
    finalSwapArray = new Array[Int](maxSwapCount)
    curSearchCount = 0
  }

  def search(step: Int): Unit = {
    if(step + lowerBound(cakeArray) >= maxSwapCount) return
    if(isSorted(cakeArray)){
      if(step<maxSwapCount){
        maxSwapCount = step
        for(k <- 0 to step){
          finalSwapArray(k) = processingSwapArray(k)
        }
      }
      return
    }

    for(i <- 1 to cakeNum-1){
      reverse(0,i)
      processingSwapArray(step) = i
      search(step+1)
      reverse(0,i)
    }

    curSearchCount += 1
  }

  def upperBound(n: Int): Int = {
    n * 2
  }

  def lowerBound(arr: Array[Int]): Int = {
    var count = 0
    for(i <- 1 to arr.length-1){
      val diff = arr(i) - arr(i-1)
      if(diff != 1 && diff != -1) count +=1
    }
    count
  }

  def isSorted(arr: Array[Int]): Boolean = {
    for(i <- 1 to arr.length-1){
      if(arr(i) < arr(i-1)) return false
    }
    true
  }

  def reverse(begin: Int, end: Int): Unit ={
    assert(end>begin)
    var i = begin
    var j = end
    var t = -999999999
    while (i < j){
      t = cakeArray(i)
      cakeArray(i) = cakeArray(j)
      cakeArray(j) = t
      i+=1
      j-=1
    }
  }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值