digitseen.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. void numberprinter(int inarr[], int arrlength) {
  5. for (int i = 0; i < arrlength; i++) {
  6. printf("number%d: %d\n", i, inarr[i]);
  7. }
  8. }
  9. struct Darray {
  10. int *digits;
  11. int length;
  12. };
  13. struct Darray *numbertodigitDarr(int input) {
  14. // same calculation for arrsize
  15. int op = 0;
  16. int tempinput = input;
  17. while (tempinput) {
  18. tempinput /= 10;
  19. op++;
  20. }
  21. // allocate memory for struct and array, apparently more ideomatic to have a single malloc
  22. struct Darray *DigDarr =
  23. malloc(op * sizeof(int) + sizeof(*DigDarr) + sizeof(int));
  24. if (DigDarr == NULL) {
  25. printf("allocation failed");
  26. exit(0);
  27. }
  28. // forgot to assign a value to the pointer variable in the struct.
  29. DigDarr->digits = (int *)(DigDarr + 1);
  30. DigDarr->length = op;
  31. // insert numbers into array in reverse order
  32. for (int i = op - 1; i >= 0; i--) {
  33. int last_digit = input % 10;
  34. printf("last digit: %d\n", last_digit);
  35. DigDarr->digits[i] = last_digit;
  36. input /= 10;
  37. }
  38. return DigDarr;
  39. }
  40. //
  41. void checkarrdupes(struct Darray input) {
  42. for (int i = 0; i < input.length; i++) {
  43. printf("digitstr: %d\n", input.digits[i]);
  44. }
  45. int digit_seen[10] = {};
  46. // kijk door elke arr element
  47. for (int i = 0; i < input.length; i++) {
  48. // kijk of input[i] al in digit_seen zit
  49. if (digit_seen[input.digits[i]]) {
  50. printf("duplicate number: %d\n", input.digits[i]);
  51. } else {
  52. digit_seen[input.digits[i]] = 1;
  53. }
  54. }
  55. }
  56. int main(void) {
  57. int n;
  58. printf("enter a number: ");
  59. // TODO: scanf is fragile. Try using fgets() and strtol() for robust input
  60. // sanitization.
  61. scanf("%d", &n);
  62. int digitslength = 0;
  63. struct Darray *mydigitsDarr = numbertodigitDarr(n);
  64. checkarrdupes(*mydigitsDarr);
  65. free(mydigitsDarr);
  66. return 0;
  67. }
  68. /*
  69. somehow I have to find a way to get the number of digits in my number
  70. for now, we use modulo. whatever remains is the last digit of the number
  71. we then divide by 10 to remove the last number
  72. we can keep a counter, and we can put it into an array. however, if we use the
  73. iterator (which has to start from 0, because we don't know the size of the
  74. number?) then our number will be the wrong way around.
  75. malloc, blijkbaar very different
  76. */