0

こんにちは私は2D配列を使用してコンソール上にマトリックスを作成しようとしています。アイデアは、出力が次のようになるはずです:

1|8|9 |16
2|7|10|15
3|6|11|14
4|5|12|13

どうすればいいのか考えている人はいますか?

4

3 に答える 3

2

マトリックスから推測できることはほとんどありません: -

  • まず、次の列に移動する前に、最初に列のすべての行をトラバースする必要があります

  • downwards第二に、反復ごとにとupwards方向を交互に行う必要があります

  • そのため、特定の列の行を反復処理するには、入れ子になった for loop が 2 つ必要になります。1 つは からrow 0 to max - 1、次は から行きrow = max - 1 to 0ます。

  • ここで、反復方向を交互に切り替えるには、ブール変数を使用して、内側のループの反復が終了するたびに切り替えます。

  • 各ループは で囲む必要がありますif-else。どちらも特定の条件で実行されます。の場合boolean downwards = false;、上に移動するループが実行され、その逆も同様です。

  • 各反復で、現在のセルに整数カウンターを入力します。これは1、で初期化する必要があり、各入力後にインクリメントします。


疑似コード : -

    // Initialize variables row, col, and count = 1

    boolean goDown = true;

    int[][] matrix = new int[row][col];  // declare matrix

    for i = 0 to col:
        if (goDown)
            for j = 0 to row:  // Move in downwards direction
                assign count++ to matrix[j][i] 
                // assign to `[j][i]` because, we have to assign to rows first

            goDown = false;    // Toggle goDown

        else
            for j = row - 1 to 0:  // Move in upwards direction
                assign count++ to matrix[j][i] 

            goDown = true;  // toggle goDown

    }
于 2012-11-23T12:45:10.300 に答える
0

最後にあなたの助けを借りて、多次元配列がどのように機能するかを注意深く調べた後、私には非常に単純に見える問題を解決しました。

int a = 4;
    int b = 4;
    int c = 1;
    boolean direction = true;
    int[][] arrey = new int[a][b];
    for (int y = 0; y <= b - 1; y++) {
        if (direction) {
            for (int x = 0; x <= a - 1; x++) {
                arrey[x][y] = c;
                c++;
            }
            direction = false;
        } else {
            for (int x = a - 1; x >= 0; x--) {
                arrey[x][y] = c;
                c++;
            }
            direction = true;
        }
    }

    for (int x = 0; x <= a - 1; x++) {
        for (int y = 0; y <= b - 1; y++) {
            System.out.print("["+arrey[x][y]+"]");
        }
        System.out.println("");
    }
于 2012-11-25T12:04:21.363 に答える
0

いくつかの疑似コードです。それが役に立ち、何かを始めるきっかけになることを願っています。

boolean goUp = false;
boolean goDown = true;
size = 4;
matrix[size][size];
k = 0; 
l =0;

loop i->0 i < size*size i++
  matrix[l][k] = i;

  if(l==size and goDown)
    goDown = false;
    goUp = true;
    k++;
  else if(l==0 and goUp)
    goDown = true;
    goUp = false;
    k++;
  else
    l = l+ (1*goDown?1:-1);
end loop;
于 2012-11-23T12:44:36.653 に答える