Latin Square in C++


The Latin square is a matrix that has a special pattern. Let's see different examples to examine the pattern.

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

The Latin square that you get will be of different size as you notice in the above examples. But, if you carefully observe the above matrices' pattern, you will find out that the last number of the previous row comes as the first element of the next row.

That's the pattern hidden in Latin square. We have to write the program that generates the above matrix for the input n.

Algorithm

  • Initialise the n with any number you like.
  • Initialise a number with the value n + 1 call it as first_half_end.
  • Write a loop that iterates from 1 to n both inclusive.
    • Assign the value of first_half_end to a variable called first_half_start.
    • Write a loop until first_half_start reaches to the value n.
      • Print the iterating variable i.e.., first_half_start.
    • Write a loop that iterates from 1 to first_half_end.
      • Print the iterating variable.
    • Decrement the value of first_half_end by 1.
    • Move the next row.

Implementation

Following is the implementation of the above algorithm in 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;
}

Output

If you run the above code, then you will get the following result.

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

Updated on: 21-Oct-2021

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements