pico-scale
util.c
Go to the documentation of this file.
1 // MIT License
2 //
3 // Copyright (c) 2022 Daniel Robertson
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in all
13 // copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 // SOFTWARE.
22 
23 #include <assert.h>
24 #include <stdlib.h>
25 #include "../include/util.h"
26 
28  const int32_t* const arr,
29  const size_t len,
30  double* const avg) {
31 
32  assert(arr != NULL);
33  assert(len > 0);
34  assert(avg != NULL);
35 
36  long long int total = 0;
37 
38  for(size_t i = 0; i < len; ++i) {
39  total += arr[i];
40  }
41 
42  *avg = (double)total / len;
43 
44 }
45 
47  int32_t* const arr,
48  const size_t len,
49  double* const med) {
50 
51  assert(arr != NULL);
52  assert(len > 0);
53  assert(med != NULL);
54 
55  qsort(
56  arr,
57  len,
58  sizeof(int32_t),
60 
66  if (len % 2 == 0) {
67  *med = (arr[(len / 2) - 1] + arr[len / 2]) / 2.0;
68  }
69  else if (len > 1) {
70  *med = (double)arr[(len / 2) + 1];
71  }
72  else {
73  *med = (double)arr[0];
74  }
75 
76 }
77 
79  const void* a,
80  const void* b) {
81 
82  assert(a != NULL);
83  assert(b != NULL);
84 
85  const int32_t* restrict const pA = (const int32_t* const)a;
86  const int32_t* restrict const pB = (const int32_t* const)b;
87 
88  //https://stackoverflow.com/a/10996555/570787
89  return (*pA < *pB) ? -1 : (*pA > *pB);
90 
91 }
void util_median(int32_t *const arr, const size_t len, double *const med)
Calculates the median value from an array of signed 32-bit integers.
Definition: util.c:46
void util_average(const int32_t *const arr, const size_t len, double *const avg)
Calculates the average value from an array of signed 32-bit integers.
Definition: util.c:27
int util__median_compare_func(const void *a, const void *b)
Definition: util.c:78