Skip to content

Instantly share code, notes, and snippets.

@skeeto
Created March 6, 2024 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skeeto/70e07fad4182a05f3ac2ee4f532117ef to your computer and use it in GitHub Desktop.
Save skeeto/70e07fad4182a05f3ac2ee4f532117ef to your computer and use it in GitHub Desktop.
// $ cc -o graph graph.c
// $ ./a.out
// Ref: https://old.reddit.com/r/roguelikedev/comments/1b7pa9w/
#include <stdio.h>
static int rand31(unsigned long long *s)
{
*s = *s*0x3243f6a8885a308dU + 1;
return (int)(*s >> 33);
}
int main(void)
{
enum {
width = 15,
height = 13,
};
unsigned long long rng[1] = {(size_t)rng};
// Normally-distributed seed position
int verts = 1 << __builtin_popcount(rand31(rng) >> 24);
for (int y = 0; y < height; y++) {
// Draw vertices
for (int x = 0; x < width; x++) {
putchar(verts&(1<<x) ? 'O' : ' ');
putchar(x==width-1 ? '\n' : ' ');
}
if (y == height-1) break;
// Initialze edge display as all spaces
char row[2*width+1] = {0};
for (int x = 0; x < width; x++) {
row[2*x+0] = row[2*x+1] = ' ';
}
int next = 0;
do {
// Slanted edges
for (int x = 0; x < width-1; x++) {
int left = verts & (1<<(x+0));
int right = verts & (1<<(x+1));
if (left && right) {
switch (rand31(rng) >> 28) {
case 1: row[2*x+1] = '\\';
next |= 1 << (x+1);
break;
case 2: row[2*x+1] = '/';
next |= 1 << x;
}
} else if (left) {
if (rand31(rng) >> 29) {
row[2*x+1] = '\\';
next |= 1 << (x+1);
}
} else if (right) {
if (rand31(rng) >> 29) {
row[2*x+1] = '/';
next |= 1 << x;
}
}
}
// Vertical edges
for (int x = 0; x < width; x++) {
if (verts & (1<<x)) {
if (!(rand31(rng) >> 29)) {
row[2*x] = '|';
next |= 1 << x;
}
}
}
} while (!next); // must propagate at least one vertex
puts(row);
verts = next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment