没有模式的例外是什么意思? (数组中出现次数最多的数字)?

时间:2014-12-03 20:04:20

标签: c++ algorithm

当问题执行时,它正确地说明模式是3.教授要求“程序应该考虑”异常“没有”模式“发生 - 数组中的值不会出现多次。”问题是我不明白它被问到了什么。我无法绕开这样的事情。

void showArray(const int[], int); 
void showMode(int [], int);

using namespace std;

int main()
{
    const int Size = 11; //size of the array
    int test[Size] = {1, 2, 3, 3, 3, 2, 2, 1, 3, 4, 5}; //elements of the array

    cout << "The Numbers in the Array are: \n";
    showArray(test, Size); //displays the array in its original order

    showMode(test, Size);

    return 0;
}

void showArray(const int arr[], int Size) 
{
    for(int count = 0; count < Size; count++)
        cout << arr[count] << " ";
    cout << endl;

}

void showMode(int test[], int Size)
{
    int counter = 1;
    int max = 0;
    int mode = test[0];

    for(int pass = 0; pass < Size - 1; pass++)
    {
        if(test[pass] == test[pass + 1])

            {
                counter++;
                if(counter > max)
                {
                    max = counter;
                    mode = test[pass];
                }
            }
        else
            counter = 1;
    }
    cout << "The Mode of the Array is: " << mode << endl;
}

1 个答案:

答案 0 :(得分:3)

在测试软件时,您希望拥有占用所有不同分支的测试用例。现在你只展示了当给定输入数组有唯一的最高频率元素时,代码工作

您的教授还希望您测试最高重复次数何时不唯一。

这通常被称为角落案例。

教授的措辞很不幸。单词 exception 在C ++中具有特定含义,这不是它......除非你的指令在最高重复次数不唯一时实际抛出异常。

良好的附加测试案例将是:

  • 长度为零的数组

    {}
    
  • 长度为一的数组

    { 7 }
    
  • 最高重复次数的双向平局

    { 1, 2, 3, 2, 1 }
    { 1, 1, 2, 3, 3 }
    
  • 最高重复次数的N路并列

    { 1, 3, 5, 4, 2 }
    
  • 领带被第一个元素打破

    { 2, 6, 3, 2, 4, 5, 2, 6, 9 }
    
  • 领带被最后一个元素打破

    { 6, 3, 2, 4, 5, 2, 6, 2 }
    
  • 其他元素有更长的“跑”

    { 5, 2, 6, 3, 2, 4, 4, 5, 2, 6, 9 }
    

如果您的代码为所有这些案例提供了正确的结果,那么您将非常确信它适用于所有输入。