在 C++ 中的拉丁方陣


拉丁方陣是一個具有特殊模式的矩陣。我們來看幾個不同的例子來檢驗一下這個模式。

1 2
2 1

1 2 3
3 1 2
2 3 1

1 2 3 4
4 1 2 3
3 4 1 2
2 3 4 1

你從上面幾個例子中會發現,得到的拉丁方陣具有不同的尺寸。但是,如果你仔細觀察這些矩陣的模式,你會發現前一行的最後一個數字會成為下一行中的第一個元素。

這就是拉丁方陣隱藏的模式。我們必須編寫一個程式,根據輸入n生成上述矩陣。

演算法

  • 使用任何你喜歡的數字初始化n。
  • 使用值n + 1 初始化一個數字,稱之為first_half_end。
  • 編寫一個迴圈,從1到n(包括兩者)進行迭代。
    • 將first_half_end的值賦給一個名為first_half_start的變數。
    • 編寫一個迴圈,直到first_half_start的值達到n。
      • 列印迭代變數,即first_half_start。
    • 編寫一個迴圈,從1到first_half_end進行迭代。
      • 列印迭代變數。
    • 將first_half_end的值減1。
    • 移到下一行。

實現

以下是該演算法在 C++ 中的實現

#include <bits/stdc++.h>

using namespace std;

void generateLatinSquare(int n) {
   int first_half_end = n + 1;

   for (int i = 1; i <= n; i++) {
      int first_half_start = first_half_end;
      while (first_half_start <= n) {
         cout << first_half_start << " ";
         first_half_start++;
      }

      for (int second_half_start = 1; second_half_start < first_half_end; second_half_start++){
         cout << second_half_start << " ";
      }
      first_half_end--;
   cout << endl;
   }
   cout << endl;
}

int main(void) {
   generateLatinSquare(2);
   generateLatinSquare(3);
   generateLatinSquare(4);
   return 0;
}

輸出

如果你執行上面的程式碼,你將得到以下結果。

1 2
2 1

1 2 3
3 1 2
2 3 1

1 2 3 4
4 1 2 3
3 4 1 2
2 3 4 1

更新於: 2021-10-21

437 次瀏覽

開啟你的 職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.