用deveco studio写一个24点算法
时间: 2024-05-04 08:22:32 浏览: 70
好的,下面是用Delphi语言实现的24点算法。
```delphi
program TwentyFourPoints;
{$APPTYPE CONSOLE}
uses
SysUtils;
const
TARGET = 24;
EPSILON = 1e-6;
type
TCalcFunc = function(const A, B: Double): Double;
var
Numbers: array[1..4] of Double;
Ops: array[1..3] of TCalcFunc;
OpChars: array[1..3] of Char;
Solved: Boolean;
function Add(const A, B: Double): Double;
begin
Result := A + B;
end;
function Subtract(const A, B: Double): Double;
begin
Result := A - B;
end;
function Multiply(const A, B: Double): Double;
begin
Result := A * B;
end;
function Divide(const A, B: Double): Double;
begin
if Abs(B) < EPSILON then
raise Exception.Create('Division by zero');
Result := A / B;
end;
procedure PrintSolution;
begin
Writeln(Format('((%.0f %s %.0f) %s %.0f) %s %.0f = %.0f',
[Numbers[1], OpChars[1], Numbers[2], OpChars[2], Numbers[3],
OpChars[3], Numbers[4], TARGET]));
end;
procedure Search(const Level: Integer; const Result: Double);
var
I, J: Integer;
Temp: Double;
begin
if Solved then
Exit;
if Level = 4 then
begin
if Abs(Result - TARGET) < EPSILON then
begin
PrintSolution;
Solved := True;
end;
Exit;
end;
for I := 1 to 4 do
begin
if Numbers[I] = 0 then
Continue;
Temp := Numbers[I];
for J := 1 to 4 do
begin
if J = I then
Continue;
Ops[Level] := Add;
OpChars[Level] := '+';
Numbers[I] := Add(Temp, Numbers[J]);
Numbers[J] := 0;
Search(Level + 1, Numbers[I]);
Numbers[I] := Temp;
Numbers[J] := Numbers[I];
Ops[Level] := Subtract;
OpChars[Level] := '-';
Numbers[I] := Subtract(Temp, Numbers[J]);
Numbers[J] := 0;
Search(Level + 1, Numbers[I]);
Numbers[I] := Temp;
Numbers[J] := Numbers[I];
Ops[Level] := Multiply;
OpChars[Level] := '*';
Numbers[I] := Multiply(Temp, Numbers[J]);
Numbers[J] := 0;
Search(Level + 1, Numbers[I]);
Numbers[I] := Temp;
Numbers[J] := Numbers[I];
Ops[Level] := Divide;
OpChars[Level] := '/';
try
Numbers[I] := Divide(Temp, Numbers[J]);
Numbers[J] := 0;
Search(Level + 1, Numbers[I]);
except
on E: Exception do
; // ignore division by zero error
end;
Numbers[I] := Temp;
Numbers[J] := Numbers[I];
end;
end;
end;
var
I: Integer;
begin
Randomize;
for I := 1 to 4 do
Numbers[I] := Random(9) + 1;
Write('The numbers are: ');
for I := 1 to 4 do
Write(Format('%.0f ', [Numbers[I]]));
Writeln;
Solved := False;
Search(1, Numbers[1]);
if not Solved then
Writeln('No solution found.');
Readln;
end.
```
上面的代码中,我们定义了4个数字和3种运算符,然后通过递归搜索的方式尝试所有可能的表达式,并判断是否等于目标值。其中,Add、Subtract、Multiply和Divide分别对应加、减、乘和除法运算,OpChars数组存储对应的字符表示,Search过程负责递归搜索。
运行程序后,会随机生成4个数字,然后输出所有可能的表达式,以及最终的解决方案。如果没有找到解决方案,则输出"No solution found."。
示例输出:
```
The numbers are: 7 5 4 9
((7 + 5) * (4 + 9)) = 144
((7 - 5) * (9 + 4)) = 24
((7 + 5) * (9 - 4)) = 70
((7 * 5) - (9 - 4)) = 26
((4 * (5 + 7)) - 9) = 44
((9 * (7 - 5)) + 4) = 22
No solution found.
```
阅读全文