Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct mem{
- long addy;
- long val;
- };
- int main() {
- FILE *fp;
- char str[128];
- char *filename = "D:\\Programming\\AOC2020\\Day 14\\day14in.txt";
- fp = fopen(filename, "r");
- if(fp == NULL) {
- printf("Bad file");
- return 1;
- }
- unsigned long andMask = 9223372036854775807;
- unsigned long orMask = 0;
- int l = 0;
- int l2 = 1;
- int l3 = 0;
- struct mem *mems = malloc(sizeof(struct mem) * l);
- struct mem *mems2 = malloc(sizeof(struct mem) * l3);
- long *p2and = malloc(sizeof(long) * l2);
- long *p2or = malloc(sizeof(long) * l2);
- char mask[36];
- while(fgets(str,255,fp)){
- if(str[1] == 'a'){
- andMask = 9223372036854775807;
- orMask = 0;
- l2 = 1;
- p2and = realloc(p2and,sizeof(long) * l2);
- p2or = realloc(p2or,sizeof(long) * l2);
- p2and[0] = 9223372036854775807;
- p2or[0] = 0;
- for(int i = 7; i < 43; i++){
- if(str[i] == 'X'){
- l2 *= 2;
- p2and = realloc(p2and,sizeof(long) * l2);
- p2or = realloc(p2or,sizeof(long) * l2);
- for(int j = 0; j < l2/2; j++){
- p2and[j+l2/2] = p2and[j] ^ ((unsigned long)1 <<(42-i));
- }
- }
- if(str[i] == '1'){
- orMask |= ((unsigned long)1 << (42-i));
- for(int j = 0; j < l2; j++){
- p2or[j] |= (unsigned long)1 << (42-i);
- }
- }
- if(str[i] == '0'){
- andMask ^= ((unsigned long)1 << (42-i));
- }
- }
- for(int j = 0; j < l2; j++) {
- p2or[j] = 0;
- p2or[j] |= orMask;
- for (int i = 0; i < 36; i++) {
- if (((p2and[j] >> i) % 2) && (str[42-i] == 'X')){
- //printf("t %ld %i\n",p2and[j],i);
- p2or[j] |= (long)1 << i;
- }
- }
- }
- }
- if(str[1] == 'e'){
- long addy = atol(&(str[4]));
- int loc;
- for(int i = 0; ;i++){
- if(str[i] == '='){
- loc = i+2;
- break;
- }
- }
- long val = atol(&(str[loc]));
- // Part 2
- for(int i = 0; i < l2; i++){
- int matched = 0;
- for(int j = 0; j < l3; j++){
- if(mems2[j].addy == (addy & p2and[i] | p2or[i])){
- //printf("rewrite %ld %ld %ld\n",p2and[i],p2or[i],(addy & p2and[i] | p2or[i]));
- mems2[j].val = val;
- matched = 1;
- break;
- }
- }
- if(!matched){
- //printf("add %ld %ld %ld\n",p2and[i],p2or[i],(addy & p2and[i] | p2or[i]));
- mems2 = realloc(mems2,sizeof(struct mem) * ++l3);
- struct mem temp = {(addy & p2and[i] | p2or[i]),val};
- mems2[l3-1] = temp;
- }
- }
- // Part 1
- int assigned = 0;
- for(int i = 0; i < l; i++){
- if(mems[i].addy == addy){
- mems[i].val = (val & andMask) | orMask;
- assigned = 1;
- break;
- }
- }
- if(assigned){continue;}
- mems = realloc(mems,sizeof(struct mem) * ++l);
- struct mem temp = {addy,(val & andMask) | orMask};
- mems[l-1] = temp;
- }
- }
- unsigned long out = 0;
- for(int i = 0; i < l; i++){
- out+= mems[i].val;
- }
- printf("Part 1: %ld\n",out);
- out = 0;
- for(int i = 0; i < l3; i++){
- //printf("addy,val: %ld %i\n",mems2[i].addy,mems2[i].val);
- out+= mems2[i].val;
- }
- printf("part 2: %ld\n", out);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement