This blog is under construction

Sunday, 28 July 2013

C program to implement latin square using arrays

Write a C program to implement Latin square using arrays.
Latin square is a square matrix of order n.  And it is filled with n different symbols, each symbol occurs only once in each row and only once in each column.

Implement Latin square with the symbols {1, 2, 3}

Number of symbols in the given array is 3.  So, we need 3 X 3 matrix to implement Latin square. First,  fill the square matrix with zeros.
0  0  0
0  0  0
0  0  0

Rotate the given symbol array left by 1 places and store the result in the first row of the above square matrix.
2  3  1
0  0  0
0  0  0

Rotate the given symbol array left by 2 places and store the result in the second row of the square matrix.
2  3  1
3  1  2
0  0  0

Rotate the given symbol array left by 3 places and store the result in the third row of the square matrix.
2  3  1
3  1  2
1  2  3

Finally, we have implemented Latin square.



  #include <stdio.h>
  #define ROW 10
  #define COL 10

  /* rotates the given input array left by "shift" places */
  void rotateArray(int data[], int n, int shift) {
        int i, j, tmp;
        for (i = 0; i < shift; i++) {
                tmp = data[0];
                for (j = 1; j <= n - 1; j++) {
                        data[j - 1] = data[j];
                }
                data[n - 1] = tmp;
        }
        return;
  }

  int main() {
        int lsquare[ROW][COL], data[COL];
        int i, j, n;

        /* get the number of entries for the input array */
        printf("Enter the number of entries:");
        scanf("%d", &n);

        /* get the entries for the input arra */
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ", i);
                scanf("%d", &data[i]);
        }

        /* fill the given symbols in each row */
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        lsquare[i][j] = data[j];
                }
        }

        /* rotate data in each row by i places */
        for (i = 0; i < n; i++) {
                rotateArray(&lsquare[i][0], n, i);
        }

        /* print the result */
        printf("\nLatin Square:\n");
        for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                        printf("%d ", lsquare[i][j]);
                }
                printf("\n");
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of entries:5
  Data[0]: 1
  Data[1]: 2
  Data[2]: 3
  Data[3]: 4 
  Data[4]: 5

  Latin Square:
  1 2 3 4 5 
  2 3 4 5 1 
  3 4 5 1 2 
  4 5 1 2 3 
  5 1 2 3 4 


1 comment: