对于统计日期的c++问题

小蓝现在有一个长度为 100 的数组,数组中的每个元素的值都在 0 到 9 的
范围之内。数组中的元素从左至右如下所示:
5 6 8 6 9 1 6 1 2 4 9 1 9 8 2 3 6 4 7 7 5 9 5 0 3 8 7 5 8 1 5 8 6 1 8 3 0 3 7 9 2
7 0 5 8 8 5 7 0 9 9 1 9 4 4 6 8 6 3 3 8 5 1 6 3 4 6 7 0 7 8 2 7 6 8 9 5 6 5 6 1 4 0 1
0 0 9 4 8 0 9 1 2 8 5 0 2 5 3 3
现在他想要从这个数组中寻找一些满足以下条件的子序列:

  1. 子序列的长度为 8;
  2. 这个子序列可以按照下标顺序组成一个 ymmdd 格式的日期,并且
    要求这个日期是 2023 年中的某一天的日期,例如 20230902,20231223。
    y 表示年份,mm 表示月份,dd 表示天数,当月份或者天数的长度只
    有一位时需要一个前导零补充。
    请你帮小蓝计算下按上述条件一共能找到多少个不同 的 2023 年的日期。
    对于相同的日期你只需要统计一次即可。

可以通过枚举所有可能的子序列来解决这个问题。先通过循环来枚举所有可能的子序列,然后检查每个子序列是否满足条件。如果满足条件,则将其添加到一个集合中(此算法使用set,不会出现重复项),以便统计不同的日期数。最后,返回集合中不同日期的数量。

#include <iostream>
#include <set>
#include <string>

using namespace std;

int main() {
    int a[100] = {5, 6, 8, 6, 9 // ...
                  };
    set<string> dates;
    for (int i = 0; i < sizeof(a) / sizeof(int) -7; i++) {
        string date = to_string(a[i]) + to_string(a[i+1]) + to_string(a[i+2]) + to_string(a[i+3]) + to_string(a[i+4]) + to_string(a[i+5]) + to_string(a[i+6]) + to_string(a[i+7]);
        if (date >= "20230101" && date <= "20231231") {
            string year = date.substr(0,4);
            string month = date.substr(4,2);
            string day = date.substr(6);
            dates.insert(year + "-" + month + "-" + day);
        }
    }
    cout << "不同日期数:" << dates.size() << endl;
    return 0;
}
  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/7653291
  • 除此之外, 这篇博客: 编写程序,实现用户输入15个数据后进行排序,要求排序后按由大到小存放在一个数组中。重新输入一个数,编写查找算法找到该数是数组中的第几个元素的值,如果该数不在数组中,则输出“无此数”。中的 C语言实现:编写程序,实现用户输入15个数据后进行排序,要求排序后按由大到小存放在一个数组中。重新输入一个数,编写查找算法找到该数是数组中的第几个元素的值,如果该数不在数组中,则输出“无此数”。 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • 编程基础第六版 课后题

    代码如下

    #include <stdio.h>
    #include <math.h>
    int main()
    {
    int i,j,t;
    int a[15];
    int x,l,h,mid,n;
    n=15;
    l=0;
    h=n-1;
    printf("请输入15个不同数字,按一次输入一个,依次输入15次的方法输入数字:\n");
    for(i=0;i<15;i++)
    scanf("%d",&a[i]);
    for(j=0;j<14;j++)
    {
    for(i=0;i<14-j;i++)   //这里我第一次写也忽略了j要不断的去替换i,所以对于i来说它的循环条件应该是14-j,有好多人可能和我一样写成i<15啦
    if( a[i]<a[i+1])
    {
    t=a[i];
    a[i]=a[i+1];
    a[i+1]=t;
    }
    }
    printf("按从大到小的排序结果:");
    for( i=0;i<15;i++)
    printf("%d\t",a[i]);
    printf("\n");
    
    for (l=0, h=14, printf("请输入一个数:"), scanf("%d", &x); l<=h;)//while也可以但是我很奇怪用while会提前退出循环哈哈哈
    {
    mid=(l+h)%2;
    if (x>a[mid])h=mid-1;
    else if (x<a[mid])l=mid+1;
    else
    {
    printf("%d是第%d位数",x,mid+1);
    break;
    }
    }
    if(x!=a[mid])
    printf("查无此数!");
    return 0;
    }
    

    这个是我用手机c compiler码的效果~顺便一提这个软件真的好用(✪▽✪)