2017年7月29日 星期六

(Java)稀疏矩陣

/*
 * 
 * 稀疏矩陣
 */
public class Sparse_Matrix {
public static void main(String[] args) {
int row = 8 , com = 9 , notzero = 8;  //非零 8個
int[][] sparse = new int[row][com];
        int[][] not_zero = new int[notzero+1][3];//3-tuple
        int tmpnotzero = notzero ;
            for(int i = 1 ; i < tmpnotzero+1 ; i++){
        int tmprow = (int) (Math.random()*100);
        tmprow = tmprow % row ;
        int tmpcom = (int) (Math.random()*100);
        tmpcom = tmpcom % com ;
        if(sparse[tmprow][tmpcom] != 0 ){//原本有值就跳此迴圈
        tmpnotzero++ ;
        continue ;
        }
        sparse[tmprow][tmpcom] = i ;
        }
        //顯示稀疏矩陣
        for(int[] i : sparse){
        for(int value : i){
        System.out.print(value+"  ");
        }
        System.out.println();
        }
        int tmp = 1 ;
        //壓縮矩陣
        not_zero[0][0] = row ; not_zero[0][1] = com ; not_zero[0][2] = notzero ; 
        for(int i = 0 ; i < row ; i++){
        for(int j = 0 ; j < com ; j++){
        if(sparse[i][j] != 0){
        not_zero[tmp][0] = i;
        not_zero[tmp][1] = j;
        not_zero[tmp][2] = sparse[i][j];
        tmp++ ;
        }        
        }
        }
      //顯示壓縮矩陣
        for(int i[] : not_zero){
        for(int value : i){
    System.out.print(value+"  ");
        }
        System.out.println();
        }
        
        
}

}

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。