#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int const size = 20;
int main(void) {
srand((unsigned)time(NULL));
int rand_nums[size];
for (int i = 0; i < size; ++i)
rand_nums[i] = rand() % 10;
for (int i = 0; i < size; ++i)
printf("%d ", rand_nums[i]);
puts("");
int n_unique = 0;
for (int i = 0; i < size; ++i) {
for (int j = 0; j < n_unique; ++j) {
if (rand_nums[i] == rand_nums[j])
goto NOT_UNIQUE;
}
rand_nums[n_unique++] = rand_nums[i];
NOT_UNIQUE:;
}
for (int i = 0; i < n_unique; ++i)
printf("%d ", rand_nums[i]);
puts("");
return 0;
}
I won't apologize for the GOTO.
Array Problem in C
If you are OK with destroying the original array, you can even do this in place.
If you are OK with destroying the original array, you can even do this in place.
I won't apologize for the GOTO.#include <stdio.h> #include <stdlib.h> #include <time.h> int const size = 20; int main(void) { srand((unsigned)time(NULL)); int rand_nums[size]; for (int i = 0; i < size; ++i) rand_nums[i] = rand() % 10; for (int i = 0; i < size; ++i) printf("%d ", rand_nums[i]); puts(""); int n_unique = 0; for (int i = 0; i < size; ++i) { for (int j = 0; j < n_unique; ++j) { if (rand_nums[i] == rand_nums[j]) goto NOT_UNIQUE; } rand_nums[n_unique++] = rand_nums[i]; NOT_UNIQUE:; } for (int i = 0; i < n_unique; ++i) printf("%d ", rand_nums[i]); puts(""); return 0; }
Clever!
I understood that @op had a hard requirement of using C, so even though int const size = 20; was the right thing to do in C++, I went for #define. This exercise showed me my C has become rusty, and C++ has spoiled me...
I understood that @op had a hard requirement of using C, so even though int const size = 20; was the right thing to do in C++, I went for #define. This exercise showed me my C has become rusty, and C++ has spoiled me...
Perhaps using the macro is more idiomatic in C, and using `const' is not as good a substitute as it is in C++. The reason this works in C99 is because a local array can have a size specified by a variable (a feature that the OP was already using). If I were to make the array global, it wouldn't have worked (but in C++ this would have been fine).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement