Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import std.algorithm;
- import std.conv;
- import std.exception;
- import std.math;
- import std.range;
- import std.stdio;
- import std.typecons;
- void main()
- {
- enum count = 100;
- enum verbose = false;
- iota(1, count + 1)
- .map!(i => tuple!("n", "naive", "formula")(i, i.solveNaively(verbose), i.solveViaFormula))
- .each!((solution)
- {
- "n %s -> %s (naive), %s (formula) ".writefln(solution.n, solution.naive, solution.formula);
- enforce(solution.naive == solution.formula, "solutions don't match");
- });
- }
- class Node
- {
- uint n;
- Node next;
- this(uint n) { this.n = n; }
- }
- uint solveNaively(uint n, bool verbose)
- {
- auto ring = makeRing(n);
- if (verbose)
- "==> %s".writefln(ring.ringToString);
- Node node = ring;
- while (node.next != node)
- {
- if (verbose)
- "%s -> %s".writefln(node.n, node.next.n);
- node = node.next = node.next.next;
- }
- return node.n;
- }
- uint solveViaFormula(uint n)
- {
- return (n - pow(2, cast(uint) log2(n))) * 2 + 1;
- }
- Node makeRing(uint count)
- {
- enforce(count);
- auto nodes = iota(count).map!(i => new Node(i + 1)).array;
- nodes.each!((i, node) => node.next = (i < count - 1 ? nodes[i + 1] : nodes.front));
- return nodes.front;
- }
- string ringToString(Node ring)
- {
- string s;
- Node node = ring;
- do
- {
- s ~= (s.empty ? "" : ", ") ~ node.n.to!string;
- node = node.next;
- } while (node != ring);
- return s;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement