5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

この記事は自分用の備忘録です。

疎行列とは

0がいっぱいある行列(二次元配列)

[
  [3, 0, 0, 0, 0],
  [0, 2, 2, 0, 0],
  [0, 0, 0, 1, 3],
  [0, 0, 0, 2, 0],
  [0, 0, 0, 0, 1]
]

やること

0がいっぱいあるとデータとして効率が悪いので、0をなくした良い感じのデータに変換せよ

やってみる

sparseMatrix.ts
// 元データ
const matrix: number[][] = [
  [3, 0, 0, 0, 0],
  [0, 2, 2, 0, 0],
  [0, 0, 0, 1, 3],
  [0, 0, 0, 2, 0],
  [0, 0, 0, 0, 1]
];

// 圧縮データ構造の型
type SparseMatrix = [number[], number[], number[]];

// 疎行列を圧縮データ構造に変換する関数
function transformSparseMatrix(matrix: number[][]): SparseMatrix {
  const sparseMatrix: SparseMatrix = [[], [], []];

  for (let i = 0; i < matrix.length; i++) {        
    for (let j = 0; j < matrix[i].length; j++) {    
      if (matrix[i][j] !== 0) {                    
        sparseMatrix[0].push(i + 1);        // rowを入れる
        sparseMatrix[1].push(j + 1);        // columnを入れる   
        sparseMatrix[2].push(matrix[i][j]); // 値を入れる
      }
    }
  }

  return sparseMatrix;
}

// 疎行列を圧縮データ構造に変換
const result: SparseMatrix = transformSparseMatrix(matrix);

// 結果の表示
console.log("行番号:", result[0]);
console.log("列番号:", result[1]);
console.log("値:", result[2]);

実行!!

スクリーンショット 2024-12-09 22.17.56.png

(1,1)->3
(2,2)->2
(2,3)->2
...

合っている!

感想

めっちゃ数Cだった。

参考

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?