2017-01-19 38 views
0

我需要找到通過某個測試的對象,以及在通過第一次測試的所有對象中,在另一次測試中具有最低值的對象。說,我必須從一羣人中找出俄羅斯方塊中得分最低的瑞典女性(假設每個人都玩過俄羅斯方塊(當然他們有))。查找for循環中的最小值:如何初始化比較變量?

我明顯在做一個for循環,並做了測試,比較俄羅斯方塊的分數到目前爲止的最低分數。但是,比較第一個得分應該是多少?

通常情況下,我也可以把第一個和之後的一切進行比較,但他們也必須通過第一個測試。我也可以採取一個任意大的數字,但這是錯誤的。

我也可以做兩個循環,第一輪收集所有的瑞典女性,然後在第二輪收集所有的分數,但是有沒有更短更簡單的方法?

實物模型在C#:

bool AreYouSwedishFemale(Human patient) 
{ 
    if(patient.isFemale && patient.isSwedish) {return true;} 
    else {return false;} 
} 

int PlayTetris(Human patient) 
{ 
    return someInt; 
} 

void myMainLoop() 
{ 
    Human[] testSubjects = {humanA, humanB, humanC}; 
    Human dreamGirl; 
    int lowestScoreSoFar; //What should this be? 

    //Loop through testSubjects 
    foreach(Human testSubject in testSubjects) 
    { 
     //Check if it's a Swedish Female 
     if(AreYouSwedishFemale(testSubject)) 
     { 
      //If so, compare her score to the lowest score so far 
      if(PlayTetris(testSubject) < lowestScoreSoFar) //Error, uninitialized variable 
      { 
       //If the lowest, save the object to a variable 
       dreamGirl = testSubject; 
       //And save the score, to compare the remaining scores to it 
       lowestScoreSoFar = PlayTetris(testSubject); 
      } 
     } 
    } 

    //In the end we have the result 
    dreamGirl.marry(); 
} 

是啊,我真的不找女孩俄羅斯方塊打,我在統一編碼,而是試圖保持這個獨立的背景下。

回答

1

您可以在PlayTetris()檢查之前對「迄今爲止的最低分數」進行初始化檢查。假設最低分數爲0,則可以將最低分數初始化爲-1。然後編輯你的循環這樣

//Loop through testSubjects 
foreach(Human testSubject in testSubjects) 
{ 
    //Check if it's a Swedish Female 
    if(AreYouSwedishFemale(testSubject)) 
    { 

     if(lowestScoreSoFar < 0 || PlayTetris(testSubject) < lowestScoreSoFar) 
     { 
      //If the lowest, save the object to a variable 
      dreamGirl = testSubject; 
      //And save the score, to compare the remaining scores to it 
      lowestScoreSoFar = PlayTetris(testSubject); 
     } 
    } 
} 

基本上,如果你的「得分最低至今」尚未設置,則第一個瑞典女你覺得會設置它。

如果由於某種原因,分數是任意的,而不是-1,你也可以只有一個「lowestWasSet」bool,當第一個女孩被發現時,它會跳閘。

更妙的是,你也可以只是做(dreamGirl == NULL)代替(lowestScoreSoFar < 0)因爲直到找到第一個瑞典女你的夢想的女孩爲空。 C#將OR檢查短路,所以第一個要通過的條件將立即跳轉到塊中。所以dreamGirl == null會通過爲true並且PlayTetris()< lowestScoreSoFar不會拋出未初始化的錯誤。

+0

工作,謝謝! – DiMarzio