digitseen.c 2.3 KB

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