稀疏数组的文件写入与还原二维数组

稀疏数组

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Final {
    public static void main(String[] args) throws IOException {
        //创建原始数组  11*11  1表示黑子,2表示蓝子
        int[][] chessArray1 = new int[11][11];
        chessArray1[1][2]=1;
        chessArray1[2][3]=2;
        chessArray1[3][4]=1;
        chessArray1[4][5]=2;
        //1、先遍历二维数组,得到非零数据个数
        int sum=0;
        for(int i=0;i<chessArray1.length;i++){
            for(int j=0;j<chessArray1[0].length;j++){
                if(chessArray1[i][j]!=0) sum++;
            }
        }
        //2、创建稀疏数组
        int[][] sparseArray = new int[sum+1][3];
        //3、给稀疏数组赋值
        sparseArray[0][0]=11;
        sparseArray[0][1]=11;
        sparseArray[0][2]=sum;

        int temp=1;
        for(int i=0;i<chessArray1.length;i++){
            for(int j=0;j<chessArray1[0].length;j++){
                if(chessArray1[i][j]!=0){
                    sparseArray[temp][0] =i;
                    sparseArray[temp][1] =j;
                    sparseArray[temp++][2] =chessArray1[i][j];
                }
            }
        }
        //将稀疏数组保存到文件;
        File f = new File("./map.data");
        FileWriter fwrite = new FileWriter(f);

        for(int i=0;i<sparseArray.length;i++){
            for(int j=0;j<3;j++){
                fwrite.write(sparseArray[i][j]+"\t");
            }
            fwrite.write("\r\n");
        }

        fwrite.close();

        //从文件中还原
        FileReader fread = new FileReader("map.data");
        char[] cbuf=new char[32];
        int hasRead=0;
        String s1="";
        while((hasRead=fread.read(cbuf))>0){
            s1+=new String(cbuf,0,hasRead);
        }
        fread.close();
        //文件中的稀疏数组输出
        System.out.println(s1);

        String[] s2 = s1.split("\n");
        String[] t=s2[0].split("\t");
        int[][] array = new int[Integer.parseInt(t[0])][Integer.parseInt(t[1])];
        for(int i=1;i<=Integer.parseInt(t[2]);i++){
            String[] t1 = s2[i].split("\t");
            array[Integer.parseInt(t1[0])][Integer.parseInt(t1[1])] = Integer.parseInt(t1[2]);
        }


        System.out.println("还原后的原始二维数组输出");
        for(int[] row:chessArray1){
            for(int data:row){
                System.out.printf("%d\t",data); //格式化输出
            }
            System.out.println();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值