Advertisement
stanevplamen

02.1.16.1.SubsetSums

May 22nd, 2013
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.47 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class SubsetSums
  5. {
  6.     static long[] nArray = { 4, 3, 4, 11, 4, 2, 6, 5, 12, 1, 13, 14, 7, 5 };
  7.     static int checkedSum = 11;
  8.  
  9.     static void Gen01(int index, int[] vector)
  10.     {
  11.         if (index == -1)
  12.         {
  13.             Print(vector);
  14.         }
  15.         else
  16.         {
  17.             for (int i = 0; i <= 1; i++)
  18.             {
  19.                 vector[index] = i;
  20.                 Gen01(index - 1, vector);
  21.             }
  22.         }
  23.     }
  24.     static void Print(int[] vector)
  25.     {
  26.         long currentSum = 0;
  27.         List<long> intList = new List<long>();
  28.  
  29.         for (int i = 0; i < vector.Length; i++)
  30.         {
  31.             if (vector[i] == 1)
  32.             {
  33.                 currentSum = currentSum + nArray[i];
  34.                 intList.Add(nArray[i]);
  35.             }
  36.         }
  37.         if (currentSum == checkedSum)
  38.         {
  39.             foreach (int c in intList)
  40.             {
  41.                 Console.Write("{0},", c);
  42.             }
  43.             Console.Write("\b;");
  44.             Console.WriteLine();
  45.             intList = new List<long>();
  46.         }
  47.         else
  48.         {
  49.             intList = new List<long>();
  50.         }
  51.        
  52.     }
  53.  
  54.     static void Main()
  55.     {
  56.         int number = nArray.Length;
  57.         int[] vector = new int[number];
  58.         Console.WriteLine("The elements which sum is equal to the requested sum ({0}) are: ", checkedSum);
  59.         Gen01(number - 1, vector);
  60.  
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement