Guest User

Problem 12. * Zero Subset

a guest
Oct 15th, 2015
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.06 KB | None | 0 0
  1. int[] numbers = { 1, 1, 1, -1, -1 };
  2.  
  3. int coefficientCombinations = (int) Math.Pow(2, numbers.Length) - 1;
  4.  
  5. for (int coefficients = coefficientCombinations; coefficients > 0; coefficients--)
  6. {
  7.  
  8.     if(onlyOneBitSet(coefficients))
  9.     {
  10.         continue;
  11.     }
  12.     int sum = 0;
  13.     for (int index = 0; index < numbers.Length; index++)
  14.     {
  15.         int bitIndex = (numbers.Length - 1) - index;
  16.         int numberIndex = index;
  17.         int coefficient = getBit(coefficients, bitIndex);
  18.         sum += coefficient * numbers[numberIndex];
  19.     }
  20.     if (sum == 0)
  21.     {
  22.         //Print the Sum
  23.     }
  24. }
  25.  
  26. static int getBit(int coefficients, int bitIndex)
  27. {
  28.     return (coefficients >> bitIndex) & 1;
  29. }
  30.  
  31. static bool onlyOneBitSet(int coefficients)
  32. {
  33.     int setBitCount = 0;
  34.     int highestBit = 31;
  35.     for(int i = 0; i <= highestBit; i++)
  36.     {
  37.         if(((coefficients >> i) & 1) == 1)
  38.         {
  39.             setBitCount++;
  40.         }
  41.     }
  42.    if(setBitCount == 1)
  43.     {
  44.         return true;
  45.     }
  46.     else
  47.     {
  48.         return false;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment