Home Backend Development C#.Net Tutorial Algorithm for calculating 24-point game implemented in C#

Algorithm for calculating 24-point game implemented in C#

Nov 10, 2016 pm 04:21 PM

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

   

namespace Calc24Points

{

    public class Cell

    {

        public enum Type

        {

            Number,

            Signal

        }

        public int Number;

        public char Signal;

        public Type Typ;

        public Cell Right;

        public Cell Left;

   

        /// <summary>

        /// 符号优先级

        /// </summary>

        public int Priority

        {

            get

            {

                if (Typ == Type.Signal)

                {

                    switch (Signal)

                    {

                        case &#39;+&#39;: return 0;

                        case &#39;-&#39;: return 0;

                        case &#39;*&#39;: return 1;

                        case &#39;/&#39;: return 1;

                        default: return -1;

                    }

                }

                return -1;

            }

        }

   

        /// <summary>

        /// 基本单元构造函数

        /// </summary>

        /// <param name="t">单元类型,数值或符号</param>

        /// <param name="num">数值</param>

        /// <param name="sig">符号</param>

        public Cell(Type t, int num, char sig)

        {

            Right = null;

            Left = null;

            Typ = t;

            Number = num;

            Signal = sig;

        }

        public Cell()

        {

            Right = null;

            Left = null;

            Number = 0;

            Typ = Type.Number;

        }

        public Cell(Cell c)

        {

            Right = null;

            Left = null;

            Number = c.Number;

            Signal = c.Signal;

            Typ = c.Typ;

        }

    }

    public class Calc24Points

    {

   

        string m_exp;

        bool m_stop;

        Cell[] m_cell;

        int[] m_express;

        StringWriter m_string;

        public Calc24Points(int n1, int n2, int n3, int n4)

        {

            m_cell = new Cell[8];

            m_cell[0] = new Cell(Cell.Type.Number, n1, &#39;?&#39;);

            m_cell[1] = new Cell(Cell.Type.Number, n2, &#39;?&#39;);

            m_cell[2] = new Cell(Cell.Type.Number, n3, &#39;?&#39;);

            m_cell[3] = new Cell(Cell.Type.Number, n4, &#39;?&#39;);

            m_cell[4] = new Cell(Cell.Type.Signal, 0, &#39;+&#39;);

            m_cell[5] = new Cell(Cell.Type.Signal, 0, &#39;-&#39;);

            m_cell[6] = new Cell(Cell.Type.Signal, 0, &#39;*&#39;);

            m_cell[7] = new Cell(Cell.Type.Signal, 0, &#39;/&#39;);

            m_stop = false;

            m_express = new int[7];

            m_string = new StringWriter();

            m_exp = null;

        }

   

        public override string ToString()

        {

            if (m_exp == null)

            {

                PutCell(0);

                m_exp = m_string.ToString();

            }

            if (m_exp != "") return m_exp;

            return null;

        }

   

        /// <summary>

        /// 在第n位置放置一个单元

        /// </summary>

        /// <param name="n"></param>

        void PutCell(int n)

        {

            if (n >= 7)

            {

                if (Calculate())

                {

                    m_stop = true;

                    Formate();

                }

                return;

            }

            int end = 8;

            if (n < 2) end = 4;

            for (int i = 0; i < end; ++i)

            {

                m_express[n] = i;

                if (CheckCell(n)) PutCell(n + 1);

                if (m_stop) break;

            }

        }

   

        /// <summary>

        /// 检查当前放置是否合理

        /// </summary>

        /// <param name="n"></param>

        /// <returns></returns>

        bool CheckCell(int n)

        {

            int nums = 0, sigs = 0;

            for (int i = 0; i <= n; ++i)

            {

                if (m_cell[m_express[i]].Typ == Cell.Type.Number) ++nums;

                else ++sigs;

            }

            if (nums - sigs < 1) return false;

            if (m_cell[m_express[n]].Typ == Cell.Type.Number) //数值不能重复,但是符号可以重复

            {

                for (int i = 0; i < n; ++i) if (m_express[i] == m_express[n]) return false;         

            }

            if (n == 6)

            {

                if (nums != 4 || sigs != 3) return false;

                if (m_cell[m_express[6]].Typ != Cell.Type.Signal) return false;

                return true;

            }

            return true;

        }

   

        /// <summary>

        /// 计算表达式是否为24

        /// </summary>

        /// <returns>返回值true为24,否则不为24</returns>

        bool Calculate()

        {

            double[] dblStack = new double[4];

            int indexStack = -1;

            for (int i = 0; i < 7; ++i)

            {

                if (m_cell[m_express[i]].Typ == Cell.Type.Number)

                {

                    ++indexStack;

                    dblStack[indexStack] = m_cell[m_express[i]].Number;

                }

                else

                {

                    switch (m_cell[m_express[i]].Signal)

                    {

                        case &#39;+&#39;:

                            dblStack[indexStack - 1] = dblStack[indexStack - 1] + dblStack[indexStack];

                            break;

                        case &#39;-&#39;:

                            dblStack[indexStack - 1] = dblStack[indexStack - 1]-+ dblStack[indexStack];

                            break;

                        case &#39;*&#39;:

                            dblStack[indexStack - 1] = dblStack[indexStack - 1] * dblStack[indexStack];

                            break;

                        case &#39;/&#39;:

                            dblStack[indexStack - 1] = dblStack[indexStack - 1] / dblStack[indexStack];

                            break;

                    }

                    --indexStack;

                }

            }

            if (Math.Abs(dblStack[indexStack] - 24) < 0.1) return true;

            return false;

        }

   

        /// <summary>

        /// 后缀表达式到中缀表达式

        /// </summary>

        void Formate()

        {

            Cell[] c = new Cell[7];

            for (int i = 0; i < 7; ++i) c[i] = new Cell(m_cell[m_express[i]]);

            int[] cStack = new int[4];

            int indexStack = -1;

            for (int i = 0; i < 7; ++i)

            {

                if (c[i].Typ == Cell.Type.Number)

                {

                    ++indexStack;

                    cStack[indexStack] = i;

                }

                else

                {

                    c[i].Right = c[cStack[indexStack]];

                    --indexStack;

                    c[i].Left = c[cStack[indexStack]];

                    cStack[indexStack] = i;

                }

            }

            ToStringFormate(c[cStack[indexStack]]);

        }

   

        void ToStringFormate(Cell root)

        {

            if (root.Left.Typ == Cell.Type.Number)

            {

                m_string.Write(root.Left.Number);

                m_string.Write(root.Signal);

            }

            else

            {

                if (root.Priority > root.Left.Priority)

                {

                    m_string.Write("(");

                    ToStringFormate(root.Left);

                    m_string.Write(")");

                }

                else ToStringFormate(root.Left);

                m_string.Write(root.Signal);

            }

            if (root.Right.Typ == Cell.Type.Number) m_string.Write(root.Right.Number);

            else

            {

                if (root.Priority >= root.Right.Priority)

                {

                    m_string.Write("(");

                    ToStringFormate(root.Right);

                    m_string.Write(")");

                }

                else ToStringFormate(root.Right);

            }

        }

    }

}

Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use various symbols in C language How to use various symbols in C language Apr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

What is the role of char in C strings What is the role of char in C strings Apr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

How to handle special characters in C language How to handle special characters in C language Apr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

The difference between char and wchar_t in C language The difference between char and wchar_t in C language Apr 03, 2025 pm 03:09 PM

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

How to convert char in C language How to convert char in C language Apr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

How to use char array in C language How to use char array in C language Apr 03, 2025 pm 03:24 PM

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

See all articles