comitting number.c

This commit is contained in:
dotterweichlu103910 committed 2026-11-18 14:31:06 +01:00
1 parent e7a872252a
commit f43fc2c9db
1 file changed
+66 -4
+66 -4
View File
@@ -14,13 +14,75 @@
// 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.
unsigned int *createNumbers(unsigned int len)
{
static void fillarray(unsigned int array[], unsigned int len) {
//nur in create numbers wegen srand
for (int i = 0; i < len; i++) {
array[i] = rand() % (len * 2 - 1) + 1; // nochmal prüfen ob passt
}
}
static unsigned int getrandomnumber(unsigned int array[], unsigned int len) {
unsigned int number = rand() % (len * 2 - 1) + 1;
for (int i = 0; i < len; i++) {
if (array[i] == number) {
number = rand() % (len * 2 - 1) + 1;
i = 0;
}
}
return number;
}
unsigned int *createNumbers(unsigned int len) {
srand(time(NULL));
unsigned int *numArray = malloc(len * sizeof(unsigned int)); // TODO: schauen wann free machbar
if (numArray == NULL) {
return NULL;
}
// search for duplicate in code
fillarray(numArray, len);
for (unsigned int i = 0; i < --len; i++) {
for (unsigned int j = i; j < len; j++) {
if (numArray[i] == numArray[j]) {
numArray[j] = getrandomnumber(numArray, len);
}
}
}
// create duplicate
unsigned int randNum1 = rand() % (len * 2 - 1) + 1;
unsigned int randNum2 = rand() % (len * 2 - 1) + 1;
while (randNum1 == randNum2) {
randNum2 = rand() % (len * 2 - 1) + 1;
}
numArray[randNum2] = numArray[randNum1];
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)
{
unsigned int getDuplicate(const unsigned int numbers[], unsigned int len) {
unsigned int duplicate = 0;
int compare(const void *a, const void *b);
int (*compareNumbers)(const void *a, const void *b) = &compare;
qsort(numbers, len, sizeof(unsigned int), compareNumbers);
for (unsigned int i = 0; i < len; i++) {
if (numbers[i] == numbers[i + 1] && duplicate != 0) {
return 0;
}
if (numbers[i] == numbers[i + 1] && duplicate == 0) {
duplicate = numbers[i];
}
}
if (duplicate == 0) {
return 0;
}
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;
}