1-稀疏数组-Scala实现
需求:怎么实现五子棋的存档。
解决:可以暴力的用二维数组去解决,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
~