是否可以减少基于重复排列的if语句?
c#
你好,我正在做这个数学游戏,对于我的最后一个场景,我做了很多重复的代码,但我不确定是否有办法简化它,我在下面提供了链接,所以也许一些经验丰富的程序员可能有一些更优雅的解决方案!例如,我试图生成类似 (a[]b)²[]c[]d 的每个排列,其中括号将被 +、-、* 或 / 替换。我一直在做的只是创建随机百分比 if 语句来选择像“(a+b)²/cd”这样的特定版本是否有可能比我一直在做的“蛮力”和可读性更低的方法?
if(UnityEngine.Random.Range(0,101)>50){
// 50% of being (a+b)²(c)+d
if(UnityEngine.Random.Range(0,101)>50){
ans = ((int) Mathf.Pow((float) a+ (float) b, 2))*c+d;
input.text = "("+a+"+"+b+")"+"²"+"("+c+")"+"+"+d+"=";
Debug.Log("Problem ID: 78");
// 50% of being (a+b)²(c)-d
} else {
ans = ((int) Mathf.Pow((float) a+ (float) b, 2))*c-d;
input.text = "("+a+"+"+b+")"+"²"+"("+c+")"+"-"+d+"=";
Debug.Log("Problem ID: 79");
}
// 50% of being (a-b)²(c)[]d
} else {
// 50% of being (a-b)²(c)+d
if(UnityEngine.Random.Range(0,101)>50){
ans = ((int) Mathf.Pow((float) a- (float) b, 2))*c+d;
input.text = "("+a+"-"+b+")"+"²"+"("+c+")"+"+"+d+"=";
Debug.Log("Problem ID: 80");
// 50% of being (a-b)²(c)-d
} else {
ans = ((int) Mathf.Pow((float) a- (float) b, 2))*c-d;
input.text = "("+a+"-"+b+")"+"²"+"("+c+")"+"-"+d+"=";
Debug.Log("Problem ID: 81");
}
(下面的 Pastebin 了解更多上下文)
https://pastebin.pl/view/d1bfb99e
回答
我很欣赏你想让你的代码更具可读性的愿望。基本思想是拆分 (a) 定义、(b) 选择和 (c) 应用您的运算符。
-
第 1 步:定义
Operators。每个都Operator结合了一个数学运算(例如Addwould be(a, b) => a + b)和一个符号(例如Addwould be"+")。class Operator { public Func<int, int, int> Calculate { get; } public string Symbol { get; } public Operator(Func<int, int, int> calculate, string symbol) { Calculate = calculate; Symbol = symbol; } } private Operator Add = new Operator((a, b) => (a + b), "+"); private Operator Subtract = new Operator((a, b) => (a - b), "-"); -
第 2 步:然后您随机选择您的运算符(我使用了
System.Random,因为我不熟悉 Unity,但可以随意将其替换为您选择的随机数生成器):var rnd = new Random(); private (Operator op1, Operator op2, int problemId) RandomlyChooseProblem() { switch (rnd.Next(4)) { case 0: return (Add, Add, 78); case 1: return (Add, Subtract, 79); case 2: return (Subtract, Add, 80); case 3: return (Subtract, Subtract, 81); default: throw new InvalidOperationException("This should not happen."); } } -
第 3 步:您应用它们:
var (op1, op2, problemId) = RandomlyChooseProblem(); ans = op2.Calculate((int)Math.Pow(op1.Calculate(a, b), 2) * c, d); input.text = $"(a{op1.Symbol}b)²*c{op2.Symbol}d"); Debug.Log($"Problem ID: {problemId}");
添加新的运算符(例如Multiply)或新的问题变体(例如(Add, Multiply, 82))现在只是一行代码。