No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

84 líneas
2.0KB

  1. //
  2. // Created by red on 02/12/19.
  3. //
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <stdint.h>
  8. void print_elems(long* arr, size_t n);
  9. long run(const long* input, size_t n, long noun, long verb);
  10. int main() {
  11. char input_str[350];
  12. memset(input_str, 0, 350*sizeof(char));
  13. scanf("%s", input_str);
  14. long input[140];
  15. char* ptr = input_str;
  16. size_t i = 0;
  17. while (*ptr != 0) { //read until null
  18. input[i] = strtol(ptr, &ptr, 10);
  19. i++;
  20. ptr++; //skip the separator character (',')
  21. }
  22. size_t size = i;
  23. long out = run(input, size, 12, 2);
  24. printf("Value of mem[0] with noun=12, verb=2: %ld\n", out);
  25. //try noun=0..99, verb=0..99
  26. for (i = 0; i < 100; i++) {
  27. for (long j = 0; j < 100; j++) {
  28. long out = run(input, size, i, j);
  29. if (out == 19690720) {
  30. printf("Noun+verb found! n: %ld, v: %ld\n", i, j);
  31. return EXIT_SUCCESS;
  32. }
  33. }
  34. }
  35. }
  36. /**
  37. * @brief run the Intcode state machine with given initial tape
  38. *
  39. * replace the values of mem[1] and mem[2] with noun and verb respectively before running
  40. *
  41. * @param input is a pointer to the tape
  42. * @param n is the memory allocated
  43. * @param noun replaces mem[1]
  44. * @param verb replaces mem[2]
  45. * @return
  46. */
  47. long run(const long* input, size_t n, long noun, long verb) {
  48. long mem[n];
  49. memcpy((void*) mem, (const void*) input, n*sizeof(long));
  50. size_t ptr = 0;
  51. mem[1] = noun;
  52. mem[2] = verb;
  53. while (ptr < n) {
  54. long opcode = mem[ptr];
  55. if (opcode == 1) {
  56. long a = mem[ptr+1];
  57. long b = mem[ptr+2];
  58. long c = mem[ptr+3];
  59. mem[c] = mem[a] + mem[b];
  60. ptr += 4;
  61. } else if (opcode == 2) {
  62. long a = mem[ptr+1];
  63. long b = mem[ptr+2];
  64. long c = mem[ptr+3];
  65. mem[c] = mem[a] * mem[b];
  66. ptr += 4;
  67. } else if (opcode == 99) {
  68. return mem[0];
  69. } else break;
  70. }
  71. return -1;
  72. }
  73. void print_elems(long* arr, size_t n) {
  74. puts("Printing elements of array");
  75. for (size_t i = 0; i < n; i++) {
  76. printf("%ld ", arr[i]);
  77. }
  78. puts("");
  79. }