RosettaCodeData/Task/Josephus-problem/D/josephus-problem-1.d

28 lines
685 B
D
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
import std.stdio, std.algorithm, std.array, std.string, std.range;
2015-02-20 00:35:01 -05:00
T pop(T)(ref T[] items, in size_t i) pure /*nothrow*/ @safe /*@nogc*/ {
2013-04-10 21:29:02 -07:00
auto aux = items[i];
2015-02-20 00:35:01 -05:00
items = items.remove(i);
2013-04-10 21:29:02 -07:00
return aux;
}
2015-02-20 00:35:01 -05:00
string josephus(in int n, in int k) pure /*nothrow*/ @safe {
2013-06-05 21:47:54 +00:00
auto p = n.iota.array;
2013-04-10 21:29:02 -07:00
int i;
2015-02-20 00:35:01 -05:00
immutable(int)[] seq;
2013-04-10 21:29:02 -07:00
while (!p.empty) {
i = (i + k - 1) % p.length;
seq ~= p.pop(i);
}
2013-06-05 21:47:54 +00:00
return format("Prisoner killing order:\n%(%(%d %)\n%)." ~
"\nSurvivor: %d",
2013-10-27 22:24:23 +00:00
seq[0 .. $ - 1].chunks(20), seq[$ - 1]);
2013-04-10 21:29:02 -07:00
}
2015-02-20 00:35:01 -05:00
void main() /*@safe*/ {
2013-06-05 21:47:54 +00:00
josephus(5, 2).writeln;
writeln;
josephus(41, 3).writeln;
2013-04-10 21:29:02 -07:00
}