2025-12-02 10:02:34 +01:00

97 lines
2.2 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include "numbers.h"
#include "bintree.h"
// --- Hilfsfunktion: Vergleich von unsigned int ------------------
static int compareUInt(const void *a, const void *b)
{
unsigned int ua = *(const unsigned int *)a;
unsigned int ub = *(const unsigned int *)b;
if (ua < ub) return -1;
if (ua > ub) return 1;
return 0;
}
// Returns len random numbers between 1 and 2x len in random order which are all different,
// except for two entries. Uses the binary search tree to avoid duplicates.
unsigned int *createNumbers(unsigned int len)
{
if (len < 2)
return NULL;
unsigned int *arr = malloc(sizeof(unsigned int) * len);
if (!arr)
return NULL;
srand((unsigned int)time(NULL));
TreeNode *root = NULL;
unsigned int count = 0;
while (count < len - 1) // generate len-1 UNIQUE numbers
{
unsigned int val = (rand() % (2 * len)) + 1;
int isDup = 0;
root = addToTree(root, &val, sizeof(unsigned int), compareUInt, &isDup);
if (!isDup)
{
arr[count++] = val;
}
}
// pick a random existing value to duplicate
unsigned int duplicateIndex = rand() % (len - 1);
arr[len - 1] = arr[duplicateIndex];
clearTree(root);
return arr;
}
// Returns the only number in the array that occurs twice.
unsigned int getDuplicate(const unsigned int numbers[], unsigned int len)
{
if (!numbers || len < 2)
return 0;
// copy array
unsigned int *copy = malloc(sizeof(unsigned int) * len);
if (!copy)
return 0;
memcpy(copy, numbers, sizeof(unsigned int) * len);
// sort
for (unsigned int i = 0; i < len - 1; i++)
{
for (unsigned int j = i + 1; j < len; j++)
{
if (copy[j] < copy[i])
{
unsigned int t = copy[i];
copy[i] = copy[j];
copy[j] = t;
}
}
}
// find adjacent duplicate
unsigned int duplicate = 0;
for (unsigned int i = 0; i < len - 1; i++)
{
if (copy[i] == copy[i + 1])
{
duplicate = copy[i];
break;
}
}
free(copy);
return duplicate;
}