Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
|
|
@ -0,0 +1,43 @@
|
|||
import std.stdio, std.string, std.array;
|
||||
|
||||
void parseRPN(in string e) {
|
||||
enum nPrec = 9;
|
||||
static struct Info { int prec; bool rAssoc; }
|
||||
immutable /*static*/ opa = ["^": Info(4, true),
|
||||
"*": Info(3, false),
|
||||
"/": Info(3, false),
|
||||
"+": Info(2, false),
|
||||
"-": Info(2, false)];
|
||||
|
||||
writeln("\nPostfix input: ", e);
|
||||
static struct Sf { int prec; string expr; }
|
||||
Sf[] stack;
|
||||
foreach (immutable tok; e.split()) {
|
||||
writeln("Token: ", tok);
|
||||
if (tok in opa) {
|
||||
immutable op = opa[tok];
|
||||
immutable rhs = stack.back;
|
||||
stack.popBack();
|
||||
auto lhs = &stack.back;
|
||||
if (lhs.prec < op.prec ||
|
||||
(lhs.prec == op.prec && op.rAssoc))
|
||||
lhs.expr = "(" ~ lhs.expr ~ ")";
|
||||
lhs.expr ~= " " ~ tok ~ " ";
|
||||
lhs.expr ~= (rhs.prec < op.prec ||
|
||||
(rhs.prec == op.prec && !op.rAssoc)) ?
|
||||
"(" ~ rhs.expr ~ ")" :
|
||||
rhs.expr;
|
||||
lhs.prec = op.prec;
|
||||
} else
|
||||
stack ~= Sf(nPrec, tok);
|
||||
foreach (immutable f; stack)
|
||||
writefln(` %d "%s"`, f.prec, f.expr);
|
||||
}
|
||||
writeln("Infix result: ", stack[0].expr);
|
||||
}
|
||||
|
||||
void main() {
|
||||
foreach (immutable test; ["3 4 2 * 1 5 - 2 3 ^ ^ / +",
|
||||
"1 2 + 3 4 + ^ 5 6 + ^"])
|
||||
parseRPN(test);
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import std.stdio, std.string, std.array, std.algorithm;
|
||||
|
||||
void rpmToInfix(in string str) @safe {
|
||||
static struct Exp { int p; string e; }
|
||||
immutable P = (in Exp pair, in int prec) pure =>
|
||||
pair.p < prec ? format("( %s )", pair.e) : pair.e;
|
||||
immutable F = (in string[] s...) pure nothrow => s.join(' ');
|
||||
|
||||
writefln("=================\n%s", str);
|
||||
Exp[] stack;
|
||||
foreach (const w; str.split) {
|
||||
if (w.isNumeric)
|
||||
stack ~= Exp(9, w);
|
||||
else {
|
||||
const y = stack.back; stack.popBack;
|
||||
const x = stack.back; stack.popBack;
|
||||
switch (w) {
|
||||
case "^": stack ~= Exp(4, F(P(x, 5), w, P(y, 4)));
|
||||
break;
|
||||
case "*", "/": stack ~= Exp(3, F(P(x, 3), w, P(y, 3)));
|
||||
break;
|
||||
case "+", "-": stack ~= Exp(2, F(P(x, 2), w, P(y, 2)));
|
||||
break;
|
||||
default: throw new Error("Wrong part: " ~ w);
|
||||
}
|
||||
}
|
||||
stack.map!q{ a.e }.writeln;
|
||||
}
|
||||
writeln("-----------------\n", stack.back.e);
|
||||
}
|
||||
|
||||
void main() {
|
||||
"3 4 2 * 1 5 - 2 3 ^ ^ / +".rpmToInfix;
|
||||
"1 2 + 3 4 + ^ 5 6 + ^".rpmToInfix;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue