#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
struct MostOftenStruct{
float value;
int count;
};
#define N 100
const float EPS = 0.101f;
void fill_array(float ar[], const unsigned int n, const float lo_v, const float hi_v);
void print_array(float ar[], const unsigned int n);
struct MostOftenStruct occurs_most_often(float ar[], const unsigned int n, const float d);
int main()
{
srand(time(NULL));
float a[N] = { 0 };
float b[N] = { 0 };
float c[N] = { 0 };// = new()
fill_array(a, N, 0.0f, 50.0f);
fill_array(b, N, 0.0f, 50.0f);
fill_array(c, N, 0.0f, 50.0f);
print_array(a, N);
print_array(b, N);
print_array(c, N);
struct MostOftenStruct m = occurs_most_often(a, N, EPS);
printf("S=%f, count=%d", m.value, m.count);
return 0;
}
struct MostOftenStruct occurs_most_often(float array[], const unsigned int n, const float eps)
{
struct MostOftenStruct * flstruct = NULL;
float prevv = 0.0f, nextv = 0.0f, delta = 0.0f;
int count = 0, sizestr = 0;
struct MostOftenStruct mos;
for (int i = 0; i < n; i++)
{
prevv = array[i];
count = 0;
for (int j = i; j < n; j++)
{
if (j == i)
{
continue;
}
nextv = array[j];
delta = fabs(nextv - prevv);
if (delta < eps)
{
count++;
}
}
if (count > 0)
{
mos.count = count;
mos.value = array[i];
sizestr++;
flstruct = (struct MostOftenStruct *)realloc(flstruct, sizestr * sizeof(struct MostOftenStruct));
flstruct[sizestr - 1] = mos;
}
}
if (flstruct == NULL) return mos;
count = flstruct[0].count;
for (int i = 0; i < sizestr; i++)
{
if (count < flstruct[i].count)
{
mos.count = flstruct[i].count;
mos.value = flstruct[i].value;
}
}
free(flstruct);
return mos;
}
void fill_array(float array[], const unsigned int n, const float lo_v, const float hi_v)
{
float rndvalue;
for (int i = 0; i < n; i++)
{
rndvalue = lo_v + (float)(rand()) / (float)(RAND_MAX / (hi_v - lo_v));
array[i] = rndvalue;
}
}
void print_array(float array[], const unsigned int n)
{
printf("\n");
for (int i = 0; i < n; i++)
{
printf("a[%3d]=% 10.4f ", i, array[i]);
if ((i + 1) % 5 == 0) printf("\n");
}
printf("\n");
}