generated from freudenreichan/info2Praktikum-DobleSpiel
wip
This commit is contained in:
parent
7663af9b39
commit
4e198f0078
78
numbers.c
78
numbers.c
@ -14,13 +14,91 @@
|
||||
// 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.
|
||||
|
||||
// Vergleichsfunktion für qsort
|
||||
static int cmp_uint(const void *a, const void *b)
|
||||
{
|
||||
unsigned int x = *(const unsigned int*)a;
|
||||
unsigned int y = *(const unsigned int*)b;
|
||||
|
||||
if (x < y) return -1;
|
||||
if (x > y) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
unsigned int *createNumbers(unsigned int len)
|
||||
{
|
||||
if (len < 2) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
unsigned int *arr = malloc(len * sizeof(unsigned int));
|
||||
if (!arr) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
BinTree *tree = createTree();
|
||||
if (!tree) {
|
||||
free(arr);
|
||||
return NULL;
|
||||
|
||||
/* Zahlen generieren: keine Duplikate */
|
||||
for (unsigned int i = 0; i < len; i++) {
|
||||
|
||||
unsigned int value;
|
||||
int inserted = 0;
|
||||
|
||||
while (!inserted) {
|
||||
value = (rand() % (2 * len)) + 1;
|
||||
|
||||
if (!search(tree, value)) {
|
||||
insert(tree, value);
|
||||
inserted = 1;
|
||||
}
|
||||
}
|
||||
|
||||
arr[i] = value;
|
||||
/* Ein zufälliges Element duplizieren */
|
||||
unsigned int a = rand() % len;
|
||||
unsigned int b;
|
||||
|
||||
do {
|
||||
b = rand() % len;
|
||||
} while (b == a);
|
||||
|
||||
arr[b] = arr[a];
|
||||
|
||||
freeTree(tree);
|
||||
return arr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 || len < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
unsigned int *tmp = malloc(len * sizeof(unsigned int));
|
||||
if (!tmp) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
memcpy(tmp, numbers, len * sizeof(unsigned int));
|
||||
|
||||
qsort(tmp, len, sizeof(unsigned int), cmp_uint);
|
||||
|
||||
unsigned int duplicate = 0;
|
||||
|
||||
for (unsigned int i = 1; i < len; i++) {
|
||||
if (tmp[i] == tmp[i - 1]) {
|
||||
duplicate = tmp[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
free(tmp);
|
||||
return duplicate;
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user