psotirov

NP-Complete problem

Nov 29th, 2012
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.75 KB | None | 0 0
  1. using System;
  2.  
  3. class NPCProblem
  4. {
  5.     static void Main()
  6.     {
  7.         Console.Write("Please enter number of integers to solve NP-Complete problem [2, 31]: ");
  8.         string input = Console.ReadLine();
  9.         int n = 0;
  10.         if (!int.TryParse(input, out n) || (n < 2) || (n > 31)) return;
  11.         int totalComb = (1 << n) - 1; //nuber of total combinations is 2^n-1
  12.         Console.WriteLine("Number of total combinations is " + totalComb);
  13.         int[] numbers = new int[n];
  14.         int totalSums = 0;
  15.         for (int i = 0; i < n; i++) // requests numbers input
  16.         {
  17.             do
  18.             {                
  19.                 Console.Write("Please enter {0} integer: ", i + 1);
  20.                 input = Console.ReadLine();
  21.             } while (!int.TryParse(input, out numbers[i])); // endless loop until user enters correct number (entering a lot of numbers causes mistakes in most cases)
  22.         }
  23.  
  24.         for (int i = 1; i <= totalComb; i++) // Main loop representing all combination of numbers (except empty subset)
  25.         {
  26.             int sum = 0;
  27.             string numbersList = "\n\nCombination "+ i + "\n\n";
  28.             for (int j = 0; j < n; j++) // numbers selection loop - in the number "i" each bit position that is set to 1 represents the index of the participating number from the array
  29.                 if (((i >> j) & 1) == 1)
  30.                 {
  31.                     sum += numbers[j];
  32.                     numbersList = numbersList + string.Format("N[{0}] = {1}\n",j+1 ,numbers[j]);
  33.                 }
  34.  
  35.             if (sum == 0)
  36.             {
  37.                 Console.WriteLine(numbersList);
  38.                 totalSums++;
  39.             }
  40.         }
  41.         Console.WriteLine("Total number of 0 sums: "  + totalSums);
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment