2020年2月20日木曜日

二次元配列の横順を縦順にする

あまプロではアプリ開発をお受けする事が有ります。

先日、二次元配列を横順から縦順に変換する機能を実装したのであメログ。
<!doctype html>
<html lang="ja">
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <title>二次元配列縦横入換</title>
        <script type="text/javascript">
            let array = [
                [ 1,  2,  3,  4],
                [ 5,  6,  7,  8],
                [ 9, 10, 11, 12]
            ];
            let rowLength = array.length;
            let colLength = array[ 0].length;
            console.log( '横順');
            for( let row = 0; row < rowLength; row++)
            {
                let line = '';
                for( let col = 0; col < colLength; col++)
                {
                    line += array[ row][ col] + ', ';
                }
                console.log( line);
            }
            console.log( '\n縦順');
            for( let row = 0; row < rowLength; row++)
            {
                let line = '';
                for( let col = 0; col < colLength; col++)
                {
                    line +=
                        array[ parseInt( ( rowLength * col + row) / colLength)]
                            [ ( col * rowLength % colLength + row) % colLength] +
                        ', ';
                }
                console.log( line);
            }
        </script>
    </head>
    <body>
    </body>
</html>
JavaScriptやとこんな感じ。
他の言語の場合は適宜方言を脳内変換して下さい。

二次元配列を出力すると通常左上から始めます。
これを右上、左下、右下から始める方法もあります。
これらを組み合わせると結構楽しく二次元配列で遊べます。