Boerner's theorem

来源:互联网 发布:php linux 删除文件 编辑:程序博客网 时间:2024/06/04 19:26
import scala.util.Random/**  * Created by fhqplzj on 16-7-16 at 下午8:06.  *//**  * 该程序的主要作用是验证一个定理,虽然结果证明定理事对的,但是不会证明。  * Boerner's theorem.  * True or false: If you sort each column of a matrix, then sort  * each row, the columns are still sorted. Justify your answer.  * 《算法》这本书357页最后一道题。  */object Justify {  val rows = 30  val cols = 40  val bound = 1000  val rand = new Random(System.nanoTime())  val sep = Array.fill(80)('*').mkString  def main(args: Array[String]) {    separate()    val matrix = generator    printMatrix(matrix)    separate("按列排序")    val column = sortColumn(matrix)    printMatrix(column)    separate("按行排序")    val row = sortRow(column)    printMatrix(row)    separate("验证结果")    val result = checker(row)    println("result = " + result)  }  def generator = {    val matrix = Array.tabulate(rows, cols) {      (row, col) =>        rand.nextInt(bound)    }    matrix  }  def printMatrix(matrix: Array[Array[Int]]): Unit = {    matrix.foreach {      line =>        println(line.mkString("\t"))    }  }  def separate(s: String = "华丽丽的分割线"): Unit = {    println()    println(sep + s + sep)    println()  }  def sortColumn(matrix: Array[Array[Int]]) = {    val result = Array.ofDim[Int](rows, cols)    for (col <- 0 until cols) {      val tmp = Array.ofDim[Int](rows)      val sorted = Array.ofDim[Int](rows)      for (row <- 0 until rows) {        tmp(row) = matrix(row)(col)      }      tmp.sorted.copyToArray(sorted)      for (row <- 0 until rows) {        result(row)(col) = sorted(row)      }    }    result  }  def sortRow(matrix: Array[Array[Int]]) = {    val result = Array.ofDim[Int](rows, cols)    for (row <- 0 until rows) {      matrix(row).sorted.copyToArray(result(row))    }    result  }  def checker(matrix: Array[Array[Int]]): Boolean = {    for (col <- 0 until cols) {      val tmp = Array.ofDim[Int](rows)      for (row <- 0 until rows) {        tmp(row) = matrix(row)(col)      }      if (!isSorted(tmp))        return false    }    true  }  def isSorted(xs: Array[Int]): Boolean = {    for (i <- 1 until xs.length if xs(i) < xs(i - 1))      return false    true  }}

0 0