Created
November 26, 2019 04:19
-
-
Save alphaKAI/e5df69e40a7fb1f9edc143d5daa09085 to your computer and use it in GitHub Desktop.
Runtime O(1) FizzBuzz by nested string-mixin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio; | |
import std.format; | |
import std.traits; | |
import std.array; | |
mixin(q{ | |
enum string fizzbuzz_code = { | |
enum string prim_fb(int M)() { | |
static if (M % 15 == 0) { return "writeln(\"fizzbuzz\");"; } | |
else if (M % 3 == 0) { return "writeln(\"fizz\");"; } | |
else if (M % 5 == 0) { return "writeln(\"buzz\");"; } | |
else { return "writeln(\"%d\");".format(M); } | |
} | |
enum string[] gen_fb_code(int M, int t = 0, string[] tmp = [])() { | |
static if (M == t) { | |
return tmp; | |
} else { | |
return gen_fb_code!(M, t + 1, tmp ~ prim_fb!(t)); | |
} | |
} | |
enum string header = "void fizzbuzz() {"; | |
enum string footer = "}"; | |
return header ~ gen_fb_code!(N).join("\n") ~ footer; | |
}(); | |
mixin(fizzbuzz_code); | |
}); | |
enum N = 30; | |
void main() { | |
fizzbuzz(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment