Latin Square in Python

A Latin square is a square matrix where each row and column contains every number from 1 to n exactly once. Let's examine the pattern in different sized Latin squares.

Understanding the Pattern

Here are examples of Latin squares of different sizes ?

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 key pattern is: the last number of the previous row becomes the first element of the next row. This creates a cyclic shift pattern where each row is a rotation of the previous row.

Algorithm

The algorithm to generate a Latin square follows these steps ?

  • Initialize n with the desired square size
  • Set first_half_end = n + 1 to track the starting point
  • For each row (1 to n):
    • Set first_half_start = first_half_end
    • Print numbers from first_half_start to n
    • Print numbers from 1 to first_half_end - 1
    • Decrement first_half_end by 1

Implementation

Here's the Python implementation that generates Latin squares ?

def generateLatinSquare(n):
    first_half_end = n + 1
    
    for i in range(1, n + 1):
        first_half_start = first_half_end
        
        # Print numbers from first_half_start to n
        while (first_half_start <= n):
            print(first_half_start, end=" ")
            first_half_start += 1
        
        # Print numbers from 1 to first_half_end - 1
        for second_half_start in range(1, first_half_end):
            print(second_half_start, end=" ")
        
        first_half_end -= 1
        print()  # New line after each row
    
    print()  # Empty line after each square

# Generate Latin squares of different sizes
generateLatinSquare(2)
generateLatinSquare(3)
generateLatinSquare(4)

The output demonstrates Latin squares of sizes 2×2, 3×3, and 4×4 ?

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 

How It Works

The algorithm works by maintaining a starting position for each row. For the first row, we start from 1. For subsequent rows, we start from the position that follows the last element of the previous row, creating the cyclic shift pattern characteristic of Latin squares.

Conclusion

Latin squares are mathematical structures where each number appears exactly once in every row and column. The cyclic shift pattern makes them useful in experimental design and combinatorics.

Updated on: 2026-03-25T10:28:16+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements