Advertisement
Guest User

Untitled

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