【问题标题】:Finding repeat numbers in a file (C++)查找文件中的重复数字 (C++)
【发布时间】:2017-03-21 02:49:44
【问题描述】:

我已经环顾了一段时间,但我仍然停留在一些逻辑上。

我有一个包含生日列表的文件。我想找出最常见的生日(月/日)。

到目前为止我的逻辑:

    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 语句,并且正在到达函数的每个部分,但循环永远不会结束。我真的迷失了我的逻辑错误可能在哪里。

【问题讨论】:

  • 什么是bdays数组变量和“bdays[i]++; //在数组i的位置加一”它可以增加值而不是在特定数组变量中赋值1
  • 有没有办法在某个位置给数组赋值?通过在数组中的某个位置添加+1然后在数组中找到具有最高值的位置来找到最常见的生日是否是逻辑上可能的途径?
  • if (i = a) 并没有按照你的想法去做。
  • 嗯,好吧,这让我觉得我不能按照我想要的方式做到这一点。我很难找到另一种编码方式。有任何想法吗?没什么特别的,只是一般的伪代码

标签: c++


【解决方案1】:

试试

if(i == a)

因为否则程序会将 i 设置为 a 的值。它可能不是完整的解决方案。

【讨论】:

    【解决方案2】:

    寻找最常见的生日:

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

    没有经过测试,但你应该明白了。

    【讨论】:

      猜你喜欢
      • 2015-07-02
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 2016-06-06
      • 2016-03-15
      • 1970-01-01
      • 2016-07-31
      • 2017-10-04
      相关资源
      最近更新 更多