2017-03-21 7 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年に1日ですが、何も出力されません。私はcoutステートメントを入れて、関数のすべての部分に達していますが、ループは終了しません。私は論理的な誤りがどこにあるのか本当に失われています。それ以外の場合はプログラムが値iに設定しようとしているので、

+0

bdays配列変数と "bdays [i] ++; //位置iの配列に1を加える"とは、特定の配列変数に1の値を代入しない値を増やすことができます – vishal

+0

特定の位置で配列に値を渡しますか?それは論理的に可能な経路は、位置に配列に+1を追加して最も一般的な誕生日を見つけて、最大値を持つ配列内の位置を見つけることですか? – borchr

+0

'if(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() }); 

テストし、あなたのアイデアを取得する必要はありません。

関連する問題