SoundChaos
SoundChaos

Reputation: 307

Flipping an array by both diagonals

I am looking to figure out how to flip an array by both of its diagonals by passing it into a method. I've got it so I can flip it by each diagonal on its own, but I can't work out how to get it to do both in one go.

Here is the array flipped by its main diagonal:

static int[,] flipDiag(int[,] originArray, int size)
{
    int[,] flippedArray = new int [size, size];


    for (int row = 0; row < size; row++)
    {
        for (int col = 0; col < size; col++)
        {
            flippedArray[row, col] = originArray[col, row];
        } 
    }

    return flippedArray;
}

And here is the loop that flips it by the other diagonal:

for (int row = 0; row < size; row++)
{
    for (int col = 0; col < size; col++)
    {
        flippedArray[row, col] = originArray[(size-1) - col, (size-1) - row];
    } 
}

Is there a way to do both of these actions so that an array structured like:

1 2 3
4 5 6
7 8 9

would output to:

1 8 3
6 5 4
7 2 9

If so, would it have to be done with some form of temp variable or temp array using two seperate loops?

Upvotes: 2

Views: 1525

Answers (1)

Martin Heraleck&#253;
Martin Heraleck&#253;

Reputation: 5779

If I understand correctly, this code is what you want: (I used letters for beter readability.)

char[,] array =
{
    { 'A', 'B', 'C', 'D', 'E' },
    { 'F', 'G', 'H', 'I', 'J' },
    { 'K', 'L', 'M', 'N', 'O' },
    { 'P', 'Q', 'R', 'S', 'T' },
    { 'U', 'V', 'W', 'X', 'Y' },
};

char[,] flippedArray = (char[,])array.Clone();

for (int row = 0; row < 5; row++)
{
    for (int col = 0; col < 5; col++)
    {
        // wheter this isn't diagonal
        if (row != col && row + col != 4)
            flippedArray[row, col] = array[4 - row, 4 - col];
    }
}

It gives this output:

A X W V E
T G R I P
O N M L K
J Q H S F
U D C B Y

Of course, replace those 5s and 4s with corresponding size of array.

Upvotes: 2

Related Questions