Найти в массиве три минимальных элемента - C (СИ)
Формулировка задачи:
Здравствуйте, девочки и мальчики. Мучаюсь с заданием, где обязательно нужно использовать указатели (pointers) и выделение памяти (malloc) . Задание звучит так:
Создать два двумерные массивы (могут быть разных размеров). Найти в первом массиве три минимальные элементы, да такие, которые не повторялись бы во втором массиве и весь результат вывести в одной строке. Вот как я начала пользуясь своим котелком, что на плечиках да плачевно:
Уже третий день сижу... Копирую, читаю, но всё никак не получается( Надеюсь на помощь. Спасибо
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int **masiv1(int m, int n);
int **masiv2(int o, int p);
int main ()
{
int m, n, o, p;
int i, j, k, l; // счетчики, по 2 на массив
time_t seconds; // ТУТ УЖЕ ДЕЙСТВОВАЛА ИСХОДЯ ИЗ ПРИМЕРОВ
time(&seconds);
srand((unsigned int) seconds); // генерирует рандом-цифры?
printf("Введите количество Строк и Столбиков 1-ого массива:\n");
scanf("[%d] [%d]", &m, &n);
printf("Введите количество Строк и Столбиков 2-ого массива:\n");
scanf("[%d] [%d]", &o, &p);
printf("\n");
for (i=0; i<m; i++)
{
for (j=0; j<n; j++)
{
printf("%d ", Masiv1[i][j]);
}
printf("\n");
}
for (k=0; i<o; k++)
{
for (l=0; j<p; k++)
{
printf("%d ", Masiv2[o][p]);
}
printf("\n");
}
// дальше кошмар для меня, проба с 1-им массивом и pointer/malloc
int **masiv1(int m ,int n)
{
int **array1;
int i, j;
array1 = (int**)malloc(m * sizeof(int *));
if (array1 !=NULL)
{
for (i=0; i < m; i++)
{
*(array1+i) = (int*)malloc(n * sizeof(int));
if (*(array1+i) ==NULL)
break;
}
}
printf("Первичный массив:\n");
for (i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
*(*(array1+i)+j)=rand() % 10;
printf("%d ",*(*(array1+i)+j));
}
printf("\n");
}
return 0;
}Решение задачи: «Найти в массиве три минимальных элемента»
textual
Листинг программы
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MINIMAL_ELEMENTS_COUNT 3
#define MAX_RAND_RANGE 50
#define MODE_EXTENDED_OUTPUT
static int** CreateAndGenerateMatrix(int*** const matrixPtr, const int N,
const int M);
static void FreeAndNilMatrix(int*** const matrixPtr, const int N);
static void PrintMatrix(const int** const matrix, const int N, const int M);
static int* GetElementsSetFromMatrix(const int** const matrix, const int N,
const int M, int** const uniqueElementsArrayPtr,
int* const uniqueElementsCountPtr);
static int CommonIntegerComparator(const void* a, const void* b);
static int* GetNonRepeatingElementsFromArray1(const int* const array1,
const int array1Length, const int* const array2, const int array2Length,
int** const uniqueElementsArrayPtr, int* const uniqueElementsCountPtr);
static int* GetNonRepeatingMinElementsFromMatrices(const int** const matrix1,
const int matrix1RowCount, const int matrix1ColCount,
const int** const matrix2, const int matrix2RowCount,
const int matrix2ColCount);
static int** CreateAndGenerateMatrix(int*** const matrixPtr, const int N,
const int M)
{
int** matrix = NULL;
int i = 0;
int j = 0;
int allocationFailed = 0;
if ((matrixPtr != NULL) && (N > 0) && (M > 0))
{
/* allocating N rows */
matrix = malloc(N * sizeof(*matrix));
if (matrix != NULL)
{
i = 0;
allocationFailed = 0;
/* allocating M columns */
while ((i < N) && !allocationFailed)
{
matrix[i] = malloc(M * sizeof(**matrix));
if (matrix[i] == NULL)
{
allocationFailed = 1;
}
i++;
}
if (allocationFailed)
{
/*
at some point allocation failed, thus, we need to deallocate i-1
previous columns and all rows
*/
for(j = 0; j < i - 1; j++)
{
free(matrix[j]);
}
free(matrix);
matrix = NULL;
}
else
{
/* filling matrix with random values */
for(i = 0; i < N; i++)
{
for(j = 0; j < M; j++)
{
matrix[i][j] = rand() % MAX_RAND_RANGE;
}
}
(*matrixPtr) = matrix;
}
}
}
return matrix;
}
static void FreeAndNilMatrix(int*** const matrixPtr, const int N)
{
int i = 0;
for(i = 0; i < N; i++)
{
free((*matrixPtr)[i]);
}
free(*matrixPtr);
(*matrixPtr) = NULL;
}
static void PrintMatrix(const int** const matrix, const int N, const int M)
{
int i = 0;
int j = 0;
printf("=============================================================\n");
for(i = 0; i < N; i++)
{
for(j = 0; j < M; j++)
{
printf("%2d ", matrix[i][j]);
}
printf("%c", '\n');
}
printf("=============================================================\n");
}
/*
This function finds all elements in matrix from which it is composed and
stores them in array. The elements in stored array are unique.
Ex.:
Given matrix:
1 2 3 0 0
3 4 5 0 2
9 7 3 3 3
->
Resulting array:
1 2 3 0 4 5 9 7
*/
static int* GetElementsSetFromMatrix(const int** const matrix, const int N,
const int M, int** const uniqueElementsArrayPtr,
int* const uniqueElementsCountPtr)
{
int* uniqueElementsArray = NULL;
int* tempPtr = NULL;
int uniqueElementsCount = 0;
int i = 0;
int j = 0;
int k = 0;
int elementFound = 0;
/* expecting max size of M * N (all elements in matrix are unique) */
uniqueElementsArray = malloc(M * N * sizeof(*uniqueElementsArray));
if (uniqueElementsArray != NULL)
{
uniqueElementsCount = 0;
elementFound = 0;
/* checking all matrix's elements */
for(i = 0; i < N; i++)
{
for(j = 0; j < M; j++)
{
/* checking if element is already present in array */
k = 0;
elementFound = 0;
while ((k < uniqueElementsCount) && !elementFound)
{
if (uniqueElementsArray[k] == matrix[i][j])
{
elementFound = 1;
}
k++;
}
if (!elementFound)
{
/* adding to array */
uniqueElementsArray[uniqueElementsCount] = matrix[i][j];
uniqueElementsCount++;
}
}
}
if (uniqueElementsCount < (M * N))
{
/* actual unique element count is less than expected, reallocing */
tempPtr = realloc(uniqueElementsArray,
uniqueElementsCount * sizeof(*uniqueElementsArray));
if (tempPtr != NULL)
{
uniqueElementsArray = tempPtr;
}
else
{
free(uniqueElementsArray);
uniqueElementsArray = NULL;
}
}
if (uniqueElementsArray != NULL)
{
/* all is OK, exporting */
(*uniqueElementsArrayPtr) = uniqueElementsArray;
(*uniqueElementsCountPtr) = uniqueElementsCount;
}
}
return uniqueElementsArray;
}
/*
Comparator for qsort (ascending order)
*/
static int CommonIntegerComparator(const void* a, const void* b)
{
return (*(int*)a - *(int*)b);
}
/*
This function searches array1 for elements that are not present in array2
and stores them in array. The elements in stored array are unique. Arrays,
supplied to function, must contain unique elements as well.
Ex.:
Given arrays:
[1]
1 2 3 4 5 11 64
[2]
4 5 0 64
->
Resulting array:
1 2 3 11
*/
static int* GetNonRepeatingElementsFromArray1(const int* const array1,
const int array1Length, const int* const array2, const int array2Length,
int** const uniqueElementsArrayPtr, int* const uniqueElementsCountPtr)
{
int* uniqueElementsArray = NULL;
int* tempPtr = NULL;
int uniqueElementsCount = 0;
int i = 0;
int j = 0;
int k = 0;
int elementFound = 0;
uniqueElementsArray = malloc(array1Length * sizeof(*uniqueElementsArray));
if (uniqueElementsArray != NULL)
{
for(i = 0; i < array1Length; i++)
{
/* seraching for element in array2 */
elementFound = 0;
j = 0;
while ((j < array2Length) && !elementFound)
{
if (array1[i] == array2[j])
{
elementFound = 1;
}
j++;
}
if (!elementFound)
{
/* adding to unique elements array */
/*
NOTE:
We do not check if an element that we want to add is already
present in array because by design both supplied arrays contain
only unique elements.
*/
uniqueElementsArray[uniqueElementsCount] = array1[i];
uniqueElementsCount++;
}
}
if (uniqueElementsCount < array1Length)
{
tempPtr = realloc(uniqueElementsArray,
uniqueElementsCount * sizeof(*uniqueElementsArray));
if (tempPtr != NULL)
{
uniqueElementsArray = tempPtr;
}
else
{
free(uniqueElementsArray);
uniqueElementsArray = NULL;
}
}
if (uniqueElementsArray != NULL)
{
(*uniqueElementsArrayPtr) = uniqueElementsArray;
(*uniqueElementsCountPtr) = uniqueElementsCount;
}
}
return uniqueElementsArray;
}
/*
This function searches two matrices and gets an array of elements from
matrix1 that are not present in matrix2. The array is sorted in ascending
order.
Ex.:
Given matrices:
[1]
43 23 28 2 36
31 13 49 43 6
49 49 17 32 16
18 43 33 20 16
[2]
22 15 8 10 13 33 15
34 9 34 43 6 39 17
33 29 23 6 34 17 18
8 19 17 39 11 10 22
27 3 49 28 34 22 46
10 49 16 32 39 28 3
->
Resulting array:
2 31 18 20
*/
static int* GetNonRepeatingMinElementsFromMatrices(const int** const matrix1,
const int matrix1RowCount, const int matrix1ColCount,
const int** const matrix2, const int matrix2RowCount,
const int matrix2ColCount)
{
int* res = NULL;
int* uniqueElementsFromMatrix1 = NULL;
int* uniqueElementsFromMatrix2 = NULL;
int* nonRepeatingElements = NULL;
int matrix1UniqueElementsCount = 0;
int matrix2UniqueElementsCount = 0;
int nonRepeatingElementsCount = 0;
int i = 0;
uniqueElementsFromMatrix1 = GetElementsSetFromMatrix(matrix1,
matrix1RowCount, matrix1RowCount, &uniqueElementsFromMatrix1,
&matrix1UniqueElementsCount);
#ifdef MODE_EXTENDED_OUTPUT
printf("Unique elements from 1:\n");
for(i = 0; i < matrix1UniqueElementsCount; i++)
{
printf("%d ", uniqueElementsFromMatrix1[i]);
}
printf("\n[%d]\n\n", matrix1UniqueElementsCount);
#endif
uniqueElementsFromMatrix2 = GetElementsSetFromMatrix(matrix2,
matrix2RowCount, matrix2RowCount, &uniqueElementsFromMatrix2,
&matrix2UniqueElementsCount);
#ifdef MODE_EXTENDED_OUTPUT
printf("Unique elements from 2:\n");
for(i = 0; i < matrix2UniqueElementsCount; i++)
{
printf("%d ", uniqueElementsFromMatrix2[i]);
}
printf("\n[%d]\n\n", matrix2UniqueElementsCount);
#endif
if ((uniqueElementsFromMatrix1 != NULL) &&
(uniqueElementsFromMatrix2 != NULL))
{
nonRepeatingElements = GetNonRepeatingElementsFromArray1(
uniqueElementsFromMatrix1, matrix1UniqueElementsCount,
uniqueElementsFromMatrix2, matrix2UniqueElementsCount,
&nonRepeatingElements, &nonRepeatingElementsCount);
if (nonRepeatingElements != NULL)
{
#ifdef MODE_EXTENDED_OUTPUT
printf("Unique elements from both:\n");
for(i = 0; i < nonRepeatingElementsCount; i++)
{
printf("%d ", nonRepeatingElements[i]);
}
printf("\n[%d]\n\n", nonRepeatingElementsCount);
#endif
qsort(nonRepeatingElements, nonRepeatingElementsCount,
sizeof(*nonRepeatingElements), CommonIntegerComparator);
res = nonRepeatingElements;
}
free(uniqueElementsFromMatrix1);
free(uniqueElementsFromMatrix2);
}
return res;
}
int main(void)
{
int** a = NULL;
int** b = NULL;
int X = 4;
int Y = 5;
int M = 6;
int N = 7;
int i = 0;
int* minimalElements = NULL;
srand(time(NULL));
a = CreateAndGenerateMatrix(&a, X, Y);
b = CreateAndGenerateMatrix(&b, M, N);
if ((a != NULL) && (b != NULL))
{
PrintMatrix(a, X, Y);
PrintMatrix(b, M, N);
minimalElements = GetNonRepeatingMinElementsFromMatrices(a, X, Y, b, M, N);
printf("First %d minimal non-repeating elements from both matrices:\n",
MINIMAL_ELEMENTS_COUNT);
for(i = 0; i < MINIMAL_ELEMENTS_COUNT; i++)
{
printf("%d ", minimalElements[i]);
}
free(minimalElements);
FreeAndNilMatrix(&a, X);
FreeAndNilMatrix(&b, M);
}
return 0;
}