Question

I have 4 Boolean parameters that I use to clean a string that I get from a scale using a Nport. I have to do this in framework 3.5 VS 2008.

I have 16 possible input combinations:

  • true true true true
  • true true true false
  • true true false true
  • true true false false
  • true false true true
  • true false true false
  • true false false true
  • true false false false
  • false true true true
  • false true true false
  • false true false true
  • false true false false
  • false false true true
  • false false true false
  • false false false true
  • false false false false

For each situation I have to do a different action on the string that I give to the method.

But how do I do this without writing many intertwined if and else clauses? I can print this out on the screen but according to me a switch is out of the question and a tuple does not exist yet in framework 3.5.

public void CompositionBooleans(string result, int counter)
        {
            if (counter == 0)
                return;

            bool[] booleans = new bool[2] { true, false };

             for (int j = 0; j < 2; j++)
            {
                StringBuilder stringBuilder = new StringBuilder(result);
                stringBuilder.Append(string.Format("{0} ", booleans[j].ToString())).ToString();

            if (counter == 1)
                Console.WriteLine(stringBuilder.ToString());

            CompositionBooleans(stringBuilder.ToString(), counter - 1);
        }
    }

This is the code I use to print it out.

But I need these situations and doing it with if else structures will take forever and is not flexible at all. Does anybody know how to do this?

Was it helpful?

Solution

If you really have one different process to do for each of the 16 possible combinations, I would suggest converting the array of Booleans into an int and switch on that int:

int i = booleans[0]?1:0 
      + 2*(booleans[1]?1:0)
      + 4*(booleans[2]?1:0)
      + 8*(booleans[3]?1:0);

switch (i)
{
   case 0: //false false false false
   case 1: //true false false false
   case 2: //false true false false
   //...
   case 15: //true true true true
}

But are you sure each situation is totally different and not a combination of 4 aspects only?

OTHER TIPS

public static void main(String[] args)
{
    boolean[] items = new boolean[] {true, true, true, true};
    int actionIndex = getActionIndex(0, 0, items);
              //do your action here: you could store lambda expressions and apply them
    System.out.write(actionIndex);
}

public static int getActionIndex(int currentItem, int currentIndex, boolean[] items)
{
    if(currentItem == items.length)
    {
        return currentIndex;
    }

    if(items[currentItem])
    {
        currentIndex += Math.pow(2, (items.length - 1) - currentItem);
    }

    return getActionIndex(++currentItem, currentIndex, items);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top