EDITВзял другой подход и нашел решение, обновили функцию, чтобы правильно найти режим или режимОбнаружение режима или режима в массиве
Я был в этом алгоритме весь день и ночь , Я просмотрел около 12 примеров кода 10x, но ни один из них, похоже, не подходит для решения моей проблемы.
Задача: Найти режим (ы) в массиве, если массив имеет более одного режима, отобразите их все. (Это домашнее задание, так что я должен использовать массивы/указатели)
Пример массива: -1, -1, 5, 6, 1, 1
Пример вывода: Этот массив имеет следующий режим (s): -1, 1
Проблема, с которой я сталкиваюсь, пытается понять, как хранить и отображать только самый высокий режим или несколько режимов, если они существуют.
Я использовал много подходов, и поэтому я вывешу мой самый последний подход:
void getMode(int *arr, int size)
{
int *count = new int[size]; // to hold the number of times a value appears in the array
// fill the count array with zeros
for (int i = 0; i < size; i++)
count[i] = 0;
// find the possible modes
for (int x = 0; x < size; x++)
{
for (int y = 0; y < size; y++)
{
// don't count the values that will always occur at the same element
if (x == y)
continue;
if (arr[x] == arr[y])
count[x]++;
}
}
// find the the greatest count occurrences
int maxCount = getMaximum(count, size);
// store only unique values in the mode array
int *mode = new int[size]; // to store the mode(s) in the list
int modeCount = 0; // to count the number of modes
if (maxCount > 0)
{
for (int i = 0; i < size; i++)
{
if (count[i] == maxCount)
{
// call to function searchList
if (!searchList(mode, modeCount, arr[i]))
{
mode[modeCount] = arr[i];
modeCount++;
}
}
}
}
// display the modes
if (modeCount == 0)
cout << "The list has no mode\n";
else if (modeCount == 1)
{
cout << "The list has the following mode: " << mode[0] << endl;
}
else if (modeCount > 1)
{
cout << "The list has the following modes: ";
for (int i = 0; i < modeCount - 1; i++)
{
cout << mode[i] << ", ";
}
cout << mode[modeCount - 1] << endl;
}
// delete the dynamically allocated arrays
delete[]count;
delete[]mode;
count = NULL;
mode = NULL;
}
/*
definition of function searchList.
searchList accepts a pointer to an int array, its size, and a value to be searched for as its arguments.
if searchList finds the value to be searched for, searchList returns true.
*/
bool searchList(int *arr, int size, int value)
{
for (int x = 0; x < size; x++)
{
if (arr[x] == value)
{
return true;
}
}
return false;
}
Правильный инструмент для решения этой проблемы - отладчик. Вы также можете найти [Как отлаживать небольшие программы] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). –
@ Да, спасибо, я проверю это. –