Programa para invertir columnas en una array 2D dada (array)

Dada una array 2D arr[][] de enteros de tamaño M x N , donde N es el número de columnas y M es el número de filas en la array. La tarea es invertir cada columna de la array 2D dada.

Entrada: arr[][] =

{{3, 2, 1}

  {4, 5, 6},

  {9, 8, 7}}

Producción:

9 8 7

4 5 6

3 2 1

Entrada: arr[][] = 

{{7, 9}, 

  {15}, 

  {4, 6}, 

  {19, 3}}

Producción:

19 3

4 6

15

7 9

 

Enfoque:   para todas y cada una de las columnas de la array o array bidimensional dada, realice los siguientes pasos:

  • Inicialice el índice de inicio como 0 y el índice final como M – 1.
  • Iterar un ciclo for hasta que el índice inicial sea menor que el índice final, intercambiar el valor en estos índices y actualizar el índice como:
swap(arr[start][i], arr[end][i]);
start++;
end--;

A continuación se muestra la implementación del algoritmo anterior: 

C++

// C++ implementation of the
// above approach
#include <bits/stdc++.h>
using namespace std;
 
const int M = 3;
const int N = 3;
 
// A utility function
// for swapping two elements.
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
// Print the arr[][]
void printMatrix(int arr[M][N])
{
 
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++) {
            cout << arr[i][j] << ' ';
        }
        cout << endl;
    }
}
 
// Function to reverse
// the given 2D arr[][]
void reverseColumnArray(int arr[M][N])
{
 
    // Print the arr[][] before
    // reversing every column
    printMatrix(arr);
    cout << endl;
 
    // Traverse each column of arr[][]
    for (int i = 0; i < N; i++) {
        // Initialise start and end index
        int start = 0;
        int end = M - 1;
 
        // Till start < end, swap the
        // element at start and end index
        while (start < end) {
            // Swap the element
            swap(&arr[start][i], &arr[end][i]);
 
            // Increment start and decrement
            // end for next pair of swapping
            start++;
            end--;
        }
    }
 
    // Print the arr[][] after
    // reversing every column
    printMatrix(arr);
}
 
// Driver Code
int main()
{
    int arr[][3]
        = { { 3, 2, 1 }, { 4, 5, 6 }, { 9, 8, 7 } };
 
    // Function call
    reverseColumnArray(arr);
    return 0;
}

Java

// Java implementation of the
// above approach
import java.util.*;
class GFG{
 
  static int M = 3;
  static int N = 3;
 
  // A utility function
  // for swapping two elements.
  private static int[][] swap(int[][] arr, int start,
                              int i, int end, int j)
  {
 
    int temp = arr[start][i];
    arr[start][i] = arr[end][j];
    arr[end][j] = temp;
    return arr;
  }
 
  // Print the arr[][]
  static void printMatrix(int arr[][])
  {
 
    for (int i = 0; i < M; i++) {
      for (int j = 0; j < N; j++) {
        System.out.print(arr[i][j] +" ");
      }
      System.out.println();
    }
  }
 
  // Function to reverse
  // the given 2D arr[][]
  static void reverseColumnArray(int arr[][])
  {
 
    // Print the arr[][] before
    // reversing every column
    printMatrix(arr);
    System.out.println();
 
    // Traverse each column of arr[][]
    for (int i = 0; i < N; i++) {
      // Initialise start and end index
      int start = 0;
      int end = M - 1;
 
      // Till start < end, swap the
      // element at start and end index
      while (start < end)
      {
 
        // Swap the element
        arr = swap(arr,start,i,end,i);
 
        // Increment start and decrement
        // end for next pair of swapping
        start++;
        end--;
      }
    }
 
    // Print the arr[][] after
    // reversing every column
    printMatrix(arr);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int arr[][]
      = { { 3, 2, 1 }, { 4, 5, 6 }, { 9, 8, 7 } };
 
    // Function call
    reverseColumnArray(arr);
  }
}
 
// This code is contributed by 29AjayKumar

Python3

# python implementation of the
# above approach
M = 3
N = 3
 
# Print the arr[][]
def printMatrix(arr):
 
    for i in range(0, M):
        for j in range(0, N):
            print(arr[i][j], end=' ')
 
        print()
 
