5

質問: 整数 n が与えられた場合、次のように 1 から n 2までの数値を出力します。

n = 4

結果は次のとおりです。

01 02 03 04
12 13 14 05
11 16 15 06
10 09 08 07

どのように解決しますか (以下のリンクで提供されている解決策とは別に)?

http://www.programmersheaven.com/mb/CandCPP/81986/81986/problem-in-making-ap-c++-program/?S=B20000

私は別の方向を見ています。これまでのところ、私が記入しなければならないポジションの順序付きリストを取得できるかどうかを調べようとしています.

これが私が調べていることです:行列を「歩く」のではなく、そのように問題を解決するために「fdisp」を取得する方法はありますか?

matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
n = len(matrix)

# final disposition wrote by hand: how to get it for arbitrary n?
fdisp = [(0,0), (0,1), (0,2), (0,3), (1,3), (2,3), (3,3), (3,2),
         (3,1), (3,0), (2,0), (1,0), (1,1), (1,2), (2,2), (2,1)]

for val,i in enumerate(fdisp):
    matrix[i[0]][i[1]] = val + 1

def show_matrix(matrix, n):
    for i,l in enumerate(matrix):
        for j in range(n):
            print "%d\t" % matrix[i][j],
        print

show_matrix(matrix, n)
4

5 に答える 5

5

ここに別のアプローチがあります。右、下、左、上、右、... の間で循環する動きを見つけることに依存しています。さらに、移動する回数は次のようになります: 右 3 回、下 3 回、左 3 回、上 2 回、右 2 回、下に 1 つ、左に 1 つ。したがって、これ以上苦労することなく、これを Python でコーディングします。

最初に、いくつかの itertools といくつかの numpy を使用します。

from itertools import chain, cycle, imap, izip, repeat
from numpy import array

方向は次のように循環します: 右、下、左、上、右、...:

directions = cycle(array(v) for v in ((0,1),(1,0),(0,-1),(-1,0)))

(ここでは numpy の配列を使用しているため、方向を簡単に追加できます。タプルはうまく追加されません。)

次に、移動回数が n-1 から 1 までカウントダウンされ、各数値が 2 回繰り返され、最初の数値が 3 回繰り返されます。

countdown = chain((n-1,), *imap(repeat, range(n-1,0,-1), repeat(2)))

したがって、一連の方向は、カウントダウンでペアになった数だけ連続する方向を繰り返すことで作成できます。

dirseq = chain(*imap(repeat, directions, countdown))

インデックスのシーケンスを取得するには、このシーケンスを合計するだけですが、(AFAIK) Python はそのようなメソッドを提供していないため、簡単にまとめてみましょう。

def sumseq(seq, start=0):
  v = start
  yield v
  for s in seq:
    v += s
    yield v

元の配列を生成するには、次のようにします。

a = array(((0,)*n,)*n) # n-by-n array of zeroes
for i, v in enumerate(sumseq(dirseq, array((0,0)))):
  a[v[0], v[1]] = i+1
print a

n = 4 の場合、次のようになります。

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

n = 5 の場合、次のようになります。

[[ 1  2  3  4  5]
 [16 17 18 19  6]
 [15 24 25 20  7]
 [14 23 22 21  8]
 [13 12 11 10  9]]

このアプローチは、長方形のグリッドに一般化できます。これは読者の演習として残しておきます ;)

于 2009-07-24T13:46:31.387 に答える
2

あなたの例はpythonであり、これはJavaですが、ロジックに従うことができるはずです:

