Newer
Older
/* average.c
*
* Copyright 2018 Bruce Cowan <bruce@bcowan.me.uk>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <stdio.h>
#include <stdlib.h>
#include "array.h"
#define INT_TO_PTR(x) ((void *) (size_t) (x))
#define PTR_TO_INT(x) ((int) (size_t) (x))
static double
total_val (const Array *array,
ValueFunc func)
{
double total = 0;
size_t length = array_get_length (array);
for (size_t i = 0; i < length; i++)
total += func (array_get (array, i));
return total;
}
static double
average_val (const Array *array,
ValueFunc func)
{
return total_val (array, func) / array_get_length (array);
}
static double
array_to_int (const void *data)
{
return (double) PTR_TO_INT (data);
}
static void
print_array (Array *array)
{
size_t length = array_get_length (array);
printf ("Array at %p is of length %zu\n", array, length);
printf ("Array has capacity %zu\n", array_get_capacity (array));
double total = total_val (array, array_to_int);
double average = average_val (array, array_to_int);
printf ("Array total is %lf\n", total);
printf ("Array average is %lf\n", average);
}
static Array *
create_test_array (size_t start,
size_t end)
{
Array *array = array_new (NULL);
for (size_t i = start; i < end; i++)
array_add (array, INT_TO_PTR (i));
return array;
}
int
main (void)
{
Array *array = create_test_array (0, 100);
print_array (array);
return EXIT_SUCCESS;
}