forked from freudenreichan/info2Praktikum-DobleSpiel
89 lines
2.7 KiB
C
89 lines
2.7 KiB
C
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
#include <time.h>
|
|
#include <string.h>
|
|
#include "numbers.h"
|
|
#include "bintree.h"
|
|
|
|
//TODO: getDuplicate und createNumbers implementieren
|
|
/* * * Erzeugen eines Arrays mit der vom Nutzer eingegebenen Anzahl an Zufallszahlen.
|
|
* Sicherstellen, dass beim Befüllen keine Duplikate entstehen.
|
|
* Duplizieren eines zufälligen Eintrags im Array.
|
|
* in `getDuplicate()`: Sortieren des Arrays und Erkennen der doppelten Zahl durch Vergleich benachbarter Elemente. */
|
|
|
|
// Returns len random numbers between 1 and 2x len in random order which are all different, except for two entries.
|
|
// Returns NULL on errors. Use your implementation of the binary search tree to check for possible duplicates while
|
|
// creating random numbers.
|
|
|
|
static int compare(const void *a, const void *b);
|
|
|
|
unsigned int *createNumbers(unsigned int len) {
|
|
if (len < 3
|
|
) {
|
|
return NULL;
|
|
}
|
|
|
|
srand(time(NULL));
|
|
int duplicate = 0;
|
|
TreeNode *tree = NULL;
|
|
unsigned int *numArray = malloc(len * sizeof(unsigned int));
|
|
|
|
for (unsigned int i = 0; i < len; i++) {
|
|
unsigned int randNumber = rand() %(len * 2) + 1;
|
|
numArray[i] = randNumber;
|
|
tree = addToTree(tree, &randNumber, sizeof(randNumber), compare, &duplicate);
|
|
if (duplicate == 1) {
|
|
i--;
|
|
}
|
|
}
|
|
// create duplicate
|
|
unsigned int randNum1 = rand() % (len);
|
|
unsigned int randNum2 = rand() % (len);
|
|
while (randNum1 == randNum2) {
|
|
randNum2 = rand() % (len);
|
|
}
|
|
numArray[randNum2] = numArray[randNum1];
|
|
clearTree(tree);
|
|
return numArray;
|
|
}
|
|
|
|
|
|
// Returns only the only number in numbers which is present twice. Returns zero on errors.
|
|
unsigned int getDuplicate(const unsigned int numbers[], unsigned int len) {
|
|
if (numbers == NULL || len == 0) {
|
|
return 0;
|
|
}
|
|
unsigned int *array = calloc(len, sizeof(unsigned int));
|
|
if (array == NULL) {
|
|
return 0;
|
|
}
|
|
memcpy(array ,numbers, sizeof(unsigned int) * len);
|
|
|
|
unsigned int duplicate = 0;
|
|
int (*compareNumbers)(const void *a, const void *b) = &compare;
|
|
qsort(array, len, sizeof(unsigned int), compareNumbers);
|
|
|
|
for (unsigned int i = 0; i < len-1; i++) {
|
|
if (array[i] == array[i + 1] && duplicate != 0) {
|
|
free(array);
|
|
return 0;
|
|
}
|
|
if (array[i] == array[i + 1] && duplicate == 0) {
|
|
duplicate = array[i];
|
|
}
|
|
}
|
|
if (duplicate == 0) {
|
|
free(array);
|
|
return 0;
|
|
}
|
|
free(array);
|
|
return duplicate;
|
|
}
|
|
|
|
int compare(const void *a, const void *b) {
|
|
unsigned int x = *((unsigned int *) a);
|
|
unsigned int y = *((unsigned int *) b);
|
|
int comp = x - y;
|
|
return comp;
|
|
}
|