Java >> Tutoriel Java >  >> Java

Programme Java pour échanger deux lignes et colonnes dans la matrice donnée

Dans ce didacticiel, nous allons apprendre à échanger deux lignes et colonnes dans la matrice donnée. Mais avant d'aller plus loin, si vous n'êtes pas familier avec les concepts du tableau, alors consultez l'article Tableaux en Java.

Vous trouverez ci-dessous la représentation graphique de l'échange de deux lignes et colonnes dans la matrice donnée.

Entrée : Saisissez la matrice :

1 2 3

4 5 6

7 8 9

Sortie : Après avoir interchangé les lignes :2 et 3

1 2 3

7 8 9

4 5 6

Après avoir interverti les colonnes :1 et 3

3 2 1

9 8 7

6 5 4

Programme 1 :Intervertir deux lignes et colonnes

Dans ce programme, nous verrons comment échanger deux lignes et colonnes dans la matrice donnée lorsque les valeurs sont définies par l'utilisateur.

Algorithme

  1. Commencer
  2. Déclarez des variables pour la taille des lignes et des colonnes.
  3. Demandez à l'utilisateur d'initialiser le nombre de lignes et de colonnes.
  4. Déclarez une matrice de cette taille.
  5. Demandez à l'utilisateur d'initialiser la matrice.
  6. Imprimez la matrice originale.
  7. Utilisez une boucle while pour vérifier si l'utilisateur souhaite échanger les lignes ou les colonnes ou aucune.
  8. Utilisez des boucles pour échanger respectivement les lignes et les colonnes.
  9. Demandez à l'utilisateur quelles sont les deux lignes ou colonnes qu'il souhaite échanger.
  10. En fonction de cela, échangez les éléments de lignes ou de colonnes.
  11. Afficher le résultat.
  12. Arrêter

Vous trouverez ci-dessous le code correspondant.

/*Java Program to interchange any two rows and columns in the given matrix*/
import java.util.Scanner;
public class Main 
{
    public static void main(String[] args) 
    {
        int m,n;   //Declare the variables for rows and columns

        //Take input from the user
        Scanner sc = new Scanner(System.in);
        
        System.out.print("Enter number of rows in matrix:");
        m = sc.nextInt();  //Initialize the number of rows

        System.out.print("Enter number of columns in matrix:");
        n = sc.nextInt();  //Initialize the number of columns
 
        int arr[][] = new int[m][n];  //Declare a Matrix
        System.out.println("Enter all the elements of matrix:");
        for (int i = 0; i < m; i++) 
        {
            for (int j = 0; j < n; j++) 
            {
                arr[i][j] = sc.nextInt();
            }
        }

       //Print the original matrix
        System.out.println("The Original Matrix:");
        for (int i = 0; i < m; i++) 
        {
            for (int j = 0; j < n; j++) 
            {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println("");
        }

        //Check whether user want to interchange rows or columns
        while (true) 
        {
            System.out.println("Enter 1 to interchange rows");
            System.out.println("Enter 2 to interchange columns");
            System.out.println("Enter 3 to Exit");
            int n1=sc.nextInt();
            switch (n1) 
            {
                case 1:
                //Enter the rows whose datas you want to interchange 
                System.out.println("Enter the row numbers:");
                int x = sc.nextInt();   
                int y = sc.nextInt();
                int temp=0;
                for(int i = 0; i < m; i++)
                {
                    temp = arr[(x-1)][i];
                    arr[x-1][i] = arr[y-1][i];
                    arr[y-1][i] = temp;
                }
                //Print the matrix after interchanging elements
                System.out.println("Matrix after interchanging rows:"+x +" and "+y);
                for (int i = 0; i < m; i++) 
                {
                    for (int j = 0; j < n; j++) 
                    {
                        System.out.print(arr[i][j] + " ");
                    }
                System.out.println("");
                }
                break;
                case 2:
                //Enter the columns whose datas you want to interchange 
                System.out.println("Enter the column numbers:");
                int p = sc.nextInt();
                int q = sc.nextInt();
                int temp1=0;
                for(int i = 0; i < p; i++)
                {
                    temp1 = arr[i][(p-1)];
                    arr[i][p-1] = arr[i][(q-1)];
                    arr[i][q-1] = temp1;
                }
                //Print the matrix after interchanging elements
                System.out.println("Matrix after interchanging columns:"+p +" and "+q);
                for (int i = 0; i < m; i++) 
                {
                    for (int j = 0; j < n; j++) 
                    {
                        System.out.print(arr[i][j] + " ");
                    }
                System.out.println("");
                }
                break;
          	case 3:
                //Exit from the program
                System.exit(0);
            }
        }
    }
}


Entrez le nombre de lignes dans la matrice :3
Entrez le nombre de colonnes dans la matrice :3
Entrez tous les éléments de la matrice :1 2 3 4 5 6 7 8 9
L'original Matrice :
1 2 3
4 5 6
7 8 9
Entrez 1 pour échanger les lignes
Entrez 2 pour échanger les colonnes
Entrez 3 pour quitter
1
Entrez les numéros de lignes :3 2
Matrice après inversion des lignes :3 et 2
1 2 3
7 8 9
4 5 6
Entrez 1 pour échanger les lignes
Entrez 2 pour échanger les colonnes
Entrez 3 pour quitter
2
Entrez les numéros de colonne :1 3
Matrice après l'échange des colonnes :1 et 3
3 2 1
7 8 9
4 5 6
Entrez 1 pour échanger les lignes
Entrez 2 pour échanger les colonnes
Entrez 3 pour Quitter
3

Programme 2 :Pour échanger deux lignes et colonnes quelconques

Dans ce programme, nous verrons comment échanger deux lignes et colonnes dans la matrice donnée lorsque les valeurs sont prédéfinies.

Algorithme

  1. Commencer
  2. Déclarez et initialisez la matrice.
  3. Imprimez la matrice d'origine.
  4. Entrez les colonnes à échanger.
  5. Appelez la méthode pour échanger les colonnes.
  6. Échangez les chiffres pour échanger les colonnes.
  7. Imprimez la matrice après avoir interverti les colonnes.
  8. Maintenant, appelez une méthode pour échanger les lignes.
  9. Échangez les nombres pour échanger les lignes.
  10. Imprimez la matrice après avoir interchangé les lignes.
  11. Arrêtez.

Vous trouverez ci-dessous le code correspondant.

/*Java Program to interchange any two rows and columns*/
import java.io.*; 
  
public class Main 
{
    //To Print the arr
    public static void printMatrix(int[][] arr) 
    { 
        for (int i = 0; i < arr.length; i++) { 
            for (int j = 0; j < arr[0].length; j++) 
                System.out.print(arr[i][j] + " "); 
            System.out.println(); 
        } 
    } 
    
    //To Interchange Columns  
    public static void interchangeColumns(int[][] arr, 
                                             int K, int L) 
    { 
        for (int i = 0; i < arr.length; i++) { 
  
            // Swap two numbers 
            int temp = arr[i][K - 1]; 
            arr[i][K - 1] = arr[i][L - 1]; 
            arr[i][L - 1] = temp; 
        } 
        System.out.println("After Interchanging Column "+ K + " and "+ L+ " :");
        // Print arr 
        printMatrix(arr); 
    } 
    
    //To Interchange Rows  
    public static void interchangeRows(int[][] arr, int x, int y) 
    { 
        for (int i = 0; i < arr[0].length; i++) { 
            
            // Swap two numbers 
            int temp = arr[x - 1][i]; 
            arr[x - 1][i] = arr[y - 1][i]; 
            arr[y - 1][i] = temp; 
        } 
        System.out.println("After Interchanging Row "+ x + " and "+ y + " :");
        // Print arr 
        printMatrix(arr); 
    } 
    
    
      
    // Driver code 
    public static void main(String args[]) throws IOException 
    { 
        int arr[][] 
            = { { 2, 9, 8 }, { 7, 6, 4 }, { 3, 9, 2 } };  //Matrix Declaration and Initialization
            
        //Print Original arr    
        System.out.println("Original arr: ");
        printMatrix(arr); 
        
        // calling to exchange Columns
        int K = 1, L = 2; 
        interchangeColumns(arr, K, L); 
        
        // calling to exchange Rows
         int K1 = 1, L1 = 2; 
        interchangeRows(arr, K1, L1); 
          
        
    } 
} 


Original arr :
2 9 8
7 6 4
3 9 2
Après avoir interverti les colonnes 1 et 2 :
9 2 8
6 7 4
9 3 2
Après avoir interverti les lignes 1 et 2 :
6 7 4
9 2 8
9 3 2


Balise Java