1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

二次元正方行列にスケーラブルな一次元の番号を付ける

Last updated at Posted at 2024-11-04

やりたいこと

二次元の正方行列に次のように番号を振ることができれば、実装を一次元に落とし込むことができ、かつ行・列数が増減しても既存の要素を触らずに済みます。
(※ただし増減は行・列の末尾に限るものとする)

[0] [1] [2] [3]
[0] 0 1 4 9
[1] 3 2 5 10
[2] 8 7 6 11
[3] 15 14 13 12

方法

番号を次のように計算すれば良いです。
$n = max(x,y)^2 + max(x,y) + y - x$
或いは
$n = max(x,y)^2 + max(x,y) + x - y$

行/列の要素数の比が異なる場合

グループを作ることで対応できます。例えば列:行=2:1なら次のようにします。

[0] [1] [2] [3]
[0] 0, 1 2, 3 8, 9 18, 19
[1] 6, 7 4, 5 10, 11 20, 21
[2] 16, 17 14, 15 12, 13 22, 23
[3] 30, 31 28, 29 26, 27 24, 25
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?