C#类.它递归地评估链式模具辊的从左到右的加法和乘法
编辑:
.Replace(" ","")
每次通话都删除了
增加了.Trim()
对int.TryParse
替代
所有工作现在都以单一方法完成
如果没有指定模具面数,则假设为6(参见维基文章)
重构冗余调用以解析"d"的左侧
重构了不必要的if
陈述
缩小:(411字节)
class D{Random r=new Random();public int R(string s){int t=0;var a=s.Split('+');if(a.Count()>1)foreach(var b in a)t+=R(b);else{var m=a[0].Split('*');if(m.Count()>1){t=1;foreach(var n in m)t*=R(n);}else{var d=m[0].Split('d');if(!int.TryParse(d[0].Trim(),out t))t=0;int f;for(int i=1;i扩展形式:
class D { ///Our Random object. Make it a first-class citizen so that it produces truly *random* results Random r = new Random(); ///Roll /// string to be evaluated ///result of evaluated string public int R(string s) { int t = 0; // Addition is lowest order of precedence var a = s.Split('+'); // Add results of each group if (a.Count() > 1) foreach (var b in a) t += R(b); else { // Multiplication is next order of precedence var m = a[0].Split('*'); // Multiply results of each group if (m.Count() > 1) { t = 1; // So that we don't zero-out our results... foreach (var n in m) t *= R(n); } else { // Die definition is our highest order of precedence var d = m[0].Split('d'); // This operand will be our die count, static digits, or else something we don't understand if (!int.TryParse(d[0].Trim(), out t)) t = 0; int f; // Multiple definitions ("2d6d8") iterate through left-to-right: (2d6)d8 for (int i = 1; i < d.Count(); i++) { // If we don't have a right side (face count), assume 6 if (!int.TryParse(d[i].Trim(), out f)) f = 6; int u = 0; // If we don't have a die count, use 1 for (int j = 0; j < (t == 0 ? 1 : t); j++) u += r.Next(1, f); t += u; } } } return t; } }测试用例:
static void Main(string[] args) { var t = new List(); t.Add("2d6"); t.Add("2d6d6"); t.Add("2d8d6 + 4d12*3d20"); t.Add("4d12"); t.Add("4*d12"); t.Add("4d"); // Rolls 4 d6 D d = new D(); foreach (var s in t) Console.WriteLine(string.Format("{0}\t{1}", d.R(s), s)); }
+1它的可读性(与顶部的红宝石解决方案不同)
@Hardwareguy,代码高尔夫的目的根本不是可读性.
2> ephemient..:
Ĵ在cobbal的帮助下,将所有内容挤压成93个字符.
$ jconsole e=:".@([`('%'"_)@.(=&'/')"0@,)@:(3 :'":(1".r{.y)([:+/>:@?@$) ::(y&[)0".}.y}.~r=.y i.''d'''@>)@;: e '3d6 + 12' 20 e 10$,:'3d6 + 12' 19 23 20 26 24 20 20 20 24 27 e 10$,:'4*d12 + 3' 28 52 56 16 52 52 52 36 44 56 e 10$,:'d100' 51 51 79 58 22 47 95 6 5 64