最近看了《编程之美》,书中讲了很多有趣的小例子,突然发现生活中有很多事情都可以和编程结合起来分析,感觉自己之前的思路真是太窄了,正好目前主要使用的编程语言是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
}
}
}