Skip to content

Instantly share code, notes, and snippets.

@thedeemon
Created January 7, 2014 05:49
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 thedeemon/8295146 to your computer and use it in GitHub Desktop.
Save thedeemon/8295146 to your computer and use it in GitHub Desktop.
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