Latin Square in Python

PythonServer Side ProgrammingProgramming

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 Python

def generateLatinSquare(n):
   first_half_end = n + 1

   for i in range(1, n + 1):
      first_half_start = first_half_end
      while (first_half_start <= n):
         print(first_half_start, end=" ")
         first_half_start += 1

      for second_half_start in range(1, first_half_end):
         print(second_half_start, end=" ")
      first_half_end -= 1
      print()
   print()

if __name__ == "__main__":
   generateLatinSquare(2)
   generateLatinSquare(3)
   generateLatinSquare(4)

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
raja
Updated on 21-Oct-2021 09:37:38

Advertisements