langs a-z
This commit is contained in:
parent
db842d013d
commit
d066446780
11389 changed files with 98361 additions and 1020 deletions
90
Task/24-game/OCaml/24-game.ocaml
Normal file
90
Task/24-game/OCaml/24-game.ocaml
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
type expression =
|
||||
| Const of float
|
||||
| Sum of expression * expression (* e1 + e2 *)
|
||||
| Diff of expression * expression (* e1 - e2 *)
|
||||
| Prod of expression * expression (* e1 * e2 *)
|
||||
| Quot of expression * expression (* e1 / e2 *)
|
||||
|
||||
let rec eval = function
|
||||
| Const c -> c
|
||||
| Sum (f, g) -> eval f +. eval g
|
||||
| Diff(f, g) -> eval f -. eval g
|
||||
| Prod(f, g) -> eval f *. eval g
|
||||
| Quot(f, g) -> eval f /. eval g
|
||||
|
||||
let rec extract acc = function
|
||||
| Const c -> (c::acc)
|
||||
| Sum (f, g) -> (extract acc f) @ (extract [] g)
|
||||
| Diff(f, g) -> (extract acc f) @ (extract [] g)
|
||||
| Prod(f, g) -> (extract acc f) @ (extract [] g)
|
||||
| Quot(f, g) -> (extract acc f) @ (extract [] g)
|
||||
|
||||
open Genlex
|
||||
|
||||
let lexer = make_lexer ["("; ")"; "+"; "-"; "*"; "/"]
|
||||
|
||||
let rec parse_expr = parser
|
||||
[< e1 = parse_mult; e = parse_more_adds e1 >] -> e
|
||||
and parse_more_adds e1 = parser
|
||||
[< 'Kwd "+"; e2 = parse_mult; e = parse_more_adds (Sum(e1, e2)) >] -> e
|
||||
| [< 'Kwd "-"; e2 = parse_mult; e = parse_more_adds (Diff(e1, e2)) >] -> e
|
||||
| [< >] -> e1
|
||||
and parse_mult = parser
|
||||
[< e1 = parse_simple; e = parse_more_mults e1 >] -> e
|
||||
and parse_more_mults e1 = parser
|
||||
[< 'Kwd "*"; e2 = parse_simple; e = parse_more_mults (Prod(e1, e2)) >] -> e
|
||||
| [< 'Kwd "/"; e2 = parse_simple; e = parse_more_mults (Quot(e1, e2)) >] -> e
|
||||
| [< >] -> e1
|
||||
and parse_simple = parser
|
||||
| [< 'Int i >] -> Const(float i)
|
||||
| [< 'Float f >] -> Const f
|
||||
| [< 'Kwd "("; e = parse_expr; 'Kwd ")" >] -> e
|
||||
|
||||
|
||||
let parse_expression = parser [< e = parse_expr; _ = Stream.empty >] -> e
|
||||
|
||||
let read_expression s = parse_expression(lexer(Stream.of_string s))
|
||||
|
||||
|
||||
let () =
|
||||
Random.self_init();
|
||||
print_endline "
|
||||
The 24 Game
|
||||
|
||||
Given any four digits in the range 1 to 9, which may have repetitions,
|
||||
Using just the +, -, *, and / operators; and the possible use of
|
||||
brackets, (), show how to make an answer of 24.
|
||||
|
||||
An answer of 'q' will quit the game.
|
||||
An answer of '!' will generate a new set of four digits.
|
||||
Otherwise you are repeatedly asked for an expression until it evaluates to 24
|
||||
|
||||
Note: you cannot form multiple digit numbers from the supplied digits,
|
||||
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n";
|
||||
|
||||
let sort = List.sort compare in
|
||||
let digits = ref [] in
|
||||
let digit_set () =
|
||||
let ar = Array.init 4 (fun _ -> 1 + Random.int 9) in
|
||||
digits := Array.to_list(Array.map float_of_int ar);
|
||||
print_string "The four digits: ";
|
||||
List.iter (Printf.printf " %g") !digits;
|
||||
print_newline();
|
||||
in
|
||||
|
||||
digit_set();
|
||||
while true do
|
||||
print_string "Expression: ";
|
||||
let str = read_line() in
|
||||
if str = "q" then exit 0;
|
||||
if str = "!" then digit_set()
|
||||
else begin
|
||||
let expr = read_expression str in
|
||||
let res = eval expr in
|
||||
Printf.printf " = %g\n%!" res;
|
||||
if res = 24.
|
||||
&& (sort !digits) = (sort (extract [] expr))
|
||||
then (print_endline "Congratulations!"; digit_set())
|
||||
else print_endline "Try again"
|
||||
end
|
||||
done
|
||||
67
Task/24-game/OpenEdge-Progress/24-game.openedge
Normal file
67
Task/24-game/OpenEdge-Progress/24-game.openedge
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
DEFINE TEMP-TABLE tt NO-UNDO FIELD ii AS INTEGER.
|
||||
|
||||
DEFINE VARIABLE p_deanswer AS DECIMAL NO-UNDO.
|
||||
DEFINE VARIABLE idigits AS INTEGER NO-UNDO EXTENT 4.
|
||||
DEFINE VARIABLE ii AS INTEGER NO-UNDO.
|
||||
DEFINE VARIABLE Digits AS CHARACTER NO-UNDO FORMAT "x(7)".
|
||||
DEFINE VARIABLE Answer AS CHARACTER NO-UNDO FORMAT "x(7)".
|
||||
DEFINE VARIABLE cexpression AS CHARACTER NO-UNDO.
|
||||
DEFINE VARIABLE cmessage AS CHARACTER NO-UNDO.
|
||||
DEFINE VARIABLE cchar AS CHARACTER NO-UNDO.
|
||||
|
||||
FUNCTION calculate RETURNS LOGICAL (
|
||||
i_de AS DECIMAL
|
||||
):
|
||||
p_deanswer = i_de.
|
||||
END FUNCTION.
|
||||
|
||||
/* generate problem */
|
||||
DO ii = 1 TO 4:
|
||||
ASSIGN
|
||||
idigits [ii] = RANDOM( 1, 9 ).
|
||||
Digits = Digits + STRING( idigits [ii] ) + " "
|
||||
.
|
||||
END.
|
||||
|
||||
/* ui */
|
||||
DISPLAY Digits.
|
||||
UPDATE Answer.
|
||||
|
||||
/* check valid input */
|
||||
DO ii = 1 TO 7:
|
||||
cchar = SUBSTRING( Answer, ii, 1 ).
|
||||
IF cchar > "" THEN DO:
|
||||
IF ii MODULO 2 = 1 THEN DO:
|
||||
IF LOOKUP( cchar, Digits, " " ) = 0 THEN
|
||||
cmessage = cmessage + SUBSTITUTE( "Invalid digit: &1.~r", cchar ).
|
||||
ELSE
|
||||
ENTRY( LOOKUP( cchar, Digits, " " ), Digits, " " ) = "".
|
||||
END.
|
||||
ELSE DO:
|
||||
IF LOOKUP( cchar, "+,-,/,*" ) = 0 THEN
|
||||
cmessage = cmessage + SUBSTITUTE( "&1 is not a valid operator.~r", cchar ).
|
||||
END.
|
||||
END.
|
||||
END.
|
||||
IF TRIM( Digits ) > "" THEN
|
||||
cmessage = cmessage + SUBSTITUTE( "You did not use digits: &1":U, TRIM( Digits ) ).
|
||||
|
||||
IF cmessage = "" THEN DO:
|
||||
/* expressions need spacing */
|
||||
DO ii = 1 TO 7:
|
||||
cexpression = cexpression + SUBSTRING( Answer, ii, 1 ) + " ".
|
||||
END.
|
||||
/* use dynamic query to parse expression */
|
||||
TEMP-TABLE tt:DEFAULT-BUFFER-HANDLE:FIND-FIRST(
|
||||
SUBSTITUTE(
|
||||
"WHERE NOT DYNAMIC-FUNCTION( 'calculate', DECIMAL( &1 ) )",
|
||||
cexpression
|
||||
)
|
||||
) NO-ERROR.
|
||||
IF p_deanswer <> 24 THEN
|
||||
cmessage = cmessage + SUBSTITUTE( "The expression evaluates to &1.", p_deanswer ).
|
||||
ELSE
|
||||
cmessage = "Solved!".
|
||||
END.
|
||||
|
||||
MESSAGE cmessage VIEW-AS ALERT-BOX.
|
||||
45
Task/24-game/PARI-GP/24-game.pari
Normal file
45
Task/24-game/PARI-GP/24-game.pari
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
game()={
|
||||
my(v=vecsort(vector(4,i,random(8)+1)));
|
||||
print("Form 24 using */+-() and: "v);
|
||||
while(1,
|
||||
my(ans=input);
|
||||
if (!valid(s,v), next);
|
||||
trap(,
|
||||
print("Arithmetic error");
|
||||
next
|
||||
,
|
||||
if(eval(s)==24, break, print("Bad sum"))
|
||||
)
|
||||
);
|
||||
print("You win!")
|
||||
};
|
||||
valid(s,v)={
|
||||
my(op=vecsort(Vec("+-*/()")),u=[]);
|
||||
s=Vec(s);
|
||||
for(i=1,#s,
|
||||
if(setsearch(op,s[i]),next);
|
||||
trap(,
|
||||
print("Invalid character "s[i]);
|
||||
return(0)
|
||||
,
|
||||
if(setsearch(v,eval(s[i])),
|
||||
u=concat(u,eval(s[i]))
|
||||
,
|
||||
print(s[i]" not allowed");
|
||||
return(0)
|
||||
)
|
||||
)
|
||||
);
|
||||
for(i=2,#s,
|
||||
if(!setsearch(op,s[i])&!setsearch(op,s[i-1]),
|
||||
print("Concatenating digits is not allowed!");
|
||||
return(0)
|
||||
)
|
||||
);
|
||||
if(vecsort(u)!=v,
|
||||
print("Invalid digits");
|
||||
0
|
||||
,
|
||||
1
|
||||
)
|
||||
};
|
||||
136
Task/24-game/PL-I/24-game.pli
Normal file
136
Task/24-game/PL-I/24-game.pli
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
/* Plays the game of 24. */
|
||||
|
||||
TWENTYFOUR: procedure options (main); /* 14 August 2010 */
|
||||
|
||||
CTP: procedure (E) returns (character(50) varying);
|
||||
declare E character (*) varying;
|
||||
declare OUT character (length(E)) varying;
|
||||
declare S character (length(E)) varying controlled;
|
||||
declare c character (1);
|
||||
declare i fixed binary;
|
||||
|
||||
/* This procedure converts an arithmetic expression to Reverse Polish Form. */
|
||||
/* A push-down pop-up stack is used for operators. */
|
||||
priority: procedure (a) returns (fixed decimal (1));
|
||||
declare a character (1);
|
||||
declare ops character (10) initial ('#+-*/') varying static;
|
||||
declare pri(6) fixed decimal (1) initial (1,2,2,3,3,4) static;
|
||||
declare i fixed binary;
|
||||
|
||||
i = index(ops,a);
|
||||
return (pri(i));
|
||||
end priority;
|
||||
|
||||
allocate S; S = '#'; out = '';
|
||||
do i = 1 to length(E);
|
||||
c = substr(E, i, 1);
|
||||
if index('+-*/', c) > 0 then
|
||||
do;
|
||||
/* Copy any higher priority operators on the stack to the output. */
|
||||
do while ( priority(c) <= priority((S)) );
|
||||
out = out || S;
|
||||
free S;
|
||||
end;
|
||||
/* Copy the input character to the stack. */
|
||||
allocate S; S = c;
|
||||
end;
|
||||
|
||||
if index('123456789', c) > 0 then
|
||||
out = out || c;
|
||||
end;
|
||||
do while (allocation(S) > 1);
|
||||
out = out || s;
|
||||
free S;
|
||||
end;
|
||||
return (out);
|
||||
end CTP;
|
||||
|
||||
/* Given a push-down pop-up stack, and an expresion in */
|
||||
/* Reverse Polish notation, evaluate the expression. */
|
||||
EVAL: procedure (E) returns (fixed decimal(15));
|
||||
declare E character (*) varying;
|
||||
declare S fixed decimal (15) controlled;
|
||||
declare (a, b) fixed decimal (15);
|
||||
declare c character (1);
|
||||
declare p fixed binary;
|
||||
declare (empty_stack, invalid_expression) condition;
|
||||
|
||||
on condition (empty_stack) begin;
|
||||
put skip list ('Your expression is not valid.');
|
||||
stop;
|
||||
end;
|
||||
on condition (invalid_expression) begin;
|
||||
put skip list ('Your expression is not valid.');
|
||||
stop;
|
||||
end;
|
||||
|
||||
do p = 1 to length(E);
|
||||
c = substr(E, p, 1);
|
||||
if index('123456789', c) > 0 then
|
||||
do; allocate S; S = c; end;
|
||||
else
|
||||
do;
|
||||
if allocation(S) = 0 then signal condition (empty_stack);
|
||||
b = S; free S;
|
||||
if allocation(S) = 0 then signal condition (empty_stack);
|
||||
a = S;
|
||||
select (c);
|
||||
when ('+') S = a + b;
|
||||
when ('-') S = a - b;
|
||||
when ('*') S = a * b;
|
||||
when ('/') S = a / b;
|
||||
when ('^') S = a ** b;
|
||||
otherwise signal condition (invalid_expression);
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
if allocation(S) ^= 1 then signal condition (invalid_expression);
|
||||
return (S);
|
||||
END eval;
|
||||
|
||||
/* Check that the player has used every digit and no others. */
|
||||
VALIDATE: procedure (E);
|
||||
declare E character (*) varying;
|
||||
declare E2 character (length(E)), (i, j) fixed binary;
|
||||
declare digits(9) character (1) static initial
|
||||
('1', '2', '3', '4', '5', '6', '7', '8', '9');
|
||||
|
||||
E2 = translate(E, ' ', '+-*/' );
|
||||
do i = 1 to 4;
|
||||
j = index(E2, digits(k(i)));
|
||||
if j > 0 then
|
||||
substr(E2, j, 1) = ' ';
|
||||
else
|
||||
do; put skip list ('You must use the digits supplied.'); stop; end;
|
||||
end;
|
||||
if E2 ^= '' then
|
||||
do; put skip list ('You must use every digit supplied, and no others.'); stop; end;
|
||||
end VALIDATE;
|
||||
|
||||
declare E character (40) varying;
|
||||
declare k(4) fixed decimal;
|
||||
declare (time, random) builtin;
|
||||
declare V fixed decimal (15);
|
||||
|
||||
k = random(TIME);
|
||||
k = 9*random() + 1;
|
||||
put skip edit ('Here are four integers:', k) (a);
|
||||
put skip list ('With these integers, make up an arithmetic expression' ||
|
||||
' that evaluates to 24.');
|
||||
put skip list ('You can use any of the operators +, -, *, and /');
|
||||
put skip list ('E.g., Given the integers 1, 3, 7, and 6,' ||
|
||||
' the expression 6*3+7-1 evaluates to 24.');
|
||||
|
||||
put skip list ('Please type an arithmetic expression :');
|
||||
get edit (E) (L) COPY;
|
||||
|
||||
CALL VALIDATE (E); /* Check that the player has used every digit and no others. */
|
||||
|
||||
E = CTP(E);
|
||||
V = EVAL (E);
|
||||
if V = 24 then
|
||||
put skip list ('Congratulations: the expression evaluates to 24.');
|
||||
else
|
||||
put skip edit ('The result is ', trim(V), ' which is not correct') (a);
|
||||
|
||||
end TWENTYFOUR;
|
||||
38
Task/24-game/Perl-6/24-game.pl6
Normal file
38
Task/24-game/Perl-6/24-game.pl6
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
grammar Exp24 {
|
||||
token TOP { ^ <exp> $ }
|
||||
token exp { <term> [ <op> <term> ]* }
|
||||
token term { '(' <exp> ')' | \d }
|
||||
token op { '+' | '-' | '*' | '/' }
|
||||
}
|
||||
|
||||
my @digits = roll 4, 1..9; # to a gamer, that's a "4d9" roll
|
||||
say "Here's your digits: {@digits}";
|
||||
|
||||
while my $exp = prompt "\n24-Exp? " {
|
||||
unless is-valid($exp, @digits) {
|
||||
say "Sorry, your expression is not valid!";
|
||||
next;
|
||||
}
|
||||
|
||||
my $value = eval $exp;
|
||||
say "$exp = $value";
|
||||
if $value == 24 {
|
||||
say "You win!";
|
||||
last;
|
||||
}
|
||||
say "Sorry, your expression doesn't evaluate to 24!";
|
||||
}
|
||||
|
||||
sub is-valid($exp, @digits) {
|
||||
unless ?Exp24.parse($exp) {
|
||||
say "Expression doesn't match rules!";
|
||||
return False;
|
||||
}
|
||||
|
||||
unless $exp.comb(/\d/).sort.join == @digits.sort.join {
|
||||
say "Expression must contain digits {@digits} only!";
|
||||
return False;
|
||||
}
|
||||
|
||||
return True;
|
||||
}
|
||||
109
Task/24-game/PowerShell/24-game.psh
Normal file
109
Task/24-game/PowerShell/24-game.psh
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
CLS
|
||||
|
||||
Function isNumeric ($x)
|
||||
{
|
||||
$x2 = 0
|
||||
$isNum = [System.Int32]::TryParse($x,[ref]$x2)
|
||||
Return $isNum
|
||||
}
|
||||
|
||||
$NumberOne = Random -Maximum 10 -Minimum 1
|
||||
$NumberTwo = Random -Maximum 10 -Minimum 1
|
||||
$NumberThree = Random -Maximum 10 -Minimum 1
|
||||
$NumberFour = Random -Maximum 10 -Minimum 1
|
||||
$NumberArray = @()
|
||||
$NumberArray += $NumberOne
|
||||
$NumberArray += $NumberTwo
|
||||
$NumberArray += $NumberThree
|
||||
$NumberArray += $NumberFour
|
||||
|
||||
Write-Host "Welcome to the 24 game!`n`nHere are your numbers: $NumberOne,$NumberTwo,$NumberThree and $NumberFour.`nUse division, multiplication, subtraction and addition to get 24 as a result with these 4 numbers.`n"
|
||||
|
||||
Do
|
||||
{
|
||||
$Wrong = 0
|
||||
$EndResult = $null
|
||||
$TempChar = $null
|
||||
$TempChar2 = $null
|
||||
$Count = $null
|
||||
$Result = Read-Host
|
||||
Foreach($Char in $Result.ToCharArray())
|
||||
{
|
||||
Switch($Char)
|
||||
{
|
||||
$NumberOne
|
||||
{
|
||||
}
|
||||
$NumberTwo
|
||||
{
|
||||
}
|
||||
$NumberThree
|
||||
{
|
||||
}
|
||||
$NumberFour
|
||||
{
|
||||
}
|
||||
"+"
|
||||
{
|
||||
}
|
||||
"-"
|
||||
{
|
||||
}
|
||||
"*"
|
||||
{
|
||||
}
|
||||
"/"
|
||||
{
|
||||
}
|
||||
"("
|
||||
{
|
||||
}
|
||||
")"
|
||||
{
|
||||
}
|
||||
" "
|
||||
{
|
||||
}
|
||||
Default
|
||||
{
|
||||
$Wrong = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
If($Wrong -eq 1)
|
||||
{
|
||||
Write-Warning "Wrong input! Please use only the given numbers."
|
||||
}
|
||||
Foreach($Char in $Result.ToCharArray())
|
||||
{
|
||||
If((IsNumeric $TempChar) -AND (IsNumeric $Char))
|
||||
{
|
||||
Write-Warning "Wrong input! Combining two or more numbers together is not allowed!"
|
||||
}
|
||||
$TempChar = $Char
|
||||
}
|
||||
Foreach($Char in $Result.ToCharArray())
|
||||
{
|
||||
If(IsNumeric $Char)
|
||||
{
|
||||
$Count++
|
||||
}
|
||||
}
|
||||
If($Count -eq 4)
|
||||
{
|
||||
$EndResult = Invoke-Expression $Result
|
||||
If($EndResult -eq 24)
|
||||
{
|
||||
Write-Host "`nYou've won the game!"
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Host "`n$EndResult is not 24! Too bad."
|
||||
}
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Warning "Wrong input! You did not supply four numbers."
|
||||
}
|
||||
}
|
||||
While($EndResult -ne 24)
|
||||
11
Task/24-game/ProDOS/24-game.dos
Normal file
11
Task/24-game/ProDOS/24-game.dos
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
:a
|
||||
editvar /modify -random- = <10
|
||||
printline These are your four digits: -random- -random- -random- -random-
|
||||
printline Use an algorithm to make the number 24.
|
||||
editvar /newvar /value=a /userinput=1 /title=Algorithm:
|
||||
do -a-
|
||||
if -a- /hasvalue 24 printline Your algorithm worked! & goto :b (
|
||||
) else printline Your algorithm did not work.
|
||||
:b
|
||||
editvar /newvar /value=b /userinput=1 /title=Do you want to play again?
|
||||
if -b- /hasvalue y goto :a else exitcurrentprogram
|
||||
160
Task/24-game/PureBasic/24-game.purebasic
Normal file
160
Task/24-game/PureBasic/24-game.purebasic
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
#digitCount = 4
|
||||
Global Dim digits(#digitCount - 1) ;holds random digits
|
||||
|
||||
Procedure showDigits()
|
||||
Print(#CRLF$ + "These are your four digits: ")
|
||||
Protected i
|
||||
For i = 0 To #digitCount - 1
|
||||
Print(Str(digits(i)))
|
||||
If i < (#digitCount - 1)
|
||||
Print(", ")
|
||||
Else
|
||||
PrintN("")
|
||||
EndIf
|
||||
Next
|
||||
Print("24 = ")
|
||||
EndProcedure
|
||||
|
||||
Procedure playAgain()
|
||||
Protected answer.s
|
||||
Repeat
|
||||
Print("Play again (y/n)? ")
|
||||
answer = LCase(Left(Trim(Input()), 1))
|
||||
Select answer
|
||||
Case "n"
|
||||
ProcedureReturn #False
|
||||
Case "y"
|
||||
ProcedureReturn #True
|
||||
Default
|
||||
PrintN("")
|
||||
Continue
|
||||
EndSelect
|
||||
ForEver
|
||||
EndProcedure
|
||||
|
||||
Procedure allDigitsUsed()
|
||||
Protected i
|
||||
For i = 0 To #digitCount - 1
|
||||
If digits(i) <> 0
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
Next
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
Procedure isValidDigit(d)
|
||||
For i = 0 To #digitCount - 1
|
||||
If digits(i) = d
|
||||
digits(i) = 0
|
||||
ProcedureReturn #True
|
||||
EndIf
|
||||
Next
|
||||
ProcedureReturn #False
|
||||
EndProcedure
|
||||
|
||||
Procedure doOperation(List op.c(), List operand.f())
|
||||
Protected x.f, y.f, op.c
|
||||
op = op(): DeleteElement(op())
|
||||
If op = '('
|
||||
ProcedureReturn #False ;end of sub-expression
|
||||
EndIf
|
||||
|
||||
y = operand(): DeleteElement(operand())
|
||||
x = operand()
|
||||
Select op
|
||||
Case '+'
|
||||
x + y
|
||||
Case '-'
|
||||
x - y
|
||||
Case '*'
|
||||
x * y
|
||||
Case '/'
|
||||
x / y
|
||||
EndSelect
|
||||
operand() = x
|
||||
ProcedureReturn #True ;operation completed
|
||||
EndProcedure
|
||||
|
||||
;returns error if present and the expression results in *result\f
|
||||
Procedure.s parseExpression(expr.s, *result.Float)
|
||||
NewList op.c()
|
||||
NewList operand.f()
|
||||
expr = ReplaceString(expr, " ", "") ;remove spaces
|
||||
|
||||
If Len(expr) = 0: *result\f = 0: ProcedureReturn "": EndIf ;no expression, return zero
|
||||
|
||||
Protected *ech.Character = @expr, lastWasDigit, lastWasOper, parenCheck, c.c
|
||||
While *ech\c
|
||||
c = *ech\c
|
||||
Select c
|
||||
Case '*', '/', '-', '+'
|
||||
If Not lastWasDigit: ProcedureReturn "Improper syntax, need a digit between operators.": EndIf
|
||||
If ListSize(op()) And (FindString("*/", Chr(op()), 1) Or (FindString("+-", Chr(op()), 1) And FindString("+-", Chr(c), 1)))
|
||||
doOperation(op(), operand())
|
||||
EndIf
|
||||
AddElement(op()): op() = c
|
||||
lastWasOper = #True: lastWasDigit = #False
|
||||
Case '('
|
||||
If lastWasDigit: ProcedureReturn "Improper syntax, need an operator before left paren.": EndIf
|
||||
AddElement(op()): op() = c
|
||||
parenCheck + 1: lastWasOper = #False
|
||||
Case ')'
|
||||
parenCheck - 1: If parenCheck < 0: ProcedureReturn "Improper syntax, missing a left paren.": EndIf
|
||||
If Not lastWasDigit: ProcedureReturn "Improper syntax, missing a digit before right paren.": EndIf
|
||||
Repeat: Until Not doOperation(op(),operand())
|
||||
lastWasDigit = #True
|
||||
Case '1' To '9'
|
||||
If lastWasDigit: ProcedureReturn "Improper syntax, need an operator between digits.": EndIf
|
||||
AddElement(operand()): operand() = c - '0'
|
||||
If Not isValidDigit(operand()): ProcedureReturn "'" + Chr(c) + "' is not a valid digit.": EndIf
|
||||
lastWasDigit = #True: lastWasOper = #False
|
||||
Default
|
||||
ProcedureReturn "'" + Chr(c) + "' is not allowed in the expression."
|
||||
EndSelect
|
||||
*ech + SizeOf(Character)
|
||||
Wend
|
||||
|
||||
If parenCheck <> 0 Or lastWasOper: ProcedureReturn "Improper syntax, missing a right paren or digit.": EndIf
|
||||
Repeat
|
||||
If Not ListSize(op()): Break: EndIf
|
||||
Until Not doOperation(op(),operand())
|
||||
*result\f = operand()
|
||||
ProcedureReturn "" ;no error
|
||||
EndProcedure
|
||||
|
||||
Define success, failure, result.f, error.s, i
|
||||
If OpenConsole()
|
||||
PrintN("The 24 Game" + #CRLF$)
|
||||
PrintN("Given four digits and using just the +, -, *, and / operators; and the")
|
||||
PrintN("possible use of brackets, (), enter an expression that equates to 24.")
|
||||
Repeat
|
||||
For i = 0 To #digitCount - 1
|
||||
digits(i) = 1 + Random(8)
|
||||
Next
|
||||
|
||||
showDigits()
|
||||
error = parseExpression(Input(), @result)
|
||||
If error = ""
|
||||
If Not allDigitsUsed()
|
||||
PrintN( "Wrong! (you didn't use all digits)"): failure + 1
|
||||
ElseIf result = 24.0
|
||||
PrintN("Correct!"): success + 1
|
||||
Else
|
||||
Print("Wrong! (you got ")
|
||||
If result <> Int(result)
|
||||
PrintN(StrF(result, 2) + ")")
|
||||
Else
|
||||
PrintN(Str(result) + ")")
|
||||
EndIf
|
||||
failure + 1
|
||||
EndIf
|
||||
Else
|
||||
PrintN(error): failure + 1
|
||||
EndIf
|
||||
Until Not playAgain()
|
||||
|
||||
PrintN("success:" + Str(success) + " failure:" + Str(failure) + " total:" + Str(success + failure))
|
||||
|
||||
Print(#CRLF$ + "Press ENTER to exit"): Input()
|
||||
CloseConsole()
|
||||
EndIf
|
||||
73
Task/24-game/TUSCRIPT/24-game.tuscript
Normal file
73
Task/24-game/TUSCRIPT/24-game.tuscript
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
$$ MODE TUSCRIPT
|
||||
BUILD X_TABLE blanks = ":': :"
|
||||
|
||||
SECTION game
|
||||
operators="*'/'+'-'(')",numbers=""
|
||||
|
||||
LOOP n=1,4
|
||||
number=RANDOM_NUMBERS (1,9,1)
|
||||
numbers=APPEND(numbers,number)
|
||||
ENDLOOP
|
||||
|
||||
SET allowed=APPEND (numbers,operators)
|
||||
SET allowed=MIXED_SORT (allowed)
|
||||
SET allowed=REDUCE (allowed)
|
||||
BUILD S_TABLE ALLOWED =*
|
||||
DATA '{allowed}'
|
||||
|
||||
SET checksum=DIGIT_SORT (numbers)
|
||||
|
||||
printnumbers=EXCHANGE (numbers,blanks)
|
||||
printoperat=EXCHANGE (operators,blanks)
|
||||
|
||||
PRINT "Your numbers ", printnumbers
|
||||
PRINT "Use only these operators ", printoperat
|
||||
PRINT "Enter an expression that equates to 24"
|
||||
PRINT "Enter 'l' for new numbers"
|
||||
PRINT "Your 4 digits: ",printnumbers
|
||||
|
||||
DO play
|
||||
ENDSECTION
|
||||
|
||||
SECTION check_expr
|
||||
SET pos = VERIFY (expr,allowed)
|
||||
IF (pos!=0) THEN
|
||||
PRINT "wrong entry on position ",pos
|
||||
DO play
|
||||
STOP
|
||||
ELSE
|
||||
SET yourdigits = STRINGS (expr,":>/:")
|
||||
SET yourchecksum = DIGIT_SORT (yourdigits)
|
||||
IF (checksum!=yourchecksum) THEN
|
||||
PRINT/ERROR "wrong digits"
|
||||
DO play
|
||||
STOP
|
||||
ELSE
|
||||
CONTINUE
|
||||
ENDIF
|
||||
ENDIF
|
||||
ENDSECTION
|
||||
|
||||
SECTION play
|
||||
LOOP n=1,3
|
||||
ASK "Expression {n}": expr=""
|
||||
IF (expr=="l") THEN
|
||||
RELEASE S_TABLE allowed
|
||||
PRINT "Your new numbers"
|
||||
DO game
|
||||
ELSEIF (expr!="") THEN
|
||||
DO check_expr
|
||||
sum={expr}
|
||||
IF (sum!=24) THEN
|
||||
PRINT/ERROR expr," not equates 24 but ",sum
|
||||
CYCLE
|
||||
ELSE
|
||||
PRINT "BINGO ", expr," equates ", sum
|
||||
STOP
|
||||
ENDIF
|
||||
ELSE
|
||||
CYCLE
|
||||
ENDIF
|
||||
ENDLOOP
|
||||
ENDSECTION
|
||||
DO game
|
||||
167
Task/24-game/TorqueScript/24-game.torquescript
Normal file
167
Task/24-game/TorqueScript/24-game.torquescript
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
function startTwentyFourGame()
|
||||
{
|
||||
if($numbers !$= "")
|
||||
{
|
||||
echo("Ending current 24 game...");
|
||||
endTwentyFourGame();
|
||||
}
|
||||
|
||||
echo("Welcome to the 24 game!");
|
||||
echo("Generating 4 numbers...");
|
||||
for(%a = 0; %a < 4; %a++)
|
||||
$numbers = setWord($numbers, %a, getRandom(0, 9));
|
||||
|
||||
echo("Numbers generated! Here are your numbers:");
|
||||
echo($numbers);
|
||||
echo("Use try24Equation( equation ); to try and guess the equation.");
|
||||
|
||||
$TwentyFourGame = 1;
|
||||
}
|
||||
|
||||
function endTwentyFourGame()
|
||||
{
|
||||
if(!$TwentyFourGame)
|
||||
{
|
||||
echo("No 24 game is active!");
|
||||
return false;
|
||||
}
|
||||
|
||||
echo("Ending the 24 game.");
|
||||
$numbers = "";
|
||||
$TwentyFourGame = 0;
|
||||
}
|
||||
|
||||
function try24Equation(%equ)
|
||||
{
|
||||
if(!$TwentyFourGame)
|
||||
{
|
||||
echo("No 24 game is active!");
|
||||
return false;
|
||||
}
|
||||
%numbers = "0123456789";
|
||||
%operators = "+-*x/()";
|
||||
%tempchars = $numbers;
|
||||
%other = strReplace(%tempchars, " ", "");
|
||||
|
||||
//Check it and make sure it has all the stuff
|
||||
%equ = strReplace(%equ, " ", "");
|
||||
%length = strLen(%equ);
|
||||
|
||||
for(%a = 0; %a < %Length; %a++)
|
||||
{
|
||||
%Char = getSubStr(%equ, %a, 1);
|
||||
if(%a+1 != %Length)
|
||||
%Next = getSubStr(%equ, %a+1, 1);
|
||||
else
|
||||
%Next = " ";
|
||||
|
||||
if(strPos(%numbers @ %operators, %char) < 0)
|
||||
{
|
||||
echo("The equation you entered is invalid! Try again.");
|
||||
return false;
|
||||
}
|
||||
if(strPos(%tempchars, %char) < 0 && strPos(%operators, %char) < 0)
|
||||
{
|
||||
echo("The equation you entered uses a number you were not given! Try again.");
|
||||
return false;
|
||||
}
|
||||
else if(strPos(%numbers, %next) >= 0 && strPos(%numbers, %char) >= 0)
|
||||
{
|
||||
echo("No numbers above 9 please! Try again.");
|
||||
echo(%next SPC %char SPC %a);
|
||||
return false;
|
||||
}
|
||||
else if(strPos(%operators, %char) > 0)
|
||||
continue;
|
||||
|
||||
%pos = 2*strPos(%other, %char);
|
||||
if(%pos < 0)
|
||||
return "ERROROMG";
|
||||
|
||||
//Remove it from the allowed numbers
|
||||
%tempchars = removeWord(%tempchars, %pos/2);
|
||||
%other = getSubStr(%other, 0, %pos) @ getSubStr(%other, %pos+1, strLen(%other));
|
||||
}
|
||||
|
||||
%result = doEquation(%equ);
|
||||
|
||||
if(%result != 24)
|
||||
{
|
||||
echo("Your equation resulted to" SPC %result @ ", not 24! Try again.");
|
||||
return false;
|
||||
}
|
||||
|
||||
for(%a = 0; %a < 4; %a++)
|
||||
$numbers = setWord($numbers, %a, getRandom(0, 9));
|
||||
|
||||
echo("Great job!" SPC %equ SPC "Does result to 24! Here's another set for you:");
|
||||
echo($numbers);
|
||||
}
|
||||
|
||||
//Evaluates an equation without using eval.
|
||||
function doEquation(%equ)
|
||||
{ //Validate the input
|
||||
%equ = strReplace(%equ, " ", "");%equ = strReplace(%equ, "*", "x");
|
||||
%equ = strReplace(%equ, "+", " + ");%equ = strReplace(%equ, "x", " x ");
|
||||
%equ = strReplace(%equ, "/", " / ");%equ = strReplace(%equ, "-", " - ");
|
||||
|
||||
//Parenthesis'
|
||||
while(strPos(%equ, "(") > -1 && strPos(%equ, ")") > 0)
|
||||
{
|
||||
%start = strPos(%equ, "(");
|
||||
%end = %start;
|
||||
%level = 1;
|
||||
while(%level != 0 && %end != strLen(%equ))
|
||||
{
|
||||
%end++;
|
||||
if(getsubStr(%equ, %end, 1) $= "(") %level++;
|
||||
if(getsubStr(%equ, %end, 1) $= ")") %level--;
|
||||
}
|
||||
if(%level != 0)
|
||||
return "ERROR";
|
||||
%inbrackets = getsubStr(%equ, %start+1, %end - strLen(getsubStr(%equ, 0, %start + 1)));
|
||||
%leftofbrackets = getsubStr(%equ, 0, %start);
|
||||
%rightofbrackets = getsubStr(%equ, %end + 1, strLen(%equ) - %end);
|
||||
%equ = %leftofbrackets @ doEquation(%inbrackets) @ %rightofbrackets;
|
||||
}
|
||||
|
||||
if(strPos(%equ, "ERROR") >= 0)
|
||||
return "ERROR";
|
||||
|
||||
//Multiplication/Division loop
|
||||
for(%a = 0; %a < getWordCount(%equ); %a++)
|
||||
{
|
||||
if(getWord(%equ, %a) $= "x" || getWord(%equ, %a) $= "/" && %a != 0)
|
||||
{
|
||||
%f = getWord(%equ, %a - 1);
|
||||
%l = getWord(%equ, %a + 1);
|
||||
%o = getWord(%equ, %a);
|
||||
switch$(%o)
|
||||
{
|
||||
case "x": %a--;
|
||||
%equ = removeWord(removeWord(setWord(%equ, %a+1, %f * %l), %a+2), %a);
|
||||
case "/": %a--;
|
||||
%equ = removeWord(removeWord(setWord(%equ, %a+1, %f / %l), %a+2), %a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Addition/Subraction loop
|
||||
for(%a = 0; %a < getWordCount(%equ); %a++)
|
||||
{
|
||||
if(getWord(%equ, %a) $= "+" || getWord(%equ, %a) $= "-" && %a != 0)
|
||||
{
|
||||
%f = getWord(%equ, %a - 1);
|
||||
%l = getWord(%equ, %a + 1);
|
||||
%o = getWord(%equ, %a);
|
||||
switch$(%o)
|
||||
{
|
||||
case "+": %a--;
|
||||
%equ = removeWord(removeWord(setWord(%equ, %a+1, %f + %l), %a+2), %a);
|
||||
case "-": %a--;
|
||||
%equ = removeWord(removeWord(setWord(%equ, %a+1, %f - %l), %a+2), %a);
|
||||
}
|
||||
}
|
||||
}
|
||||
return %equ;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue