Skip to content

Instantly share code, notes, and snippets.

@vurtun
Last active December 8, 2023 09:34
Show Gist options
  • Save vurtun/58d273684a5f6fd8826c5e753716fdc2 to your computer and use it in GitHub Desktop.
Save vurtun/58d273684a5f6fd8826c5e753716fdc2 to your computer and use it in GitHub Desktop.
AoC 2023
#include <stdio.h>
#include <limits.h>
#define byte4_dup(c) (((c)<<24u)|((c)<<16u)|((c)<<8u)|(c))
#define byte4_cmp_lt(x,n) (((x)-~0UL/255u*(n))&~(x)&~0UL/255u*128u) // x>=0; 0<=n<=128
#define byte4_cmp_gt(x,n) (((x)+~0UL/255*(127-(n))|(x))&~0UL/255*128) // x>=0; 0<=n<=127
#ifdef _MSC_VER
static int bit_ffs32(unsigned int u) {_BitScanForward(&u, u); return (int)(u);}
static int bit_fls32(unsigned int u) {_BitScanBackward(&u, u); return 31-(int)(u);}
#else /* GCC, CLANG */
#define bit_ffs32(u) __builtin_ctz(u)
#define bit_fls32(u) (31-__builtin_clz(u))
#endif
#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
int main() {
static const char *in[] = {
"1abc2 ",
"pqr3stu8vwx",
"a1b2c3d4e5f",
"treb7uchet ",
};
for (int i = 0; i < 4; ++i) {
const char *s = in[i];
int lhs = INT_MAX, rhs = 0;
for (int at = 0;; at += 4) {
/* check for number character */
unsigned v = *(unsigned*)(s + at);
unsigned n = v - byte4_dup('0');
unsigned e = byte4_cmp_lt(n,10);
if (e) {
int ffs = at + (bit_ffs32(e) >> 3);
int fls = at + (bit_fls32(e) >> 3);
lhs = min(ffs, lhs);
rhs = max(fls, rhs);
}
/* check for '\0' */
unsigned c = (~v) & 0x80808080;
if ((v - 0x01010101) & c) {
break;
}
}
int res = (s[lhs] - '0') * 10 + (s[rhs] - '0');
printf("[%d] = %d\n", i, res);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment