Skip to content

Instantly share code, notes, and snippets.

@thedeemon
Created January 5, 2015 17:07
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/b3969f49df0cbc6eb376 to your computer and use it in GitHub Desktop.
Save thedeemon/b3969f49df0cbc6eb376 to your computer and use it in GitHub Desktop.
Micro interpreter in D
import std.stdio, std.algorithm;
struct Exp {
enum Tag { IfGt, Swap, Copy }
Tag tag;
int i, j;
Exp[] bl1, bl2;
}
int eval(int[] a, const ref Exp e) {
final switch(e.tag) {
case Exp.Tag.IfGt: return 1 + evalBlock(a, a[e.i] > a[e.j] ? e.bl1 : e.bl2);
case Exp.Tag.Swap:
auto ai = a[e.i], aj = a[e.j];
a[e.i] = aj; a[e.j] = ai; return 1;
case Exp.Tag.Copy:
a[e.i] = a[e.j]; return 1;
}
}
int evalBlock(int[] a, const Exp[] blk) {
int sum = 0;
foreach(ref e; blk) sum += eval(a, e);
return sum;
}
int numSteps(const Exp[] blk, const int[] ua) {
int[100] stack = void;
auto a = stack[0 .. ua.length];
a[] = ua[];
auto n = evalBlock(a, blk);
return (a[1]==2 && a[6]==7) ? n : 25000;
}
int[][] inputs;
int calcScore(const Exp[] blk) { return inputs.map!(a => numSteps(blk, a)).sum; }
auto cmp(int i, int j) { return Exp(Exp.Tag.IfGt, i, j, [Exp(Exp.Tag.Swap, i, j)], []); }
void main(string[] argv) {
int[] ns = [1,2,3,4,5,6,7,8], zs = [0,0,0,0];
do inputs ~= ns ~ zs; while (nextPermutation(ns));
auto sornet =
[cmp(0, 1), cmp(2, 3), cmp(4, 5), cmp(6, 7),
cmp(0, 2), cmp(1, 3), cmp(4, 6), cmp(5, 7),
cmp(1, 2), cmp(5, 6), cmp(0, 4), cmp(3, 7),
cmp(1, 5), cmp(2, 6),
cmp(1, 4), cmp(3, 6)];
int s = 999999999;
foreach(i; 0..40) s = min(s, calcScore(sornet));
writeln(s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment