C++で上部の対角線を下部と交換します
このチュートリアルは、c ++コードを使用して、3つの対角配列の上の行を下の行に交換するように設計されています。さらに、3対角配列が入力である場合、切望される結果は次のようなものでなければなりません。
このために、アクションのコースは次のようにアルゴリズムで簡単に説明されます;
アルゴリズム
Step-1: Input a diagonal array Step-2: Pass it to Swap() method Step-3: Traverse the outer loop till 3 Step-4: increment j= i+ 1 in the inner loop till 3 Step-5: put the array value in a temp variable Step-6: interchange the value arr[i][j]= arr[j][i] Step-7: put the temp data to arr[j][i] Step-8: Print using for loop
したがって、c ++コードは、前述のアルゴリズムに合わせて次のように作成されます。
例
#include <iostream>
#define n 3
using namespace std;
// Function to swap the diagonal
void swap(int arr[n][n]){
// Loop for swap the elements of matrix.
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
// Loop for print the matrix elements.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << arr[i][j] << " ";
cout << endl;
}
}
// Driver function to run the program
int main(){
int arr[n][n] = {
{ 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9},
};
cout<<"Input::"<<endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout << arr[i][j]<< " ";
cout << endl;
}
// Function call
cout<<"Output(Swaped)::"<<endl;
swap(arr);
return 0;
} 出力
以下の出力に見られるように、3D配列の下部セグメントとスワップされた上部の行は次のようになります;
Input:: 1 2 3 4 5 6 7 8 9 Output(Swaped):: 1 4 7 2 5 8 3 6 9
-
C++の対角トラバースII
numsというリストのリストがあるとすると、numsのすべての要素を対角線順に表示する必要があります。 したがって、入力が次のような場合 その場合、出力は[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]になります。 これを解決するには、次の手順に従います- 配列retを定義する 1つの2Dアレイvを定義する 初期化i:=0の場合、i
-
C ++でのMatrixのジグザグ(または対角)トラバーサル
この問題では、2D行列が与えられます。私たちの仕事は、マトリックのすべての要素を対角線の順序で印刷することです。 問題を理解するために例を見てみましょう 1 2 3 4 5 6 7 8 9 出力- 1 4 2 7 5 3 8 6 9 マトリックスをジグザグ形式または対角形式で印刷するときに従うパターンを見てみましょう。 こ