# Function to reverse
# the given 2D arr[][]
def reverseColumnArray(arr):
 
    # Print the arr[][] before
    # reversing every column
    printMatrix(arr)
    print()
 
    # Traverse each column of arr[][]
    for i in range(0, N):
        # Initialise start and end index
        start = 0
        end = M - 1
 
        # Till start < end, swap the
        # element at start and end index
        while (start < end):
            # Swap the element
            temp = arr[start][i]
            arr[start][i] = arr[end][i]
            arr[end][i] = temp
 
            # Increment start and decrement
            # end for next pair of swapping
            start += 1
            end -= 1
 
        # Print the arr[][] after
        # reversing every column
    printMatrix(arr)
 
# Driver Code
if __name__ == "__main__":
 
    arr = [[3, 2, 1], [4, 5, 6], [9, 8, 7]]
 
    # Function call
    reverseColumnArray(arr)
 
    # This code is contributed by rakeshsahni

C#

// C# implementation of the
// above approach
using System;
class GFG
{
 
    static int M = 3;
    static int N = 3;
 
    // A utility function
    // for swapping two elements.
    private static int[,] swap(int[,] arr, int start,
                                int i, int end, int j)
    {
 
        int temp = arr[start, i];
        arr[start, i] = arr[end, j];
        arr[end, j] = temp;
        return arr;
    }
 
    // Print the arr[][]
    static void printMatrix(int[,] arr)
    {
 
        for (int i = 0; i < M; i++)
        {
            for (int j = 0; j < N; j++)
            {
                Console.Write(arr[i, j] + " ");
            }
            Console.WriteLine("");
        }
    }
 
    // Function to reverse
    // the given 2D arr[][]
    static void reverseColumnArray(int[,] arr)
    {
 
        // Print the arr[][] before
        // reversing every column
        printMatrix(arr);
        Console.WriteLine();
 
        // Traverse each column of arr[][]
        for (int i = 0; i < N; i++)
        {
            // Initialise start and end index
            int start = 0;
            int end = M - 1;
 
            // Till start < end, swap the
            // element at start and end index
            while (start < end)
            {
 
                // Swap the element
                arr = swap(arr, start, i, end, i);
 
                // Increment start and decrement
                // end for next pair of swapping
                start++;
                end--;
            }
        }
 
        // Print the arr[][] after
        // reversing every column
        printMatrix(arr);
    }
 
    // Driver Code
    public static void Main()
    {
        int[,] arr = { { 3, 2, 1 }, { 4, 5, 6 }, { 9, 8, 7 } };
 
        // Function call
        reverseColumnArray(arr);
    }
}
 
// This code is contributed by Saurabh Jaiswal

Javascript

<script>
   // JavaScript code for the above approach
   let M = 3;
   let N = 3;
 
   // Print the arr[][]
   function printMatrix(arr) {
 
     for (let i = 0; i < M; i++) {
       for (let j = 0; j < N; j++) {
         document.write(arr[i][j] + ' ');
       }
       document.write('<br>')
     }
   }
 
   // Function to reverse
   // the given 2D arr[][]
   function reverseColumnArray(arr) {
 
     // Print the arr[][] before
     // reversing every column
     printMatrix(arr);
     document.write('<br>')
 
     // Traverse each column of arr[][]
     for (let i = 0; i < N; i++)
     {
      
       // Initialise start and end index
       let start = 0;
       let end = M - 1;
 
       // Till start < end, swap the
       // element at start and end index
       while (start < end)
       {
        
         // Swap the element
         let temp = arr[start][i]
         arr[start][i] = arr[end][i]
         arr[end][i] = temp
 
         // Increment start and decrement
         // end for next pair of swapping
         start++;
         end--;
       }
     }
 
     // Print the arr[][] after
     // reversing every column
     printMatrix(arr);
   }
 
   // Driver Code
   let arr
     = [[3, 2, 1], [4, 5, 6], [9, 8, 7]];
 
   // Function call
   reverseColumnArray(arr);
 
 // This code is contributed by Potta Lokesh
 </script>
Producción

3 2 1 
4 5 6 
9 8 7 

9 8 7 
4 5 6 
3 2 1 

Complejidad de tiempo: O(N 2 ), se utilizan dos bucles for, uno para iterar sobre todas las columnas y el bucle interno intercambia el índice inicial y final de cada columna.
Complejidad auxiliar: 0(1) ya que no hay espacio adicional, ni siquiera para intercambiar los dos elementos.

Publicación traducida automáticamente

Artículo escrito por pintusaini y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *