Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Direct translation of github.com/ttsiodras/PrimeSpirals into D.
module main;
import std.stdio, std.range, std.algorithm, std.conv, std.typecons, std.math;
auto primeSpiralPixels()
{
auto primesSoFar = [2];
int color(int x) {
foreach(prime; primesSoFar.until!(p => p > sqrt(cast(float)x)))
if (0 == x % prime) return 255;
primesSoFar ~= x;
return 0;
}
return chain([255,0], iota(3, int.max).map!color);
}
auto next(R)(ref R range) { auto x = range.front; range.popFront(); return x; }
void main(string[] argv)
{
int[Tuple!(int,int)] screen;
auto rows = argv.length == 1 ? 202 : argv[1].to!int;
auto moves = [[1,0], [0,-1], [-1,0], [0,1]].cycle;
auto move = moves.next, check = moves.next;
auto lastPosition = [rows/2, rows/2];
foreach(c; primeSpiralPixels.take(rows * rows)) {
screen[tuple(lastPosition[0], lastPosition[1])] = c;
lastPosition[] += move[];
auto checkPosition = tuple(lastPosition[0] + check[0], lastPosition[1] + check[1]);
if (checkPosition !in screen) {
move = check; check = moves.next;
}
}
auto image = File("ulam.pgm", "w");
image.write("P5\n", rows - 1, " ", rows - 1, "\n255\n");
foreach(row; 1..rows)
foreach(col; 1..rows)
image.write(screen[tuple(col, row)].to!char);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment