Skip to content

Instantly share code, notes, and snippets.

@yamader

yamader/main.d Secret

Last active May 12, 2022 10:31
Show Gist options
  • Save yamader/119c342c444b0fc2f9cfd175d6cea340 to your computer and use it in GitHub Desktop.
Save yamader/119c342c444b0fc2f9cfd175d6cea340 to your computer and use it in GitHub Desktop.
#!/usr/bin/env rdmd
import std;
enum Nums = 5;
enum Ans = 10;
enum Rng = 10;
auto genRnd(size_t len, size_t range) {
auto rnd = Xorshift(unpredictableSeed);
auto a = new int[](len);
foreach(ref n; a) {
rnd.popFront;
n = cast(int)(rnd.front % range);
}
return a;
}
auto calc(string formula, ref int[] used) {
// sanitize
auto nums = "";
size_t i = 0;
foreach(c; formula) switch(c) {
case '0': .. case '9':
nums ~= c; break;
case '-':
if(!nums.length) nums ~= '-';
else switch(nums[$-1]) {
case '0': .. case '9':
nums ~= ' '; break;
case ' ':
nums ~= '-'; break;
default:
throw new Exception("syntax error (minus symbol)");
}
break;
case '+', '*', '/':
nums ~= ' '; break;
case '(', ')', ' ', '\t':
break;
default:
throw new Exception("invalid character in formula");
}
used = nums.split.map!(to!int).array;
auto s = executeShell(`echo "` ~ formula ~ `" | bc`);
if(s.status != 0) throw new Exception("cannot calculate using bc");
return s.output.chomp.to!int;
}
// a - b
auto arrSub(T)(T[] a, T[] b) {
T[] sub = a.dup;
foreach(n; b) {
auto i = sub.countUntil(n);
if(i < 0) throw new Exception("item not found");
sub = sub.remove(i);
}
return sub;
}
void main(string[] args) {
writeln(`四則演算をして最終的に"` ~ Ans.to!string ~ `"を作ろう`);
int[] num = genRnd(Nums, Rng);
while(num.length != 1) {
writeln("今回使える数字は以下のとおりです");
foreach(n; num) writefln("・ %d", n);
try {
int[] used;
auto ans = readln.chomp.calc(used);
num = arrSub(num, used) ~ ans;
} catch(Exception e) {
//stderr.writeln(e);
writeln("不正な入力");
}
writeln();
}
writefln("最終的に残ったのは%d", num[0]);
if(num[0] != Ans) writeln("失敗!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment