Advertisement
Guest User

saunderl

a guest
Dec 1st, 2008
525
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3.  
  4. class LatinSquare
  5. {
  6.     static void Main()
  7.     {
  8.         var LatinSquare = new int[9, 9];
  9.         var Pattern = new int[] {1,2,3,4,5,6,7,8,9};
  10.  
  11.         Pattern = Shuffle(Pattern);
  12.        
  13.         //Use the first row as a pattern for the rest
  14.         //of the Latin Square
  15.         for (int i = 0; i < 9; i++)
  16.         {
  17.             {LatinSquare[i,0] = Pattern[i];
  18.         }
  19.            
  20.         for (int x = 0; x < 9; x++)
  21.         {
  22.             for (int y = 1; y < 9; y++)
  23.             {
  24.                 LatinSquare[Pattern[y] - 1, y] =
  25.                     LatinSquare[LatinSquare[x, 0] - 1, 0];
  26.             }
  27.  
  28.             Pattern = RotatePattern(Pattern);
  29.         }
  30.  
  31.         PrintLatinSquare(LatinSquare);
  32.  
  33.         Console.Read();
  34.     }
  35.  
  36.     private static T[] Shuffle<T>(T[] OriginalArray)
  37.     {
  38.         var matrix = new SortedList();
  39.         var r = new Random();
  40.  
  41.         for (int x = 0; x <= OriginalArray.GetUpperBound(0); x++)
  42.         {
  43.             int i = r.Next();
  44.  
  45.             if (!matrix.ContainsKey(i))
  46.             {
  47.                 matrix.Add(i, OriginalArray[x]);
  48.             }
  49.         }
  50.  
  51.         var OutputArray = new T[OriginalArray.Length];
  52.  
  53.         var counter = 0;
  54.         foreach (DictionaryEntry entry in matrix)
  55.         {
  56.             OutputArray[counter++] = (T)entry.Value;
  57.         }
  58.  
  59.         return OutputArray;
  60.     }
  61.  
  62.     private static int[] RotatePattern(int[] Pattern)
  63.     {
  64.         int temp = Pattern[0];
  65.  
  66.         ;for (int y = 0; y < 9 - 1; y++)
  67.         {
  68.             Pattern[y] = Pattern[y + 1];
  69.         }
  70.  
  71.         Pattern[9 - 1] = temp;
  72.  
  73.         return Pattern;
  74.     }
  75.  
  76.     private static void PrintLatinSquare(int[,] LatinSquare)
  77.     {
  78.         //Print out the Latin Square
  79.         for (int i = 0; i < 9; i++)
  80.         {
  81.             for (int j = 0; j < 9; j++)
  82.             {
  83.                 Console.Write(LatinSquare[j, i].ToString().PadLeft(3));
  84.             }
  85.             Console.WriteLine();
  86.         }
  87.     }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement