稀疏数组练习题:
作业要求:
1.将二维数组转换为稀疏数组
2.实现稀疏数组的存取
3.将稀疏数组再转换为二维数组
代码实现如下:
import java.io.*;
/**
* 典型题型:棋盘
* 通过模拟实现棋盘的续盘功能来了解稀疏数组的应用
*/
public class SparseArray {
public static void main(String[] args) throws FileNotFoundException {
int[][] chessArray = new int[11][11]; //创建一个11 x 11的棋盘
chessArray[1][2] = 1; //1表示黑棋
chessArray[2][3] = 2; //2表示白棋
chessArray[3][4] = 1;
chessArray[4][5] = 2;
//构建一个二维棋盘出来
//遍历二维数组,每列显示一维数组
for(int[] chessRow : chessArray){
//每个一维数组显示其中的数据
for (int data : chessRow){
System.out.print("\t" + data);
}
//显示完该行一维数组换行显示下一行
System.out.println();
}
//遍历二维数组,将里面的数值转换为稀疏数组,记录数值的个数
int sum = 0;
for (int i = 0; i < chessArray.length; i++) {
for (int j = 0; j < chessArray[i].length; j++) {
if (chessArray[i][j] != 0){
sum++;
}
}
}
System.out.println("sum = " +sum);
//创建一个稀疏数组
int[][] sparseArray = new int[sum + 1][3];
//稀疏数组的行
sparseArray[0][0] = 11;
//稀疏数组的列
sparseArray[0][1] = 11;
//sum
sparseArray[0][2] = sum;
int arrayIndex = 1;
for (int i = 0; i < chessArray.length; i++) {
for (int j = 0; j < chessArray[i].length; j++) {
//稀疏数组中存入的值
if (chessArray[i][j] != 0){
sparseArray[arrayIndex][0] = i;
sparseArray[arrayIndex][1] = j;
sparseArray[arrayIndex][2] = chessArray[i][j];
arrayIndex++;
}
}
}
/* System.out.println("sum = " + sum);
System.out.println(sparseArray[0][0] + "\t" + sparseArray[0][1]);*/
System.out.println("稀疏数组++++++++++++++++++++++++");
//定义一个换行count
int count = 0;
for (int i = 0; i < sparseArray.length; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(sparseArray[i][j] + "\t");
count++;
}
if (count % 3 == 0){
System.out.println();
}
}
/**
* 通过遍历的方式将稀疏数组存到硬盘中
*/
FileOutputStream fw = null;
try {
fw = new FileOutputStream("Data Structure/sparseArray.txt");
for (int i = 0; i < sparseArray.length; i++) {
for (int j = 0; j < 3; j++) {
fw.write(sparseArray[i][j]);
}
}
fw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("===========================");
//从硬盘中读取稀疏数组
int[][] sa2 = new int[sum+1][3];
FileInputStream reader = null;
reader = new FileInputStream("Data Structure/sparseArray.txt");
try {
for (int i = 0; i < sa2.length; i++) {
for (int j = 0; j < 3; j++) {
sa2[i][j] = reader.read();
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
for(int i =0; i < sa2.length; i++) {
//定义格式并输出
System.out.printf("%d\t%d\t%d\n", sa2[i][0], sa2[i][1], sa2[i][2]);
}
/**
* 将稀疏数组转换为二维数组并遍历二维数组
*/
int[][] chessArray2 = new int[sa2[0][0]][sa2[0][1]];
for (int i = 0; i < sa2.length; i++) {
for (int j = 0; j < sa2[i].length; j++) {
if (i > 0){
chessArray2[sa2[i][0]][sa2[i][1]] = sa2[i][2];
}
}
}
System.out.println("=============================");
for (int[] ca2 : chessArray2){
for (int data : ca2){
System.out.print(data + "\t");
}
System.out.println();
}
}
}