随机生成四则运算表达式【Unity】
根据自己项目需求调整代码中表达式的公共方法
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
/// <summary>
/// 四则运算管理类
/// </summary>
public class FourArithmetic : Singleton<FourArithmetic>
{
#region 表达式方法
public string expression = "";
/// <summary>
/// 随机数加法表达式
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
public void RandomNumAdd(int min, int max)
{
expression = "";
//System.Random ran = new System.Random();
//int n1 = ran.Next(min, max);
//int n2 = ran.Next(min, max);
int n1 = UnityEngine.Random.Range(min, max);
int n2 = UnityEngine.Random.Range(min, max); if (n1 < 0) expression += "(" + n1 + ")";
else expression += n1;
expression += "+";
if (n2 < 0) expression += "(" + n2 + ")";
else expression += n2;
} /// <summary>
/// 随机数减法表达式
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
public void RandomNumMinus(int min, int max)
{
expression = "";
//System.Random ran = new System.Random();
//int n1 = ran.Next(min, max);
//int n2 = ran.Next(min, max);
int n1 = UnityEngine.Random.Range(min, max);
int n2 = UnityEngine.Random.Range(min, max); if (n1 > n2)
{
if (n1 < 0) expression += "(" + n1 + ")";
else expression += n1;
expression += "-";
if (n2 < 0) expression += "(" + n2 + ")";
else expression += n2;
}
else
{
RandomNumMinus(min, max);
}
} /// <summary>
/// 随机数乘法表达式
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
public void RandomNumMultiply(int min, int max)
{
expression = "";
//System.Random ran = new System.Random();
//int n1 = ran.Next(min, max);
//int n2 = ran.Next(0, 3);
int n1, n2;
if (max > 10)
{
n1 = UnityEngine.Random.Range(min, max);
n2 = UnityEngine.Random.Range(1, 3);
}
else
{
n1 = UnityEngine.Random.Range(min, max);
n2 = UnityEngine.Random.Range(min, max);
} if (n1 < 0) expression += "(" + n1 + ")";
else expression += n1;
expression += "*";
if (n2 < 0) expression += "(" + n2 + ")";
else expression += n2;
} /// <summary>
/// 随机数除法表达式
/// </summary>
public void RandomNumDivide(int min, int max)
{
expression = "";
//System.Random ran = new System.Random();
//int n1 = ran.Next(min, max);
//int n2 = ran.Next(min, max);
int n1 = UnityEngine.Random.Range(min, max);
int n2 = UnityEngine.Random.Range(1, 10);
if (n1 < 0) expression += "(" + n1 + ")";
else expression += n1;
expression += "/";
if (n2 < 0) expression += "(" + n2 + ")";
else expression += n2;
} /// <summary>
/// 三个数以上四则运算混合计算表达式
/// </summary>
/// <param name="select">选择对应的表达式</param>
/// <param name="min"></param>
/// <param name="max"></param>
public void MixedCalculation(int select, int min, int max)
{
System.Random ran = new System.Random();
//int n1, n2;
expression = "";
switch (select)
{
case 0://带括号三个数字的混合计算
{
int n1 = ran.Next(min, max);
int n2 = ran.Next(min, max);
int n3 = ran.Next(1, 3);
expression += "(";
if (n1 < 0) expression += "(" + n1 + ")";
else expression += n1;
if (ran.Next(0, 2) == 1) expression += "+";
else expression += "-";
if (n2 < 0) expression += "(" + n2 + ")";
else expression += n2 + ")";
expression += "*" + n3;
break;
}
case 2: //三个数字的加减混合表达式
{
int n1 = ran.Next(min, max);
int n2 = ran.Next(min, max);
int n3 = ran.Next(min, max);
expression += n1;
AddAndMinuMix(n2);
AddAndMinuMix(n3);
break;
}
case 3: //三个数字的混合计算
{
int n1 = ran.Next(min, max);
int n2 = ran.Next(min, max);
int n3 = ran.Next(min, max);
expression += n1;
AddMinusMultiplyMix(n2);
AddMinusMultiplyMix(n3);
break;
}
case 4: //四个数字的混合计算
{
int n1 = ran.Next(min, max);
int n2 = ran.Next(min, max);
int n3 = ran.Next(min, max);
int n4 = ran.Next(min, max);
expression += n1;
AddMinusMultiplyMix(n2);
AddMinusMultiplyMix(n3);
AddMinusMultiplyMix(n4);
break;
}
case 5: //五个数字的混合计算
{
int n1 = ran.Next(min, max);
int n2 = ran.Next(min, max);
int n3 = ran.Next(min, max);
int n4 = ran.Next(min, max);
int n5 = ran.Next(min, max);
expression += n1;
AddMinusMultiplyMix(n2);
AddMinusMultiplyMix(n3);
AddMinusMultiplyMix(n4);
AddMinusMultiplyMix(n5);
break;
}
default:
break;
} } /// <summary>
/// 加减混合表达式
/// </summary>
/// <param name="nextNum"></param>
private void AddAndMinuMix(int nextNum)
{
int random = UnityEngine.Random.Range(0, 2);
if (random.Equals(0))
{
expression += "+";
}
else if (random.Equals(1))
{
expression += "-";
}
expression += nextNum;
} /// <summary>
/// 加减乘混合表达式
/// </summary>
/// <param name="nextNum"></param>
private void AddMinusMultiplyMix(int nextNum)
{
//System.Random ran = new System.Random();
//if (ran.Next(0, 3) == 0)
//{
// expression += "+";
//}
//else if (ran.Next(0, 3) == 1)
//{
// expression += "-";
//}
//else
//{
// nextNum = ran.Next(1, 3);//重新随机
// expression += "*";
//}
int random = UnityEngine.Random.Range(0, 3);
if (random.Equals(0))
{
expression += "+";
}
else if (random.Equals(1))
{
expression += "-";
}
else
{
nextNum = UnityEngine.Random.Range(1, 3);
expression += "*";
} expression += nextNum;
} /// <summary>
/// 四则运算混合表达式
/// </summary>
/// <param name="nextNum"></param>
private void FourArithmeticMix(int nextNum)
{
int random = UnityEngine.Random.Range(0, 4);
if (random.Equals(0))
{
expression += "+";
}
else if (random.Equals(1))
{
expression += "-";
}
else if (random.Equals(2))
{
nextNum = UnityEngine.Random.Range(1, 3);
expression += "*";
}
else if (random.Equals(3))
{
nextNum = UnityEngine.Random.Range(1, 10);
expression += "/";
}
expression += nextNum;
}
#endregion #region 计算表达式
private Dictionary<char, int> priorities = new Dictionary<char, int> { { '#', -1 }, { '+', 0 }, { '-', 0 }, { '*', 1 }, { '/', 1 } }; //优先级 // private Dictionary<char, int> priorities = null;
/// <summary>
/// 初始化运算符优先级
/// </summary>
public void InitPriorities() //添加了四种运算符以及四种运算符的优先级
{
//priorities = new Dictionary<char, int>();
//priorities.Add('#', -1);
//priorities.Add('+', 0);
//priorities.Add('-', 0);
//priorities.Add('*', 1);
//priorities.Add('/', 1);
} /// <summary>
/// 计算表达式
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public double Calcuate()
{
try
{
var rpn = QueueSort(expression); //rpn逆波兰表达式reverse polish notation
Stack<double> operandStack = new Stack<double>();
double left, right;
object cur;
while (rpn.Count > 0)
{
cur = rpn.Dequeue(); //出列 if (cur is char) //如果cur为字符的话
{
right = operandStack.Pop(); //右边的数字出栈
left = operandStack.Pop(); //左边的数字出栈
//Debug.Log("左:" + left + "右:" + right + "现在的字符:" + cur);
operandStack.Push(Compute(left, right, (char)cur)); //此时调用compute方法
}
else
{
operandStack.Push(double.Parse(cur.ToString())); //是数字就压栈
}
}
return operandStack.Pop();
}
catch
{
Debug.LogError("表达式格式不正确!");
throw new Exception("表达式格式不正确!");
}
} /// <summary>
/// 队列排序
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
private Queue<object> QueueSort(string expression) // 队列排序
{
Queue<object> result = new Queue<object>();
Stack<char> operatorStack = new Stack<char>(); //运算符栈
operatorStack.Push('#');
char top, cur, tempChar; //top栈顶,current最近的;
string tempNum;
for (int i = 0, j; i < expression.Length;) //取出表达式
{
cur = expression[i++]; //取出表达式的每个字符赋给cur
top = operatorStack.Peek(); //栈顶元素赋给top此时为"#" if (cur == '(') //将左括号压栈,此时栈顶元素为"("
{
operatorStack.Push(cur);
}
else
{
if (IsOperator(cur)) //如果是运算符的话
{
while (IsOperator(top) && ((IsAssoc(cur) && priorities[cur] <= priorities[top])) || (!IsAssoc(cur) && priorities[cur] < priorities[top]))
{
result.Enqueue(operatorStack.Pop()); //如果元素为运算符并且优先级小于栈顶元素优先级,出栈
top = operatorStack.Peek(); //继续把栈顶元素赋给top
}
operatorStack.Push(cur); //把数字压栈
}
else if (cur == ')') //将右括号添加到结尾
{
while (operatorStack.Count > 0 && (tempChar = operatorStack.Pop()) != '(')
{
result.Enqueue(tempChar);
}
}
else
{
tempNum = "" + cur;
j = i;
while (j < expression.Length && (expression[j] == '.' || (expression[j] >= '0' && expression[j] <= '9')))
{
tempNum += expression[j++];
}
i = j;
result.Enqueue(tempNum);
}
}
}
while (operatorStack.Count > 0)
{
cur = operatorStack.Pop();
if (cur == '#') continue;
if (operatorStack.Count > 0)
{
top = operatorStack.Peek();
} result.Enqueue(cur);
} return result;
} const string operators = "+-*/"; //运算符
/// <summary>
/// 计算左右两个数的方法
/// </summary>
/// <param name="leftNum"></param>
/// <param name="rightNum"></param>
/// <param name="op"></param>
/// <returns></returns>
private double Compute(double leftNum, double rightNum, char op) //这是一种方法,用来计算左右两个数的静态方法!
{
switch (op)
{
case '+': return leftNum + rightNum;
case '-': return leftNum - rightNum;
case '*': return leftNum * rightNum;
case '/': return leftNum / rightNum;
default: return 0;
}
} /// <summary>
/// 判断这个字符是否是运算符?
/// </summary>
/// <param name="op"></param>
/// <returns></returns>
private bool IsOperator(char op) //每次判断这个字符是否是运算符?
{
return operators.IndexOf(op) >= 0;
} /// <summary>
/// 返回一个关联符号
/// </summary>
/// <param name="op"></param>
/// <returns></returns>
private bool IsAssoc(char op) //返回一个关联符号
{
return op == '+' || op == '-' || op == '*' || op == '/';
}
#endregion
}
参考博客链接:https://www.cnblogs.com/thinking-star/p/4917349.html
随机生成四则运算表达式【Unity】的更多相关文章
- 结对作业——随机生成四则运算(Core 第7组)
结对作业 ——随机生成四则运算(core第7组) 吕佳玲 PB16060145 涂涵越 PB16060282 GITHUB地址 https://github.com/hytu99/homework_2 ...
- 基于c编写的关于随机生成四则运算的小程序
基于http://www.cnblogs.com/HAOZHE/p/5276763.html改编写的关于随机生成四则运算的小程序 github源码和工程文件地址:https://github.com/ ...
- 用Java随机生成四则运算
代码链接:https://github.com/devilwjy/Code.Demo 需求分析: 1.程序可接收一个输入参数n,然后随机产生n道加减乘除练习题,每个数字在 0 和 100 之间,运算符 ...
- (幼儿园毕业)Javascript小学级随机生成四则运算
软件工程第二次结对作业四则运算自动生成器网页版 一.题目要求 本次作业要求两个人合作完成,驾驶员和导航员角色自定,鼓励大家在工作期间角色随时互换,这里会布置两个题目,请各组成员根据自己的爱好任选一题. ...
- 随机生成四则运算式2-NEW+PSP项目计划(补充没有真分数的情况)
PS:这是昨天编写的随机生成四则运算式2的代码:http://www.cnblogs.com/wsqJohn/p/5264448.html 做了一些改进. 补:在上一次的运行中并没有加入真分数参与的运 ...
- 软件工程课堂作业(二)续——升级完整版随机产生四则运算题目(C++)
一.设计思想: 1.根据题目新设要求,我将它们分为两类:一类是用户输入数目,根据这个数目改变一系列后续问题:另一类是用户输入0或1,分情况解决问题. 2.针对这两类要求,具体设计思路已在上篇博文中写出 ...
- Android:随机生成算数四则运算简单demo(随机生成2~4组数字,进行加减乘除运算)
首先创建一个新的Android工程,下面是页面布局: Java代码: 我们先来分析一下如何完成的步骤: 1.首先,先完成生成随机数.(包括随机生成几组数字,范围为多少的数字,四则运算符号等): 2.要 ...
- 随机生成30道四则运算-NEW
补充:紧跟上一个随机生成30道四则运算的题目,做了一点补充,可以有真分数之间的运算,于是需要在原来的基础上做一些改进. 首先指出上一个程序中的几个不足:1.每次执行的结果都一样,所以不能每天给孩子出3 ...
- 随机生成30道四则运算题NEW
代码: #include <iostream> #include <time.h> using namespace std; void main() { srand((int) ...
- 用C++实现简单随机二元四则运算
让我们想看看二元四则运算都需要实现什么: (1) 定制题目数量 (2) 是否有乘除法 (3) 题目数值范围 (4) 加减有无负数 (5) 除法有无余数 (6) 是否支持分数(真分数.假分数…) (7) ...
随机推荐
- pie-engine-ai项目jenkins.yaml文件
apiVersion: apps/v1kind: Deploymentmetadata: name: jenkins namespace: pie-engine-ai labels: name: je ...
- 在platformio自动上传esp8266固件
不想每次上传固件的时候手工点按钮,修改这个文件:C:\Users\你的登录名.platformio\platforms\espressif8266\builder\main.py 在319行UPLOA ...
- jmeter--json格式的请求数据参数化以及断言
环境背景:登录接口测试 第一步:创建登录接口的http请求 第二步:添加配置原件--CSV Data Set Config(配置如图所示) 第三步:接口的请求下添加响应断言(如:用响应状态码作为检查点 ...
- MQTT 客户端出现连接订阅等问题时如何排查?
大家好,这是一期社区专题 FAQ.我们整理了近期社区中关注度较高的问题,在这里进行统一汇总解答. 今后本系列内容将不定期推送,敬请关注. 同时,如果大家在使用 EMQX 的过程中遇到问题,欢迎通过以下 ...
- vim多视窗操作
命令行模式下输入:sp 1.txt 打开新的水平分屏视窗来编辑1.txt 命令行模式下输入:vsp 2.txt 打开新的垂直分屏视窗来编辑2.txt 普通模式下Ctrl+w s 将当前窗口分割成两个水 ...
- Android Studio 修改jar包中的.class代码
修改a.jar中的b.class文件: 1.在Android Studio的项目中引入a.jar,sync,通过反编译找到并拷贝b.java的代码 2.使用压缩软件打开a.jar,并删掉需要修改的文件 ...
- 这些有用的CSS伪类通常被忽略
这些有用的CSS伪类通常被忽略 这篇文章在一定程度上鼓励你在构建UI时使用更简单的CSS和更少的JavaScript. ::first-line 选择文本的第一行 这个选择器用于选取指定选择器的首 ...
- 使用Kali破解无线密码
1.查看网卡信息,是否有wlanX网卡ifconfig 2.启动网卡监听模式 airmon-ng start wlan0 检查下是否处于监听模型:ifconfig查看一下,如果网卡名加上了mon后则成 ...
- 面试之AQS
https://blog.csdn.net/wwwzhouzy/article/details/119702170 https://copyfuture.com/blogs-details/20200 ...
- 【Windows】Windows11 安卓子系统安装方法与使用技巧
安卓子系统 (Windows Subsystem For Android, WSA) 可以说是 Windows11 的最强功能,能在 Windows 系统中体验各种安卓应用.但是有些电脑可能不符合硬件 ...