| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- #include <stdbool.h>
- #include <stdio.h>
- #include <stdlib.h>
- void numberprinter(int inarr[], int arrlength) {
- for (int i = 0; i < arrlength; i++) {
- printf("number%d: %d\n", i, inarr[i]);
- }
- }
- struct Darray {
- int *digits;
- int length;
- };
- struct Darray *numbertodigitDarr(int input) {
- // same calculation for arrsize
- int op = 0;
- int tempinput = input;
- while (tempinput) {
- tempinput /= 10;
- op++;
- }
- // allocate memory for struct and array, apparently more ideomatic to have a single malloc
- struct Darray *DigDarr =
- malloc(op * sizeof(int) + sizeof(*DigDarr) + sizeof(int));
- if (DigDarr == NULL) {
- printf("allocation failed");
- exit(0);
- }
- // forgot to assign a value to the pointer variable in the struct.
- DigDarr->digits = (int *)(DigDarr + 1);
- DigDarr->length = op;
- // insert numbers into array in reverse order
- for (int i = op - 1; i >= 0; i--) {
- int last_digit = input % 10;
- printf("last digit: %d\n", last_digit);
- DigDarr->digits[i] = last_digit;
- input /= 10;
- }
- return DigDarr;
- }
- //
- void checkarrdupes(struct Darray input) {
- for (int i = 0; i < input.length; i++) {
- printf("digitstr: %d\n", input.digits[i]);
- }
- int digit_seen[10] = {};
- // kijk door elke arr element
- for (int i = 0; i < input.length; i++) {
- // kijk of input[i] al in digit_seen zit
- if (digit_seen[input.digits[i]]) {
- printf("duplicate number: %d\n", input.digits[i]);
- } else {
- digit_seen[input.digits[i]] = 1;
- }
- }
- }
- int main(void) {
- int n;
- printf("enter a number: ");
- // TODO: scanf is fragile. Try using fgets() and strtol() for robust input
- // sanitization.
- scanf("%d", &n);
- int digitslength = 0;
- struct Darray *mydigitsDarr = numbertodigitDarr(n);
- checkarrdupes(*mydigitsDarr);
- free(mydigitsDarr);
- return 0;
- }
- /*
- somehow I have to find a way to get the number of digits in my number
- for now, we use modulo. whatever remains is the last digit of the number
- we then divide by 10 to remove the last number
- we can keep a counter, and we can put it into an array. however, if we use the
- iterator (which has to start from 0, because we don't know the size of the
- number?) then our number will be the wrong way around.
- malloc, blijkbaar very different
- */
|