如何打印最长重复序列的第一个元素的索引?

时间:2017-04-12 01:13:19

标签: c++ arrays

我正在为作业编写一个程序,它是: 编写一个程序,创建一个包含20个元素的int数组,询问用户需要多少次抛出(1-20),填充数组,结果是根据用户的要求多次抛出一个数字立方体,打印出值水平投掷然后显示找到的最长跑 在投掷的顺序。 对于上面的示例,输出将是用户请求18次投掷:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

1 5 5 4 3 1 2 2 2 2 6 1 3 3 5 5 5 5

最长的一次发生在指数14处。

我为第一部分编写了程序,但我仍然试图找到最长运行的索引。到目前为止,这是我的代码:

const int SIZE = 20;

int main()
int arr[SIZE];
int numToss;
srand(time(0));

    cout << "How many tosses are required? Enter a value from 1 to 20: " << endl;
    cin >> numToss;
        while (numToss > SIZE || numToss < 1)
        {
            cout << "Please enter a value for the number of tosses greater than 1 and less than 20: " << endl;
            cin >> numToss;
        }

    for (int i = 0; i < numToss; i++)
    {
        arr[i] = 1 + rand() % 6;
        cout << " " << arr[i];
    }
cout << endl;


int max_count = 0;
int length = arr[0];
    for (int i = 0; i < length; i++)
    {
        int count = 1;
        for (int j = i + 1; j < length; j++)
        {
            if (arr[i] == arr[j])
            count++;
        }
        if (count > max_count)
            max_count = count;
    }
    int result = 0;
    for (int i = 0; i < length; i++)
    {
        int count=1;
        for (int j = i + 1; j < length; j++)
        {
            if (arr[i] == arr[j])
            count++;
        }
        if (count == max_count)
          {
            max_count = arr[i];
            result = i;
            cout << "The longest run occurs at " << result << endl;
          }
    }

return 0;

它打印不正确,我怎么解决这个问题?任何帮助表示赞赏!

0 个答案:

没有答案