'Is there a way of comparing 2 variables in a grid like way instead of nested if statements?
I am dealing with a prisoners paradox type problem where there are multiple combinations (2x2 -> 4) and each has a different result. Is there a good way of looking at the inputs and deciding the output other than nested if statements which can get confusing if theres more than 2 options for inputs. For example there are 2 prisoners being questioned: A and B. If both choose to expose the other then they both are imprisoned for 5 years, if both stay loyal then they both only recieve 1 year in prison, however if A exposes B but B remains loyal, A will be set free and B will be imprisoned for 10 years. Currently my logic looks roughly like this:
if (A.Cooperate)
{
if (B.Cooperate)
{
A.Sentence = 5;
B.Sentence = 5;
}
else
{
A.Sentence = 0;
B.Sentence = 10;
}
}
else
{
if (B.Cooperate)
{
A.Sentence = 10;
B.Sentence = 0;
}
else
{
A.Sentence = 1;
B.Sentence = 1;
}
}
Although I would like to add more options than just a boolean yes/no and fear it will become over complicated with many nested if statements.
Solution 1:[1]
This is how I would do it to improve readability and logic
static void Interrogate(Prisoner A, Prisoner B)
{
if (!B.Cooperate && !A.Cooperate)
{
A.Sentence = 1;
B.Sentence = 1;
}
else if (B.Cooperate && !A.Cooperate)
{
A.Sentence = 10;
B.Sentence = 0;
}
else if (A.Cooperate && !B.Cooperate)
{
A.Sentence = 0;
B.Sentence = 10;
}
else
{
A.Sentence = 5;
B.Sentence = 5;
}
}
Solution 2:[2]
You can use the new switch format
switch (A.Cooperate, B.Cooperate) {
case (true, false): {
.....
}
break;
case (true, true): {
....
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | pm100 |