Day 4: Perilous Pier

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • Strlcpy@2@programming.dev
    link
    fedilink
    English
    arrow-up
    5
    ·
    20 hours ago

    C

    Was set on the final solution quite quickly: for every stride and offset, find the first non-? character, then check the remaining characters against it. My only trouble was fumbling some of the loop exits and such. The solution worked well for part 2, I just had to make it read the full input into a buffer.

    Code
    #include <stdio.h>
    
    static int
    solve(const char *word, int len)
    {
    	int stride, off, i,j;
    
    	for (stride=1; stride<len; stride++) {
    		for (off=0; off<stride; off++) {
    			for (i=off; i<len && word[i] == '?'; i+=stride) ;
    			for (j=i+stride; j<len; j+=stride)
    				if (word[j] != '?' && word[j] != word[i])
    					goto next;
    		}
    		break; /* match */
    	next:
    	}
    
    	return stride;
    }
    
    int
    main()
    {
    	static char buf[5*4096];
    	int p1=0, cur=0, len;
    
    	while (fgets(buf+cur, sizeof(buf)-cur, stdin)) {
    		for (len=0; buf[cur+len] && buf[cur+len]!='\n'; len++) ;
    		p1 += solve(buf+cur, len);
    		cur += len;
    	}
    
    	printf("04: %d %d\n", p1, solve(buf, cur));
    }
    

    Bench still looking good:

    day01  0:00.00  1500 Kb  0+83 faults
    day02  0:00.00  1504 Kb  0+84 faults
    day03  0:00.00  1572 Kb  0+88 faults
    day04  0:00.00  1648 Kb  0+90 faults