1-稀疏數組-Scala實現

需求:怎麼實現五子棋的存檔。node

解決:能夠暴力的用二維數組去解決,0表示沒有棋子;1表示黑棋;2表示白棋。但會有不少的多餘的0,能夠用稀疏數組。就把原來的數據變成一個小數據量的數組,達到壓縮的目的。數組

import scala.collection.mutable.ArrayBuffer

object SparseArrayDemo {
  def main(args: Array[String]): Unit = {
    val rows=11
    val cols=11
    val chessMap1: Array[Array[Int]] = Array.ofDim[Int](rows,cols)

    //初始化
    chessMap1(1)(2)=1//表示黑子
    chessMap1(2)(3)=2//表示白子
    chessMap1(3)(6)=2
    chessMap1(5)(10)=1
    for (row <- chessMap1){
      for (itm <- row){
        printf("%d ",itm)
      }
      println()
    }

    //對原始的二維數組進行壓縮
    //1,建立ArrayList,能夠動態的添加數據
    //2,使用node對象,表示一行數據
    val spaseArray = ArrayBuffer[Node]()
    spaseArray.append(new Node(rows,cols,0))
    //遍歷棋盤,若是有非0的值就加入spaseArray
    //壓縮
    for (i <- 0 until chessMap1.length){

      for (j <- 0 until chessMap1(i).length){
        if (chessMap1(i)(j) != 0){
          spaseArray.append(new Node(i,j,chessMap1(i)(j)))
        }
      }
    }

    println("稀疏數組狀況是")
    for (i <- 0 until spaseArray.length){
      val node = spaseArray(i)
      printf("%d %d %d",node.row ,node.col,node.value)
      println()
    }

    //從稀疏數據恢復
    //1.讀取第一行,建立一個二維的棋盤
    //2,從第二行開始遍歷恢復
    val node: Node = spaseArray(0)
    val chessMap2: Array[Array[Int]] = Array.ofDim[Int](node.row,node.col)
    for (i <- 1 until spaseArray.length){
      val node2 = spaseArray(i)
      chessMap2(node2.row)(node2.col)=node2.value;
    }
    for (row <- chessMap2){
      for (itm <- row){
        printf("%d ",itm)
      }
      println()
    }

  }

}
class Node(val row:Int,val col:Int,val value:Int)
0 0 0 0 0 0 0 0 0 0 0 
0 0 1 0 0 0 0 0 0 0 0 
0 0 0 2 0 0 0 0 0 0 0 
0 0 0 0 0 0 2 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 1 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
稀疏數組狀況是
11 11 0
1 2 1
2 3 2
3 6 2
5 10 1
0 0 0 0 0 0 0 0 0 0 0 
0 0 1 0 0 0 0 0 0 0 0 
0 0 0 2 0 0 0 0 0 0 0 
0 0 0 0 0 0 2 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 1 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 

~app

相關文章
相關標籤/搜索