scala数据结构(一):稀疏数组

在二维数组中很多数值默认都是0.记录着很多没有意义的数据,如何只存储有效棋子的位置,默认值可以不存储
类比五子棋
scala数据结构(一):稀疏数组_第1张图片

package com.zyd

import scala.collection.mutable.ArrayBuffer

object SparseArrayDemo {
  //初始化棋盘大小
  val rwoNum = 15
  val colsNum = 15

  def initChessBoard(): Array[Array[Int]] = {
    //用于创建多维数组
    val arr: Array[Array[Int]] = Array.ofDim[Int](rwoNum, colsNum);
    val white = 1
    val black = 2
    arr(1)(2) = white;
    arr(2)(3) = black
    arr
  }

  //2.将五子棋盘转换为稀疏数组
  def toSparseArray(chess: Array[Array[Int]]): SparseArray = {
    val sparseArray = new SparseArray
    for (row <- chess.indices; col <- chess(row).indices if chess(row)(col) != 0) {
      sparseArray.add(row, col, chess(row)(col))
    }
    sparseArray
  }

  // 3. 把稀疏数组转换成二维棋盘  
  def sparse2Chess(sparseArray: SparseArray): Array[Array[Int]] = {
    val arr = Array.ofDim[Int](rwoNum, colsNum)
    sparseArray.buf.foreach(node => {
      arr(node.row)(node.col) = node.value
    })
    arr
  }

  def printChess(chess: Array[Array[Int]]): Unit = {
    for (row <- chess.indices;col <- chess(row).indices){
      print(chess(row)(col) + "")
      if (col == chess(row).length -1 ) println()
    }
  }


  def main(args: Array[String]): Unit = {
    //1.初始化棋盘
    val chess = initChessBoard()
    //2.将五子棋盘转换为稀疏数组
    val sparseArray: SparseArray = toSparseArray(chess);
    println(sparseArray)
    //3.稀疏数字转成屋子棋盘
    println("++++++++++++++稀疏数字转成屋子棋盘+++++++++++++++")
    val array = sparse2Chess(sparseArray)
    //4.打印棋盘
    printChess(array)
  }

}

//定义稀疏数组
class SparseArray {
  //使用可变数组来存储Node(行列值信息)
  val buf: ArrayBuffer[Node] = ArrayBuffer[Node]()
  //判断稀疏数组是否为空
  val isEmpty: Boolean = buf.isEmpty

  //向稀疏数组中添加数据
  def add(row: Int, col: Int, value: Int): ArrayBuffer[Node] = {
    buf += Node(row, col, value)
  }

  override def toString: String = buf.toString()

  //用来存储二维数组中非默认值的行,列,值
  case class Node(row: Int, col: Int, value: Int)

}

结果

ArrayBuffer(Node(1,2,1), Node(2,3,2))
++++++++++++++稀疏数字转成屋子棋盘+++++++++++++++
000000000000000
001000000000000
000200000000000
000000000000000
000000000000000
000000000000000
000000000000000
000000000000000
000000000000000
000000000000000
000000000000000
000000000000000
000000000000000
000000000000000
000000000000000

你可能感兴趣的:(scala数据结构(一):稀疏数组)