Day 2
							parent
							
								
									193b462b98
								
							
						
					
					
						commit
						60fafe8ee1
					
				| @ -0,0 +1,85 @@ | ||||
| #include "stdlib.h" | ||||
| #include "stdio.h" | ||||
| #include "string.h" | ||||
| 
 | ||||
| int numbers[2048*2048]; | ||||
| int sizes[2048]; | ||||
| 
 | ||||
| int _is_safe(int n, int size, int* levels) { | ||||
|   if(size <= 0) return 0; | ||||
| 
 | ||||
|   int current = -1; | ||||
|   int direction = 0; | ||||
| 
 | ||||
|   for(int i = 0; i < size; i++) { | ||||
|     if(i == n) continue; | ||||
|     int next = levels[i]; | ||||
|     if(current == -1) { | ||||
|       current = next; | ||||
|     } else if(direction == 0 && (next < current && next >= current - 3)) { | ||||
|       direction = 1; | ||||
|     } else if(direction == 0 && (next > current && next <= current + 3)) { | ||||
|       direction = 2; | ||||
|     } else if(direction == 0) { | ||||
|       return 0; | ||||
|     } else if(direction == 1 && (next >= current || next < current - 3)) { | ||||
|       return 0; | ||||
|     } else if(direction == 2 && (next <= current || next > current + 3)) { | ||||
|       return 0; | ||||
|     } | ||||
| 
 | ||||
|     current = next; | ||||
|   } | ||||
| 
 | ||||
|   return 1; | ||||
| } | ||||
| 
 | ||||
| int is_safe(int size, int* levels) { | ||||
|   for(int i = -1; i < size; i++) { | ||||
|     if(_is_safe(i, size, levels)) return 1; | ||||
|   } | ||||
|   return 0; | ||||
| } | ||||
| 
 | ||||
| int main(int argc, char* argv[]) { | ||||
|   if(argc < 2) { | ||||
|     fprintf(stderr, "Filename required\n"); | ||||
|     return 1; | ||||
|   } | ||||
| 
 | ||||
|   FILE* file = fopen(argv[1], "r"); | ||||
|   if(file == NULL) { | ||||
|     fprintf(stderr, "Could not open %s\n", argv[1]); | ||||
|     return 2; | ||||
|   } | ||||
|    | ||||
|   memset(numbers, 0, sizeof(numbers)); | ||||
|   char* line = NULL; | ||||
|   size_t line_size = 0; | ||||
|   int i = 0; | ||||
|   while(getline(&line, &line_size, file) > 0) { | ||||
|     char* save = NULL; | ||||
|     char* token = strtok_r(line, " ", &save); | ||||
|     if(token == NULL || token[0] == '\n' || token[0] == '\0') break; | ||||
|     int j = 0; | ||||
|     do { | ||||
|       numbers[i*2048 + j] = atoi(token); | ||||
|       j += 1; | ||||
|     } while((token = strtok_r(NULL, " ", &save))); | ||||
|     sizes[i] = j; | ||||
|     i += 1; | ||||
|   } | ||||
|   free(line); | ||||
| 
 | ||||
|   int safe = 0; | ||||
|   for(i = 0; i < 2048; i++) { | ||||
|     if(sizes[i] == 0) continue; | ||||
|     if(is_safe(sizes[i], &numbers[2048*i])) { | ||||
|       safe += 1; | ||||
|     } | ||||
|   } | ||||
| 
 | ||||
|   fprintf(stdout, "Safe: %d\n", safe); | ||||
| 
 | ||||
|   return 0; | ||||
| } | ||||
		Loading…
	
		Reference in New Issue