C# 版本的24点实现
C# 版本的24点实现。
已经实现基本功能,可以正确的算 3, 3, 8, 8 这类组合。
稍加修改就可以支持任意数目的操作数和操作符组合形成的四则运算表达式,不限于24点。
代码还比较简单粗糙,晚一点优化了再更新此贴。
关于二叉树拓扑结构的遍历,参考了:
http://blogs.msdn.com/b/ericlippert/archive/2010/04/19/every-binary-tree-there-is.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace calc24
{
class MainClass
{
public static void Main (string[] args)
{
var permuteOfNums = Permute (new List<int> { 4, 5, 6, 7 });
foreach (var op1 in new List<string>{"+","-","*","/"}) {
foreach (var op2 in new List<string>{"+","-","*","/"}) {
foreach (var op3 in new List<string>{"+","-","*","/"}) {
var ops = new List<string>{ op1, op2, op3 };
foreach (var node in AllCompleteBinaryTreesOf7Nodes()) {
foreach (var nums in permuteOfNums) {
var tree = CreateOne24CalculationFormula (node, nums, ops);
try {
var result = Evaluate (tree);
if (Math.Abs (result - 24) < 0.0001) {
Console.WriteLine (BinaryTreeString (tree));
}
} catch (DivideByZeroException) {
}
}
}
}
}
}
}
static float Evaluate (Node node)
{
switch (node.Data) {
case "+":
return Evaluate (node.Left) + Evaluate (node.Right);
case "-":
return Evaluate (node.Left) - Evaluate (node.Right);
case "*":
return Evaluate (node.Left) * Evaluate (node.Right);
case "/":
return Evaluate (node.Left) / Evaluate (node.Right);
default:
return float.Parse (node.Data);
}
}
static Node CreateOne24CalculationFormula (Node node, List<int> nums, List<string> operators)
{
Node result = null;
var iNums = 0;
var iOps = 0;
Func<Node, Node> copy = null;
copy = (src) => {
Node dest;
if (src.Left == null && src.Right == null) {
dest = new Node (null, null, nums [iNums++].ToString ());
} else {
var left = copy (src.Left);
var right = copy (src.Right);
dest = new Node (left, right, operators [iOps++]);
}
return dest;
};
result = copy (node);
return result;
}
static IEnumerable<List<T>> Permute<T> (List<T> elements)
{
if (elements.Count == 1)
return EnumerableOfOneElement (elements);
IEnumerable<List<T>> result = null;
foreach (var first in elements) {
var remaining = elements.ToArray ().ToList ();
remaining.Remove (first);
var permutesOfRemaining = Permute (remaining);
foreach (var p in permutesOfRemaining) {
var arr = new List<T> { first };
arr.AddRange (p);
var seq = EnumerableOfOneElement (arr);
if (result == null) {
result = seq;
} else {
result = Enumerable.Union (result, seq);
}
}
}
return result;
}
static IEnumerable<T> EnumerableOfOneElement<T> (T element)
{
yield return element;
}
static IEnumerable<Node> AllCompleteBinaryTreesOf7Nodes ()
{
var trees = AllBinaryTrees (7);
return (from t in trees
where IsCompleteBinaryTree (t)
select t);
}
static bool IsCompleteBinaryTree (Node node)
{
if (node == null)
return true;
if (node.Left == null && node.Right != null ||
node.Left != null && node.Right == null)
return false;
return IsCompleteBinaryTree (node.Left) && IsCompleteBinaryTree (node.Right);
}
static IEnumerable<Node> AllBinaryTrees (int size)
{
if (size == 0)
return new Node[] { null };
return from i in Enumerable.Range (0, size)
from left in AllBinaryTrees (i)
from right in AllBinaryTrees (size - 1 - i)
select new Node (left, right, "");
}
public static string BinaryTreeString (Node node)
{
var sb = new StringBuilder ();
Action<Node> f = null;
f = n => {
if (n == null) {
//sb.Append ("x");
} else if (new []{ "+", "-", "*", "/" }.Contains (n.Data)) {
sb.Append ("(");
f (n.Left);
sb.Append (" " + n.Data + " ");
f (n.Right);
sb.Append (")");
} else {
sb.Append (n.Data);
}
};
f (node);
return sb.ToString ();
}
}
class Node
{
public Node Left { get; set; }
public Node Right { get; set; }
public string Data { get; set; }
public Node ()
{
}
public Node (Node left, Node right, string data)
{
this.Left = left;
this.Right = right;
this.Data = data;
}
}
}
测试:
(4 * ((5 + 7) - 6))
(4 * ((7 + 5) - 6))
((5 + 7) * (6 - 4))
((7 + 5) * (6 - 4))
(((5 + 7) - 6) * 4)
(((7 + 5) - 6) * 4)
(4 * (5 + (7 - 6)))
(4 * (7 + (5 - 6)))
(4 * ((5 - 6) + 7))
(4 * ((7 - 6) + 5))
((6 - 4) * (5 + 7))
((6 - 4) * (7 + 5))
((5 + (7 - 6)) * 4)
((7 + (5 - 6)) * 4)
(((5 - 6) + 7) * 4)
(((7 - 6) + 5) * 4)
(4 * (5 - (6 - 7)))
(4 * (7 - (6 - 5)))
((5 - (6 - 7)) * 4)
((7 - (6 - 5)) * 4)
Press any key to continue...
C# 版本的24点实现的更多相关文章
- Racket 版本的 24 点实现
Racket 版本的 24 点实现 #lang racket ; Author: woodfox ; Date: Oct 11, 2014 ; ==================== 1. Non- ...
- 团队作业4--第一次项目冲刺(Alpha版本)预备工作
小组说明 我们组是从周一开始对项目进行研究讨论并编程的,因为我们看截止日期是周日,就从周一才开始,起步晚了,是我们认识上的失误,导致我们周一周二的步伐没有协调好,项目进展的不稳定,但是我们在上周末并不 ...
- ESP-IDF版本2.1.1
版本2.1.1是一个错误修复版本.它包括对KRACK和BlueBorne漏洞的修复. 版本2.1.1的文档可在http://esp-idf.readthedocs.io/en/v2.1.1/上找到. ...
- Android 7.0以上版本 系统解决拍照的问题 exposed beyond app through ClipData.Item.getUri()
解决方案1: android.os.FileUriExposedException: file:///storage/emulated/0/ilive/images/photophoto.jpeg e ...
- 交叉编译OpenCV的Android版本
交叉编译OpenCV的Android版本 OpenCV作为一个强大的图像处理库,在Android上也有强大的应用. OpenCV官网提供了SDK的下载,可以直接下载使用 OpenCV官网地址:http ...
- selenium:chromedriver与chrome版本的对应关系
转自:http://blog.csdn.NET/huilan_same/article/details/51896672 再使用selenium打开chrome浏览器的时候,需要用chromedriv ...
- 四、10分钟ToPandas_0.24.2
# Author:Zhang Yuan整理,版本Pandas0.24.2 # 0. 习惯上,我们会按下面格式引入所需要的包: import pandas as pd import numpy as n ...
- OpenCV.3.4.6_VS2015&cmake编译x86版本的bin&lib
ZC:<<OpenCV3编程入门>> 的 2.2.2 中也有该内容的讲解 1.参考网址:opencv3.3.0+vs2015+cmake编译opencv x86 - wowo的 ...
- PDF 文件编写器 C# 类库(版本 1.28.0)使用详解
PDF File Writer 是一个 C# .NET 类库,允许应用程序创建 PDF 文件. PDF File Writer C# 类库使 .NET 应用程序能够生成 PDF 文档.该库使应用程序免 ...
随机推荐
- Codeforces 535D - Tavas and Malekas
535D - Tavas and Malekas 题目大意:给你一个模板串,给你一个 s 串的长度,告诉你 s 串中有 m 个模板串并告诉你,他们的其实位置, 问你这样的 s 串总数的多少,答案对1e ...
- c# 服务安装后自动启动
switch (rs) { case 1: var path = @&q ...
- HDU4857 逃生 拓扑排序
Problem Description糟糕的事情发生啦,现在大家都忙着逃命.但是逃命的通道很窄,大家只能排成一行. 现在有n个人,从1标号到n.同时有一些奇怪的约束条件,每个都形如:a必须在b之前.同 ...
- 【Ray Tracing The Next Week 超详解】 光线追踪2-9
我们来整理一下项目的代码 目录 ----include --hit --texture --material ----RTdef.hpp ----ray.hpp ----camera.hpp ---- ...
- PHP中的字符串 — 表示方法
Strings 的字符集,因此本质上不支持Unicode编码,关于Unicode阅读 utf8_encode() 和 utf8_decode() . 注意: 一个字符串的大小决定与计算机内存的大小,理 ...
- js常用事件
为了便于使读者更好地运用js事件,就把常用事件大致分为以下几种: a. 表单元素事件,在表单元素中生效 onfocus ------获取焦点 onblur -------失去焦点 onsubmit ...
- JDBC(7)—DAO
介绍: DAO(Data Access Object):数据访问对象 1.what:访问数据信息的类,包含了对数据的CRUD(create read.update.delete),而不包含业务相关的信 ...
- CentOS 7安装Ansible
在CentOS下安装Ansible非常的简单,但需要注意一下几点: 1.为了简单建议使用yum的epel源安装,毕竟没什么模块需要自己定制的,如果非要指定版本,可以指定不同的版本,下面会讲. 2.母机 ...
- API判断本机安装的Revit版本信息
start [Transaction(TransactionMode.Manual)] [Regeneration(RegenerationOption.Manual)] public class c ...
- shell中空格的使用;空格替换;通配符
测试: test $? -eq && echo "yes" || echo "no" 通配符: 通配符 ()*:0个或多个连续的字符 ()?:任 ...