Advertisement
Guest User

Untitled

a guest
Oct 29th, 2014
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.99 KB | None | 0 0
  1. module dmain;
  2.  
  3. import std.stdio;
  4. import std.file;
  5. import std.string;
  6. import std.typecons;
  7.  
  8. /*
  9.  * This program computes graph coloring and chromatic number,
  10.  * taking adjacency matrix as input
  11.  */
  12.  
  13. int[][] readAdjacencyMatrix(string text)
  14. {
  15.     int[][] res;
  16.     foreach(line; text.splitLines)
  17.     {
  18.         int[] row;
  19.         foreach(c; line)
  20.         {
  21.             if (c == '1')
  22.                 row ~= 1;
  23.             else if (c == '0')
  24.                 row ~= 0;
  25.         }
  26.         res ~= row;
  27.     }
  28.     return res;
  29. }
  30.  
  31. bool isValidAdjacencyMatrix(int[][] matrix)
  32. {
  33.     size_t n = matrix.length;
  34.     foreach(row; matrix)
  35.         if (row.length != n)
  36.             return false;
  37.     return true;
  38. }
  39.  
  40. void binaryAddRows(int[][] matrix, size_t a, size_t b, size_t dest)
  41. {
  42.     for (size_t i = 0; i < matrix.length; i++)
  43.     {
  44.         matrix[dest][i] = matrix[a][i] || matrix[b][i];
  45.     }
  46. }
  47.  
  48. Tuple!(int, int[]) coloring(int[][] matrix)
  49. {
  50.     int colors = 0;
  51.     int[] p = new int[matrix.length];
  52.  
  53.     for (size_t i = 0; i < matrix.length; i++)
  54.     {
  55.         if (p[i] == 0)
  56.         {
  57.             for (size_t j = 0; j < matrix.length; j++)
  58.             {
  59.                 if (matrix[i][j] == 0)
  60.                 {
  61.                     if (p[j] == 0)
  62.                     {
  63.                         binaryAddRows(matrix, i, j, i);
  64.                         p[j] = colors+1;
  65.                     }
  66.                 }
  67.             }
  68.  
  69.             p[i] = colors+1;
  70.             colors++;
  71.         }
  72.     }
  73.  
  74.     return tuple(colors, p);
  75. }
  76.  
  77. void main(string[] args)
  78. {
  79.     assert(args.length > 1, "No input file provided");
  80.  
  81.     int[][] matrix = readAdjacencyMatrix(readText(args[1]));
  82.     assert(isValidAdjacencyMatrix(matrix), "Invalid input, matrix is not square");
  83.  
  84.     writeln("Adjacency matrix:");
  85.     foreach(row; matrix)
  86.         writeln(row);
  87.     writeln();
  88.  
  89.     auto c = coloring(matrix);
  90.     writefln("Chromatic number = %s", c[0]);
  91.     writefln("Colors = %s", c[1]);
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement