|
- //
- // Created by red on 02/12/19.
- //
-
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <stdint.h>
-
- void print_elems(long* arr, size_t n);
- long run(const long* input, size_t n, long noun, long verb);
-
- int main() {
- char input_str[350];
- memset(input_str, 0, 350*sizeof(char));
- scanf("%s", input_str);
- long input[140];
- char* ptr = input_str;
- size_t i = 0;
- while (*ptr != 0) { //read until null
- input[i] = strtol(ptr, &ptr, 10);
- i++;
- ptr++; //skip the separator character (',')
- }
- size_t size = i;
- long out = run(input, size, 12, 2);
- printf("Value of mem[0] with noun=12, verb=2: %ld\n", out);
- //try noun=0..99, verb=0..99
- for (i = 0; i < 100; i++) {
- for (long j = 0; j < 100; j++) {
- long out = run(input, size, i, j);
- if (out == 19690720) {
- printf("Noun+verb found! n: %ld, v: %ld\n", i, j);
- return EXIT_SUCCESS;
- }
- }
- }
- }
-
- /**
- * @brief run the Intcode state machine with given initial tape
- *
- * replace the values of mem[1] and mem[2] with noun and verb respectively before running
- *
- * @param input is a pointer to the tape
- * @param n is the memory allocated
- * @param noun replaces mem[1]
- * @param verb replaces mem[2]
- * @return
- */
- long run(const long* input, size_t n, long noun, long verb) {
- long mem[n];
- memcpy((void*) mem, (const void*) input, n*sizeof(long));
- size_t ptr = 0;
- mem[1] = noun;
- mem[2] = verb;
- while (ptr < n) {
- long opcode = mem[ptr];
- if (opcode == 1) {
- long a = mem[ptr+1];
- long b = mem[ptr+2];
- long c = mem[ptr+3];
- mem[c] = mem[a] + mem[b];
- ptr += 4;
- } else if (opcode == 2) {
- long a = mem[ptr+1];
- long b = mem[ptr+2];
- long c = mem[ptr+3];
- mem[c] = mem[a] * mem[b];
- ptr += 4;
- } else if (opcode == 99) {
- return mem[0];
- } else break;
- }
- return -1;
- }
-
- void print_elems(long* arr, size_t n) {
- puts("Printing elements of array");
- for (size_t i = 0; i < n; i++) {
- printf("%ld ", arr[i]);
- }
- puts("");
- }
|