2017-03-21 27 views
0

我已經查找了一段時間,但我仍然停留在一些邏輯上。在文件中查找重複的數字(C++)

我有一個包含生日列表的文件。我想找到最常見的生日(月/日)。

我到目前爲止邏輯:

int maxValue = 0; 

    int maxBday; 

    while (Bday >> month >> b >> day >> b >> year) // take in values a line at a time from the file 

    { 
     int a = totalDays(month, day); //function finds number of days into the year 
     //(i.e. Feb. 2 = 33, not considering leap years in this problem). 

     for (int i = 0; i < 365; i++) 
     { 
      if (i = a) //going through all 365 days until the number of days matches 
      { 
       bdays[i]++; //add one to the array at position i 

       if (bdays[i] > maxValue) //finding what the maximum value in the array is 
       { 
        maxBday = i; //max number of days 
        maxValue = bdays[i]; //Setting new max for next line 
       } 
      } 
     } 
    } 
    cout << "The most common birthday: " << maxBday; 
} 

我稍後會創建一個函數來天的總數轉換成一年的實際日期晚。

我的文件在1/1上有一個重複的日期,所以輸出應該是1,但是我沒有得到任何輸出。我已經放入了cout語句,並且函數的每個部分都已經到達,但是循環不會結束。我真的迷失在我的邏輯錯誤可能出現的地方。

+0

什麼是bdays數組變量和「bdays [i] ++;//添加一個數組在位置我」它可以增加值不分配1值在特定的數組變量 – vishal

+0

有沒有辦法分配一個值在某個位置的數組?在邏輯上可能的途徑是通過在某個位置向陣列添加+1來找到最常見的生日,然後在陣列中找到具有最高值的位置? – borchr

+0

'如果(i = a)'不符合你的想法。 –

回答

1

嘗試

if(i == a) 

,否則該計劃是要我設置的值。它可能不是整個解決方案。

1

爲了找到最常見的生日:

  1. 使用多集。
  2. 存儲集合中的每個生日。
  3. 找到具有最大count()的生日。

像這樣(未測試):

#include <multiset> 
#include <tuple> 

struct Birthday { int d; int m; int y; } 

bool operator<(Birthday const & lhs, Birthday const & rhs) { 
     return std::tie(lhs.d, lhs.m, lhs.y) < std::tie(rhs.d, rhs.m, rhs.y); 
} 

multiset<Birthday> birthdays; 
//loop and insert birthdays with birthdays.insert(Birthday{...}); 

auto maxIt = std::max_element(begin(birthdays), end(birthdays), 
      [](Birthday const & b, 
      Birthday const & b2) { return b.count() > b2.count() }); 

沒有測試,但你應該明白我的意思。