Reputation: 1202
I have 3 int values:
int value1;
int value2;
int value3;
And 3 bool values:
bool maxIs1;
bool maxIs2;
bool maxIs3;
Input values have to be separate variables.
maxIs1 = True
means that value1
must have maximum value and so on.
I need method to compare this set of numbers with set of conditions. For example:
int value1 = 10;
int value2 = 1;
int value3 = 10;
bool maxIs1 = True;
bool maxIs2 = False;
bool maxIs3 = True;
bool result = compareValues(); //true
Or:
int value1 = 1;
int value2 = 1;
int value3 = 10;
bool maxIs1 = True;
bool maxIs2 = False;
bool maxIs3 = True;
bool result = compareValues(); //false
What is the most efficient way to do so?
Upvotes: 0
Views: 108
Reputation: 45967
I don't think you have to care about efficiency in case of 3 values
int value1 = 10;
int value2 = 1;
int value3 = 1;
bool maxIs1 = true;
bool maxIs2 = false;
bool maxIs3 = true;
int max = new[] { value1, value2, value3 }.Max();
bool result = (!maxIs1 || value1 == max) && (!maxIs2 || value2 == max) && (!maxIs3 || value3 == max);
Upvotes: 1
Reputation: 17233
This was fun. If you can put them into an array you can use linq to cleanly check if they all satisfy the condition:
var values = new[] { value1, value2, value3 };
var maxes = new[] { maxIs1, maxIs2, maxIs3 };
var max = values.Max();
var result = values
.Zip(maxes, (f, s) => new { value = f, isMax = s })
.All(c => !c.isMax || (c.value == max));
Upvotes: 2
Reputation: 2163
Try this solution if you want different number of value :
static void Main()
{
List<int> listOfInts = new List<int>();
List<bool> listOfBools = new List<bool>();
listOfInts.Add(1);
listOfInts.Add(2);
listOfInts.Add(1);
listOfBools.Add(false);
listOfBools.Add(false);
listOfBools.Add(false);
Console.WriteLine("value = " + Compare(listOfInts,listOfBools));
}
and Compare()
should be like this :
static bool Compare(List<int> listOfInts, List<bool> listOfBools)
{
int max = listOfInts.Max();
bool isCorrect = true;
var maxList = listOfInts.Where(value => value == max);
var indicesOfMax = GetIndeciesOfMax(maxList, listOfInts);
for (int i = 0; i < listOfInts.Count; i++)
{
if (indicesOfMax.Contains(i) && listOfInts[i] == max && listOfBools[i])
{
isCorrect = true;
}
else if (!indicesOfMax.Contains(i) && listOfInts[i] != max && !listOfBools[i])
{
isCorrect = true;
}
else
{
isCorrect = false;
break;
}
}
return isCorrect;
}
static List<int> GetIndeciesOfMax(IEnumerable<int> maxList, List<int> list)
{
List<int> indecies = new List<int>();
foreach (var m in maxList)
{
indecies.Add(list.IndexOf(m));
}
return indecies;
}
Upvotes: 0