Tech Tips

  1. Uncategorized
  2. 1314 view

[Scaka]Pancake Sort

Image Video of Pancake Sort

Source code of scala

object PancakeSort {
   def main(args: Array[String]) {
      // Prepare input values
      val arr = List(23, 10, 20, 11, 12, 6, 7)
      // Do pancake sort
      val result = pancakeSort((for(x <- 0 to arr.size-1) yield (x, arr(x))).toList, arr.size)
      // Output the result
      println("Input")
      arr.foreach(x => println(x))
      println("Output:")
      result.foreach(x => println(x._2))
   }

   def pancakeSort(arr: List[(Int, Int)], n:Int):List[(Int, Int)] = {
      // Apply flip operator from idx 0th to nth
      if (n <= 0) return arr else return pancakeSort(flips(arr.filter(x => x._1 <= n)) ::: arr.filter(x => x._1 > n), n-1)
   }

   def flips(arr: List[(Int, Int)]):List[(Int, Int)] = {
      // Get index of max value
      val max_index = arr.reduceLeft{ (a,b) => if (a._2 > b._2) (a._1, a._2) else (b._1, b._2) }._1
      // Place max value to tail
      val tmp_arr = (arr.filter(a => a._1 <= max_index).reverse ::: arr.filter(a => a._1 > max_index)).reverse
      // Refine value's index
      return (for (x <- 0 to tmp_arr.size-1) yield (x, tmp_arr(x)._2)).toList
   }
}

Uncategorized recent post

  1. Run Amazon FreeRTOS on M5Stack Core2 for AWS …

  2. Udacity Self-Driving Car Engineer Nanodegree …

  3. Install sbt 1.0.0 and run sample template

  4. Visualization of Neural Network and its Train…

  5. [Machine Learning]Created docker image includ…

関連記事

PAGE TOP