public class SquareTest {

public static void main(String[] args) {
    SquareTest squareTest = new SquareTest(4);
    System.out.println(squareTest);
}

private int squareSize;
private int[][] numberSquare;
private int currentX;
private int currentY;
private Direction currentDirection;

private enum Direction {
    LEFT_TO_RIGHT, RIGHT_TO_LEFT, TOP_TO_BOTTOM, BOTTOM_TO_TOP;
};

public SquareTest(int squareSize) {
    this.squareSize = squareSize;
    numberSquare = new int[squareSize][squareSize];
    currentY = 0;
    currentX = 0;
    currentDirection = Direction.LEFT_TO_RIGHT;
    constructSquare();
}

private void constructSquare() {
    for (int i = 0; i < squareSize * squareSize; i = i + 1) {
        numberSquare[currentY][currentX] = i + 1;
        if (Direction.LEFT_TO_RIGHT.equals(currentDirection)) {
            travelLeftToRight();
        } else if (Direction.RIGHT_TO_LEFT.equals(currentDirection)) {
            travelRightToLeft();
        } else if (Direction.TOP_TO_BOTTOM.equals(currentDirection)) {
            travelTopToBottom();
        } else {
            travelBottomToTop();
        }
    }
}

private void travelLeftToRight() {
    if (currentX + 1 == squareSize || numberSquare[currentY][currentX + 1] != 0) {
        currentY = currentY + 1;
        currentDirection = Direction.TOP_TO_BOTTOM;
    } else {
        currentX = currentX + 1;
    }
}

private void travelRightToLeft() {
    if (currentX - 1 < 0 || numberSquare[currentY][currentX - 1] != 0) {
        currentY = currentY - 1;
        currentDirection = Direction.BOTTOM_TO_TOP;
    } else {
        currentX = currentX - 1;
    }
}

private void travelTopToBottom() {
    if (currentY + 1 == squareSize || numberSquare[currentY + 1][currentX] != 0) {
        currentX = currentX - 1;
        currentDirection = Direction.RIGHT_TO_LEFT;
    } else {
        currentY = currentY + 1;
    }
}

private void travelBottomToTop() {
    if (currentY - 1 < 0 || numberSquare[currentY - 1][currentX] != 0) {
        currentX = currentX + 1;
        currentDirection = Direction.LEFT_TO_RIGHT;
    } else {
        currentY = currentY - 1;
    }
}

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < squareSize; i = i + 1) {
        for (int j = 0; j < squareSize; j = j + 1) {
            builder.append(numberSquare[i][j]);
            builder.append(" ");
        }
        builder.append("\n");
    }

    return builder.toString();
}
}
于 2009-07-23T21:04:08.713 に答える
2

これを行う別の方法として、今回は C# を使用します。

int number = 9;
var position = new { x = -1, y = 0 };
var directions = new [] { 
    new { x = 1, y = 0 },
    new { x = 0, y = 1 },
    new { x = -1, y = 0 },
    new { x = 0, y = -1 }
};

var sequence = (
    from n in Enumerable.Range(1, number)
    from o in Enumerable.Repeat(n, n != number ? 2 : 1)
    select o
).Reverse().ToList();

var result = new int[number,number];

for (int i = 0, current = 1; i < sequence.Count; i++)
{
    var direction = directions[i % directions.Length];      

    for (int j = 0; j < sequence[i]; j++, current++)
    {
        position = new {
            x = position.x + direction.x,
            y = position.y + direction.y
        };

        result[position.y, position.x] = current;
    }
}
于 2009-07-23T21:18:44.177 に答える
1

私は方法を発見しました。特に、「fdisp」を構築するためのよりクリーンな方法を見つける必要があります。n = 5

dim = n
pos = (0, -1)
fdisp = []
squares = n % 2 == 0 and n / 2 or n / 2 + 1

for _ in range(squares):
    pos = (pos[0], pos[1] + 1)
    fdisp.append(pos)

    fdisp += [(pos[0],pos[1]+i) for i in range(1, dim)]
    pos = fdisp[-1]
    fdisp += [(pos[0]+i,pos[1]) for i in range(1, dim)]
    pos = fdisp[-1]
    fdisp += [(pos[0],pos[1]-i) for i in range(1, dim)]
    pos = fdisp[-1]
    fdisp += [(pos[0]-i,pos[1]) for i in range(1, dim - 1)]
    pos = fdisp[-1]
    dim = dim - 2

matrix = [[0] * n for i in range(n)]

for val,i in enumerate(fdisp):
    matrix[i[0]][i[1]] = val + 1

def show_matrix(matrix, n):
    for i,l in enumerate(matrix):
        for j in range(n):
            print "%d\t" % matrix[i][j],
        print

show_matrix(matrix, n)
于 2009-07-24T10:22:53.583 に答える