2017-03-21 70 views
0

的每一個最大數我有3種int類型:最有效的方法來查找一組數字

int value1; 
int value2; 
int value3; 

而3布爾值:

bool maxIs1; 
bool maxIs2; 
bool maxIs3; 

的輸入值必須是獨立的變量。

maxIs1 = True表示value1必須具有最大值等。

我需要方法來比較這組數字與一組條件。 例如:

int value1 = 10; 
int value2 = 1; 
int value3 = 10; 

bool maxIs1 = True; 
bool maxIs2 = False; 
bool maxIs3 = True; 

bool result = compareValues(); //true 

或者:

int value1 = 1; 
int value2 = 1; 
int value3 = 10; 

bool maxIs1 = True; 
bool maxIs2 = False; 
bool maxIs3 = True; 

bool result = compareValues(); //false 

什麼是最有效的方式來做到這一點?

+0

是變量不變(3)或有可能是其他變量的量? –

+0

在我的情況下,這裏只有3. – InfernumDeus

+0

如果你擔心效率和超過3個值,這是一個'O(n)'問題,你只需要迭代一次輸入。 – Rawling

回答

1

我不認爲你不必在意效率在3個值

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); 
0

的情況下,如果你想不同數量的值嘗試這種解決方案:

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)); 

    } 

Compare()應該像這個:

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; 
    } 
+2

你真的做了一個簡單的任務複雜.... – caesay

+0

我認爲你是對的,爲你的簡單答案+1 –

2

這很有趣。如果你可以把它們放到一個數組,你可以使用LINQ乾淨檢查它們是否都滿足條件:

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)); 
+0

如果價值是最大的但你的答案滿足條件,但布爾價值說,它不是,我想在這它應該返回false –

+1

@AliEzzatOdeh:如果這是你想要的行爲,你可以將最後一行改爲'.All(c =>(!c.isMax && c.value!= max)||(c.isMax && c。 value == max));' – caesay

相關問題