``````
unit U_X9321;
{Copyright 2001, Gary Darby, Intellitech Systems Inc., www.DelphiForFun.org
This program may be used or modified for any non-commercial purpose
so long as this original notice remains in place.
All other rights are reserved
}

{
Consider the following equation where "op" represents one of the four basic
operators + (addition), - (subtraction), * (multiplication) or / (division).

X = 9 op 3 op 2  op 1

Complete the equation by filling in the  "op" operators to produce integer X
values 0 through 9 in as many ways as possible.
}

....``````
``{Generated code snipped}``
``````....

var
{character representation of operators - used to display results}
opstr:array [1..4] of char=('+','-','*','/');

function eval(i,j,k:integer):integer;
{given 3 operators, (i,j,k), evaluate 9 i 3 j 2 k 1}
{i,j,k values: 1 ==> '+', 2 ==> '-', 3 ==> '*', 4 ==> '/'}
var
x,x2:extended;
n:integer;
begin
{make a number from 0 to 7 representing the 8 possible
sequences of operations}
{n=  (0 or 4)      +  (0 or 2)        + (0 or 1)  }
n:=((i-1) div 2)*4 + ((j-1) div 2)*2 + (k-1) div 2;
case n of
0:  {+-, +-, +-}
begin
if i=1 then x:=9+3  else x:=9-3;
if j=1 then x:=x+2  else x:=x-2;
if k=1 then x:=x+1 else x:=x-1;
end;
1: begin  {+-, +-, */}
if k=3 then x2:= 2*1 else x2:=2;
if i=1 then x:=9+3 else x:=9-3;
if j=1 then x:=x+x2 else x:=x-x2;
end;
2: begin  {+-, */, +-}
if j=3 then x:= 3*2 else x:=3 / 2;
if i=1 then x:=9+x else x:=9-x;
if k=1 then x:=x+1 else x:=x-1;
end;
3: begin  {+-, */, */}
if j=3 then x:= 3*2 else x:=3 / 2;
if k=3 then x:=x*1 else x:=x / 1;
if i=1 then x:=9+x else x:=9-x;
end;
4: begin  {*/, +-, +-}
if i=3 then x:=9*3  else x:=9 / 3;
if j=1 then x:=x+2  else x:=x-2;
if k=1 then x:=x+1 else x:=x-1;
end;
5: begin  {*/, +-, */}
if i=3 then x:=9*3  else x:=9 / 3;
if k=3 then x2:= 2*1 else x2:=2 / 1;
if j=1 then x:=x+x2 else x:=x-x2;
end;
6: begin  {*/, */, +-}
if i=3 then x:=9*3  else x:=9 / 3;
if j=3 then x:= x*2 else x:=x / 2;
if k=1 then x:=x+1 else x:=x-1;
end;
7: begin  {*/, */, */}
if i=3 then x:=9*3  else x:=9 / 3;
if j=3 then x:= x*2 else x:=x / 2;
if k=3 then x:=x*1 else x:=x / 1;
end;
end; {case}
if x =int(x) then result:=trunc(x) {if x is an integer, return it}
else result:=-9999; {if not an integer, return -9999 as an error flag}
end;

procedure Tform1.Showvalues(from,through:integer);
{generate all permutations of operators and evaluate each}
var
list:Tstringlist;
begin
list:=Tstringlist.create; {make a stringlist so we can sort it}
for i:=1 to 4 do {1st operator}
for j:=1 to 4 do {2nd operator}
for k:=1 to 4 do {3rd operator}
begin
then list.add(format('%4d = 9 %s 3 %s 2 %s 1 ',
end;
listbox1.Items.Assign(list); {move sorted list to display area}
list.free;
end;

procedure TForm1.AllBtnClick(Sender: TObject);
begin   showvalues(-1000000,100000);  end;

procedure TForm1.OneNineBtnClick(Sender: TObject);
begin  showvalues(0,9); end;