24 game/Solve: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 13: Line 13:
{{trans|Nim}}
{{trans|Nim}}


<lang 11l>[Char = ((Float, Float) -> Float)] op
<syntaxhighlight lang=11l>[Char = ((Float, Float) -> Float)] op
op[Char(‘+’)] = (x, y) -> x + y
op[Char(‘+’)] = (x, y) -> x + y
op[Char(‘-’)] = (x, y) -> x - y
op[Char(‘-’)] = (x, y) -> x - y
Line 52: Line 52:
[5, 7, 9, 7],
[5, 7, 9, 7],
[3, 3, 8, 8]]
[3, 3, 8, 8]]
print(‘solve(’nums‘) -> ’solve(nums))</lang>
print(‘solve(’nums‘) -> ’solve(nums))</syntaxhighlight>


{{out}}
{{out}}
Line 71: Line 71:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<lang AArch64 Assembly>
<syntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program game24Solvex64.s */
/* program game24Solvex64.s */
Line 502: Line 502:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 526: Line 526:


Note: the permute function was locally from [[Permutations#ABAP|here]]
Note: the permute function was locally from [[Permutations#ABAP|here]]
<lang ABAP>data: lv_flag type c,
<syntaxhighlight lang=ABAP>data: lv_flag type c,
lv_number type i,
lv_number type i,
lt_numbers type table of i.
lt_numbers type table of i.
Line 723: Line 723:
modify iv_set index lv_perm from lv_temp_2.
modify iv_set index lv_perm from lv_temp_2.
modify iv_set index lv_len from lv_temp.
modify iv_set index lv_len from lv_temp.
endform.</lang>
endform.</syntaxhighlight>


Sample Runs:
Sample Runs:
Line 1,016: Line 1,016:
=={{header|Argile}}==
=={{header|Argile}}==
{{works with|Argile|1.0.0}}
{{works with|Argile|1.0.0}}
<lang Argile>die "Please give 4 digits as argument 1\n" if argc < 2
<syntaxhighlight lang=Argile>die "Please give 4 digits as argument 1\n" if argc < 2


print a function that given four digits argv[1] subject to the rules of \
print a function that given four digits argv[1] subject to the rules of \
Line 1,113: Line 1,113:
(roperators[(rrop[rpn][2])]) (rdigits[3]);
(roperators[(rrop[rpn][2])]) (rdigits[3]);
return buffer as text
return buffer as text
nil</lang>
nil</syntaxhighlight>
Examples:
Examples:
<pre>$ arc 24_game_solve.arg -o 24_game_solve.c
<pre>$ arc 24_game_solve.arg -o 24_game_solve.c
Line 1,127: Line 1,127:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<lang ARM Assembly>
<syntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program game24Solver.s */
/* program game24Solver.s */
Line 1,514: Line 1,514:
.include "../affichage.inc"
.include "../affichage.inc"


</syntaxhighlight>
</lang>
{{output}}
{{output}}
<pre>
<pre>
Line 1,543: Line 1,543:
{{works with|AutoHotkey_L}}
{{works with|AutoHotkey_L}}
Output is in RPN.
Output is in RPN.
<lang AHK>#NoEnv
<syntaxhighlight lang=AHK>#NoEnv
InputBox, NNNN ; user input 4 digits
InputBox, NNNN ; user input 4 digits
NNNN := RegExReplace(NNNN, "(\d)(?=\d)", "$1,") ; separate with commas for the sort command
NNNN := RegExReplace(NNNN, "(\d)(?=\d)", "$1,") ; separate with commas for the sort command
Line 1,650: Line 1,650:
o := A_LoopField o
o := A_LoopField o
return o
return o
}</lang>
}</syntaxhighlight>
{{out}}for 1127:
{{out}}for 1127:
<pre>
<pre>
Line 1,665: Line 1,665:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic>
<syntaxhighlight lang=bbcbasic>
PROCsolve24("1234")
PROCsolve24("1234")
PROCsolve24("6789")
PROCsolve24("6789")
Line 1,722: Line 1,722:
IF I% > 4 PRINT "No solution found"
IF I% > 4 PRINT "No solution found"
ENDPROC
ENDPROC
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,738: Line 1,738:
Note: This a brute-force approach with time complexity <em>O(6<sup>n</sup>.n.(2n-3)!!)</em> and recursion depth <em>n</em>.<br>
Note: This a brute-force approach with time complexity <em>O(6<sup>n</sup>.n.(2n-3)!!)</em> and recursion depth <em>n</em>.<br>


<lang c>#include <stdio.h>
<syntaxhighlight lang=c>#include <stdio.h>


typedef struct {int val, op, left, right;} Node;
typedef struct {int val, op, left, right;} Node;
Line 1,820: Line 1,820:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 1,828: Line 1,828:
This code may be extended to work with more than 4 numbers, goals other than 24, or different digit ranges. Operations have been manually determined for these parameters, with the belief they are complete.
This code may be extended to work with more than 4 numbers, goals other than 24, or different digit ranges. Operations have been manually determined for these parameters, with the belief they are complete.


<lang cpp>
<syntaxhighlight lang=cpp>
#include <iostream>
#include <iostream>
#include <ratio>
#include <ratio>
Line 1,919: Line 1,919:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,975: Line 1,975:
Redundant expressions are filtered out (based on https://www.4nums.com/theory/) but I'm not sure I caught them all.
Redundant expressions are filtered out (based on https://www.4nums.com/theory/) but I'm not sure I caught them all.
{{works with|C sharp|8}}
{{works with|C sharp|8}}
<lang csharp>using System;
<syntaxhighlight lang=csharp>using System;
using System.Collections.Generic;
using System.Collections.Generic;
using static System.Linq.Enumerable;
using static System.Linq.Enumerable;
Line 2,289: Line 2,289:
$"{(wrapLeft ? $"({Left})" : $"{Left}")} {Symbol} {(wrapRight ? $"({Right})" : $"{Right}")}";
$"{(wrapLeft ? $"({Left})" : $"{Left}")} {Symbol} {(wrapRight ? $"({Right})" : $"{Right}")}";
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,325: Line 2,325:
=={{header|Ceylon}}==
=={{header|Ceylon}}==
Don't forget to import ceylon.random in your module.ceylon file.
Don't forget to import ceylon.random in your module.ceylon file.
<lang ceylon>import ceylon.random {
<syntaxhighlight lang=ceylon>import ceylon.random {
DefaultRandom
DefaultRandom
}
}
Line 2,457: Line 2,457:
expressions.each(print);
expressions.each(print);
}
}
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang Clojure>(ns rosettacode.24game.solve
<syntaxhighlight lang=Clojure>(ns rosettacode.24game.solve
(:require [clojure.math.combinatorics :as c]
(:require [clojure.math.combinatorics :as c]
[clojure.walk :as w]))
[clojure.walk :as w]))
Line 2,484: Line 2,484:
(map println)
(map println)
doall
doall
count))</lang>
count))</syntaxhighlight>


The function <code>play24</code> works by substituting the given digits and the four operations into the binary tree patterns (o (o n n) (o n n)), (o (o (o n n) n) n), and (o n (o n (o n n))).
The function <code>play24</code> works by substituting the given digits and the four operations into the binary tree patterns (o (o n n) (o n n)), (o (o (o n n) n) n), and (o n (o n (o n n))).
Line 2,490: Line 2,490:


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> >>SOURCE FORMAT FREE
<syntaxhighlight lang=cobol> >>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This code is dedicated to the public domain
*> This is GNUCobol 2.0
*> This is GNUCobol 2.0
Line 2,935: Line 2,935:
end-perform
end-perform
.
.
end program twentyfoursolve.</lang>
end program twentyfoursolve.</syntaxhighlight>


{{out}}
{{out}}
Line 2,965: Line 2,965:


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang=coffeescript>
# This program tries to find some way to turn four digits into an arithmetic
# This program tries to find some way to turn four digits into an arithmetic
# expression that adds up to 24.
# expression that adds up to 24.
Line 3,053: Line 3,053:
solution = solve_24_game a, b, c, d
solution = solve_24_game a, b, c, d
console.log "Solution for #{[a,b,c,d]}: #{solution ? 'no solution'}"
console.log "Solution for #{[a,b,c,d]}: #{solution ? 'no solution'}"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,076: Line 3,076:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


<lang lisp>(defconstant +ops+ '(* / + -))
<syntaxhighlight lang=lisp>(defconstant +ops+ '(* / + -))


(defun digits ()
(defun digits ()
Line 3,131: Line 3,131:
digits which evaluates to 24. The first form found is returned, or
digits which evaluates to 24. The first form found is returned, or
NIL if there is no solution."
NIL if there is no solution."
(solvable-p digits))</lang>
(solvable-p digits))</syntaxhighlight>


{{out}}
{{out}}
Line 3,149: Line 3,149:
This uses the Rational struct and permutations functions of two other Rosetta Code Tasks.
This uses the Rational struct and permutations functions of two other Rosetta Code Tasks.
{{trans|Scala}}
{{trans|Scala}}
<lang d>import std.stdio, std.algorithm, std.range, std.conv, std.string,
<syntaxhighlight lang=d>import std.stdio, std.algorithm, std.range, std.conv, std.string,
std.concurrency, permutations2, arithmetic_rational;
std.concurrency, permutations2, arithmetic_rational;


Line 3,184: Line 3,184:
foreach (const prob; [[6, 7, 9, 5], [3, 3, 8, 8], [1, 1, 1, 1]])
foreach (const prob; [[6, 7, 9, 5], [3, 3, 8, 8], [1, 1, 1, 1]])
writeln(prob, ": ", solve(24, prob));
writeln(prob, ": ", solve(24, prob));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[6, 7, 9, 5]: (6+(9*(7-5)))
<pre>[6, 7, 9, 5]: (6+(9*(7-5)))
Line 3,193: Line 3,193:
The program takes n numbers - not limited to 4 - builds the all possible legal rpn expressions according to the game rules, and evaluates them. Time saving : 4 5 + is the same as 5 4 + . Do not generate twice. Do not generate expressions like 5 6 * + which are not legal.
The program takes n numbers - not limited to 4 - builds the all possible legal rpn expressions according to the game rules, and evaluates them. Time saving : 4 5 + is the same as 5 4 + . Do not generate twice. Do not generate expressions like 5 6 * + which are not legal.


<lang scheme>
<syntaxhighlight lang=scheme>
;; use task [[RPN_to_infix_conversion#EchoLisp]] to print results
;; use task [[RPN_to_infix_conversion#EchoLisp]] to print results
(define (rpn->string rpn)
(define (rpn->string rpn)
Line 3,305: Line 3,305:
(writeln digits '→ target)
(writeln digits '→ target)
(try-rpn digits target))
(try-rpn digits target))
</lang>
</syntaxhighlight>


{{out}}
{{out}}
Line 3,352: Line 3,352:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Ruby}}
{{trans|Ruby}}
<lang elixir>defmodule Game24 do
<syntaxhighlight lang=elixir>defmodule Game24 do
@expressions [ ["((", "", ")", "", ")", ""],
@expressions [ ["((", "", ")", "", ")", ""],
["(", "(", "", "", "))", ""],
["(", "(", "", "", "))", ""],
Line 3,397: Line 3,397:
IO.puts "found #{length(solutions)} solutions, including #{hd(solutions)}"
IO.puts "found #{length(solutions)} solutions, including #{hd(solutions)}"
IO.inspect Enum.sort(solutions)
IO.inspect Enum.sort(solutions)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 3,418: Line 3,418:
=={{header|ERRE}}==
=={{header|ERRE}}==
ERRE hasn't an "EVAL" function so we must write an evaluation routine; this task is solved via "brute-force".
ERRE hasn't an "EVAL" function so we must write an evaluation routine; this task is solved via "brute-force".
<lang ERR>
<syntaxhighlight lang=ERR>
PROGRAM 24SOLVE
PROGRAM 24SOLVE


Line 3,730: Line 3,730:


END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,753: Line 3,753:
Via brute force.
Via brute force.


<lang Euler Math Toolbox>
<syntaxhighlight lang=Euler Math Toolbox>
>function try24 (v) ...
>function try24 (v) ...
$n=cols(v);
$n=cols(v);
Line 3,776: Line 3,776:
$return 0;
$return 0;
$endfunction
$endfunction
</syntaxhighlight>
</lang>


<lang Euler Math Toolbox>
<syntaxhighlight lang=Euler Math Toolbox>
>try24([1,2,3,4]);
>try24([1,2,3,4]);
Solved the problem
Solved the problem
Line 3,799: Line 3,799:
-1+5=4
-1+5=4
3-4=-1
3-4=-1
</syntaxhighlight>
</lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
Line 3,805: Line 3,805:
It eliminates all duplicate solutions which result from transposing equal digits.
It eliminates all duplicate solutions which result from transposing equal digits.
The basic solution is an adaption of the OCaml program.
The basic solution is an adaption of the OCaml program.
<lang fsharp>open System
<syntaxhighlight lang=fsharp>open System


let rec gcd x y = if x = y || x = 0 then y else if x < y then gcd y x else gcd y (x-y)
let rec gcd x y = if x = y || x = 0 then y else if x < y then gcd y x else gcd y (x-y)
Line 3,913: Line 3,913:
|> Seq.groupBy id
|> Seq.groupBy id
|> Seq.iter (fun x -> printfn "%s" (fst x))
|> Seq.iter (fun x -> printfn "%s" (fst x))
0</lang>
0</syntaxhighlight>
{{out}}
{{out}}
<pre>>solve24 3 3 3 4
<pre>>solve24 3 3 3 4
Line 3,942: Line 3,942:
=={{header|Factor}}==
=={{header|Factor}}==
Factor is well-suited for this task due to its homoiconicity and because it is a reverse-Polish notation evaluator. All we're doing is grouping each permutation of digits with three selections of the possible operators into quotations (blocks of code that can be stored like sequences). Then we <code>call</code> each quotation and print out the ones that equal 24. The <code>recover</code> word is an exception handler that is used to intercept divide-by-zero errors and continue gracefully by removing those quotations from consideration.
Factor is well-suited for this task due to its homoiconicity and because it is a reverse-Polish notation evaluator. All we're doing is grouping each permutation of digits with three selections of the possible operators into quotations (blocks of code that can be stored like sequences). Then we <code>call</code> each quotation and print out the ones that equal 24. The <code>recover</code> word is an exception handler that is used to intercept divide-by-zero errors and continue gracefully by removing those quotations from consideration.
<lang factor>USING: continuations grouping io kernel math math.combinatorics
<syntaxhighlight lang=factor>USING: continuations grouping io kernel math math.combinatorics
prettyprint quotations random sequences sequences.deep ;
prettyprint quotations random sequences sequences.deep ;
IN: rosetta-code.24-game
IN: rosetta-code.24-game
Line 3,959: Line 3,959:
print expressions [ [ 24= ] [ 2drop ] recover ] each ;
print expressions [ [ 24= ] [ 2drop ] recover ] each ;
24-game</lang>
24-game</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,987: Line 3,987:


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang Fortran>program solve_24
<syntaxhighlight lang=Fortran>program solve_24
use helpers
use helpers
implicit none
implicit none
Line 4,055: Line 4,055:
end function op
end function op


end program solve_24</lang>
end program solve_24</syntaxhighlight>


<lang Fortran>module helpers
<syntaxhighlight lang=Fortran>module helpers


contains
contains
Line 4,128: Line 4,128:
end subroutine nextpermutation
end subroutine nextpermutation


end module helpers</lang>
end module helpers</syntaxhighlight>
{{out}} (using g95):
{{out}} (using g95):
<pre> 3 6 7 9 : 3 *(( 6 - 7 )+ 9 )
<pre> 3 6 7 9 : 3 *(( 6 - 7 )+ 9 )
Line 4,145: Line 4,145:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Solution in '''RPN'''
<syntaxhighlight lang=gap># Solution in '''RPN'''
check := function(x, y, z)
check := function(x, y, z)
local r, c, s, i, j, k, a, b, p;
local r, c, s, i, j, k, a, b, p;
Line 4,228: Line 4,228:
# A tricky one:
# A tricky one:
Player24([3,3,8,8]);
Player24([3,3,8,8]);
"8383/-/"</lang>
"8383/-/"</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang=go>package main


import (
import (
Line 4,401: Line 4,401:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 8 6 7 6: No solution
<pre> 8 6 7 6: No solution
Line 4,416: Line 4,416:


=={{header|Gosu}}==
=={{header|Gosu}}==
<lang Gosu>
<syntaxhighlight lang=Gosu>
uses java.lang.Integer
uses java.lang.Integer
uses java.lang.Double
uses java.lang.Double
Line 4,527: Line 4,527:
print( "No solution!" )
print( "No solution!" )
}
}
</syntaxhighlight>
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==


<lang haskell>import Data.List
<syntaxhighlight lang=haskell>import Data.List
import Data.Ratio
import Data.Ratio
import Control.Monad
import Control.Monad
Line 4,580: Line 4,580:
nub $ permutations $ map Constant r4
nub $ permutations $ map Constant r4


main = getArgs >>= mapM_ print . solve 24 . map (toEnum . read)</lang>
main = getArgs >>= mapM_ print . solve 24 . map (toEnum . read)</syntaxhighlight>


Example use:
Example use:
Line 4,598: Line 4,598:
(8 / (2 / (9 - 3)))</pre>
(8 / (2 / (9 - 3)))</pre>
===Alternative version===
===Alternative version===
<lang haskell>import Control.Applicative
<syntaxhighlight lang=haskell>import Control.Applicative
import Data.List
import Data.List
import Text.PrettyPrint
import Text.PrettyPrint
Line 4,639: Line 4,639:


main = mapM_ (putStrLn . render . toDoc) $ solve 24 [2,3,8,9]</lang>
main = mapM_ (putStrLn . render . toDoc) $ solve 24 [2,3,8,9]</syntaxhighlight>
{{out}}
{{out}}
<pre>((8 / 2) * (9 - 3))
<pre>((8 / 2) * (9 - 3))
Line 4,658: Line 4,658:
This shares code with and solves the [[24_game#Icon_and_Unicon|24 game]]. A series of pattern expressions are built up and then populated with the permutations of the selected digits. Equations are skipped if they have been seen before. The procedure 'eval' was modified to catch zero divides. The solution will find either all occurrences or just the first occurrence of a solution.
This shares code with and solves the [[24_game#Icon_and_Unicon|24 game]]. A series of pattern expressions are built up and then populated with the permutations of the selected digits. Equations are skipped if they have been seen before. The procedure 'eval' was modified to catch zero divides. The solution will find either all occurrences or just the first occurrence of a solution.


<lang Icon>invocable all
<syntaxhighlight lang=Icon>invocable all
link strings # for csort, deletec, permutes
link strings # for csort, deletec, permutes


Line 4,733: Line 4,733:
suspend 2(="(", E(), =")") | # parenthesized subexpression, or ...
suspend 2(="(", E(), =")") | # parenthesized subexpression, or ...
tab(any(&digits)) # just a value
tab(any(&digits)) # just a value
end</lang>
end</syntaxhighlight>




Line 4,740: Line 4,740:


=={{header|J}}==
=={{header|J}}==
<lang J>perm=: (A.&i.~ !) 4
<syntaxhighlight lang=J>perm=: (A.&i.~ !) 4
ops=: ' ',.'+-*%' {~ >,{i.each 4 4 4
ops=: ' ',.'+-*%' {~ >,{i.each 4 4 4
cmask=: 1 + 0j1 * i.@{:@$@[ e. ]
cmask=: 1 + 0j1 * i.@{:@$@[ e. ]
Line 4,748: Line 4,748:
parens=: ], 0 paren 3, 0 paren 5, 2 paren 5, [: 0 paren 7 (0 paren 3)
parens=: ], 0 paren 3, 0 paren 5, 2 paren 5, [: 0 paren 7 (0 paren 3)
all=: [: parens [:,/ ops ,@,."1/ perm { [:;":each
all=: [: parens [:,/ ops ,@,."1/ perm { [:;":each
answer=: ({.@#~ 24 = ".)@all</lang>
answer=: ({.@#~ 24 = ".)@all</syntaxhighlight>


This implementation tests all 7680 candidate sentences.
This implementation tests all 7680 candidate sentences.
Line 4,765: Line 4,765:
Here is an alternative version that supports multi-digit numbers. It prefers expressions without parens, but searches for ones with if needed.
Here is an alternative version that supports multi-digit numbers. It prefers expressions without parens, but searches for ones with if needed.


<lang J>ops=: > , { 3#<'+-*%'
<syntaxhighlight lang=J>ops=: > , { 3#<'+-*%'
perms=: [: ":"0 [: ~. i.@!@# A. ]
perms=: [: ":"0 [: ~. i.@!@# A. ]
build=: 1 : '(#~ 24 = ".) @: u'
build=: 1 : '(#~ 24 = ".) @: u'
Line 4,779: Line 4,779:
if. 0 = #es do. es =. ([: ,/ [: ,/ ops combp"1 2/ perms) build y end.
if. 0 = #es do. es =. ([: ,/ [: ,/ ops combp"1 2/ perms) build y end.
es -."1 ' '
es -."1 ' '
)</lang>
)</syntaxhighlight>


{{out}}
{{out}}
Line 4,800: Line 4,800:


Note that this version does not extend to different digit ranges.
Note that this version does not extend to different digit ranges.
<lang java>import java.util.*;
<syntaxhighlight lang=java>import java.util.*;


public class Game24Player {
public class Game24Player {
Line 5,063: Line 5,063:
res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));
res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,107: Line 5,107:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
This is a translation of the C code.
This is a translation of the C code.
<lang javascript>var ar=[],order=[0,1,2],op=[],val=[];
<syntaxhighlight lang=javascript>var ar=[],order=[0,1,2],op=[],val=[];
var NOVAL=9999,oper="+-*/",out;
var NOVAL=9999,oper="+-*/",out;


Line 5,210: Line 5,210:
solve24("1234");
solve24("1234");
solve24("6789");
solve24("6789");
solve24("1127");</lang>
solve24("1127");</syntaxhighlight>


Examples:
Examples:
Line 5,224: Line 5,224:


'''Infrastructure:'''
'''Infrastructure:'''
<lang jq># Generate a stream of the permutations of the input array.
<syntaxhighlight lang=jq># Generate a stream of the permutations of the input array.
def permutations:
def permutations:
if length == 0 then []
if length == 0 then []
Line 5,261: Line 5,261:
| ($in[$i+1:] | triples) as $tail
| ($in[$i+1:] | triples) as $tail
| [$head, $in[$i], $tail]
| [$head, $in[$i], $tail]
end;</lang>
end;</syntaxhighlight>
'''Evaluation and pretty-printing of allowed expressions'''
'''Evaluation and pretty-printing of allowed expressions'''
<lang jq># Evaluate the input, which must be a number or a triple: [x, op, y]
<syntaxhighlight lang=jq># Evaluate the input, which must be a number or a triple: [x, op, y]
def eval:
def eval:
if type == "array" then
if type == "array" then
Line 5,285: Line 5,285:


def pp:
def pp:
"\(.)" | explode | map([.] | implode | if . == "," then " " elif . == "\"" then "" else . end) | join("");</lang>
"\(.)" | explode | map([.] | implode | if . == "," then " " elif . == "\"" then "" else . end) | join("");</syntaxhighlight>


'''24 Game''':
'''24 Game''':
<lang jq>def OPERATORS: ["+", "-", "*", "/"];
<syntaxhighlight lang=jq>def OPERATORS: ["+", "-", "*", "/"];


# Input: an array of 4 digits
# Input: an array of 4 digits
Line 5,308: Line 5,308:
;
;


solve(24), "Please try again."</lang>
solve(24), "Please try again."</syntaxhighlight>
{{out}}
{{out}}
<lang sh>$ jq -r -f Solve.jq
<syntaxhighlight lang=sh>$ jq -r -f Solve.jq
[1,2,3,4]
[1,2,3,4]
That was too easy. I found 242 answers, e.g. [4 * [1 + [2 + 3]]]
That was too easy. I found 242 answers, e.g. [4 * [1 + [2 + 3]]]
Line 5,325: Line 5,325:
[1,2,3,4,5,6]
[1,2,3,4,5,6]
That was too easy. I found 197926 answers, e.g. [[2 * [1 + 4]] + [3 + [5 + 6]]]
That was too easy. I found 197926 answers, e.g. [[2 * [1 + 4]] + [3 + [5 + 6]]]
Please try again.</lang>
Please try again.</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==


For julia version 0.5 and higher, the Combinatorics package must be installed and imported (`using Combinatorics`). Combinatorial functions like `nthperm` have been moved from Base to that package and are not available by default anymore.
For julia version 0.5 and higher, the Combinatorics package must be installed and imported (`using Combinatorics`). Combinatorial functions like `nthperm` have been moved from Base to that package and are not available by default anymore.
<lang julia>function solve24(nums)
<syntaxhighlight lang=julia>function solve24(nums)
length(nums) != 4 && error("Input must be a 4-element Array")
length(nums) != 4 && error("Input must be a 4-element Array")
syms = [+,-,*,/]
syms = [+,-,*,/]
Line 5,348: Line 5,348:
end
end
return "0"
return "0"
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>julia> for i in 1:10
<pre>julia> for i in 1:10
Line 5,367: Line 5,367:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|C}}
{{trans|C}}
<lang scala>// version 1.1.3
<syntaxhighlight lang=scala>// version 1.1.3


import java.util.Random
import java.util.Random
Line 5,465: Line 5,465:
println(if (solve24(n)) "" else "No solution")
println(if (solve24(n)) "" else "No solution")
}
}
}</lang>
}</syntaxhighlight>


Sample output:
Sample output:
Line 5,482: Line 5,482:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>dim d(4)
<syntaxhighlight lang=lb>dim d(4)
input "Enter 4 digits: "; a$
input "Enter 4 digits: "; a$
nD=0
nD=0
Line 5,604: Line 5,604:
exit function
exit function
[handler]
[handler]
end function</lang>
end function</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Line 5,610: Line 5,610:
Generic solver: pass card of any size with 1st argument and target number with second.
Generic solver: pass card of any size with 1st argument and target number with second.


<lang lua>
<syntaxhighlight lang=lua>
local SIZE = #arg[1]
local SIZE = #arg[1]
local GOAL = tonumber(arg[2]) or 24
local GOAL = tonumber(arg[2]) or 24
Line 5,685: Line 5,685:


permgen(input, SIZE)
permgen(input, SIZE)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,725: Line 5,725:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The code:
The code:
<lang Mathematica>
<syntaxhighlight lang=Mathematica>
treeR[n_] := Table[o[trees[a], trees[n - a]], {a, 1, n - 1}]
treeR[n_] := Table[o[trees[a], trees[n - a]], {a, 1, n - 1}]
treeR[1] := n
treeR[1] := n
Line 5,741: Line 5,741:
Permutations[Array[v, 4]], 1]],
Permutations[Array[v, 4]], 1]],
Quiet[(# /. v[q_] :> val[[q]]) == 24] &] /.
Quiet[(# /. v[q_] :> val[[q]]) == 24] &] /.
Table[v[q] -> val[[q]], {q, 4}])]</lang>
Table[v[q] -> val[[q]], {q, 4}])]</syntaxhighlight>


The <code>treeR</code> method recursively computes all possible operator trees for a certain number of inputs. It does this by tabling all combinations of distributions of inputs across the possible values. (For example, <code>treeR[4]</code> is allotted 4 inputs, so it returns <code>{o[treeR[3],treeR[1]],o[treeR[2],treeR[2]],o[treeR[1],treeR[3]]}</code>, where <code>o</code> is the operator (generic at this point).
The <code>treeR</code> method recursively computes all possible operator trees for a certain number of inputs. It does this by tabling all combinations of distributions of inputs across the possible values. (For example, <code>treeR[4]</code> is allotted 4 inputs, so it returns <code>{o[treeR[3],treeR[1]],o[treeR[2],treeR[2]],o[treeR[1],treeR[3]]}</code>, where <code>o</code> is the operator (generic at this point).
Line 5,775: Line 5,775:
**For each result, turn the expression into a string (for easy manipulation), strip the "<code>HoldForm</code>" wrapper, replace numbers like "-1*7" with "-7" (a idiosyncrasy of the conversion process), and remove any lingering duplicates. Some duplicates will still remain, notably constructs like "3 - 3" vs. "-3 + 3" and trivially similar expressions like "(8*3)*(6-5)" vs "(8*3)/(6-5)". Example run input and outputs:
**For each result, turn the expression into a string (for easy manipulation), strip the "<code>HoldForm</code>" wrapper, replace numbers like "-1*7" with "-7" (a idiosyncrasy of the conversion process), and remove any lingering duplicates. Some duplicates will still remain, notably constructs like "3 - 3" vs. "-3 + 3" and trivially similar expressions like "(8*3)*(6-5)" vs "(8*3)/(6-5)". Example run input and outputs:


<lang Mathematica>game24play[RandomInteger[{1, 9}, 4]]</lang>
<syntaxhighlight lang=Mathematica>game24play[RandomInteger[{1, 9}, 4]]</syntaxhighlight>


{{out}}
{{out}}
Line 5,800: Line 5,800:
An alternative solution operates on Mathematica expressions directly without using any inert intermediate form for the expression tree, but by using <code>Hold</code> to prevent Mathematica from evaluating the expression tree.
An alternative solution operates on Mathematica expressions directly without using any inert intermediate form for the expression tree, but by using <code>Hold</code> to prevent Mathematica from evaluating the expression tree.


<lang Mathematica>evaluate[HoldForm[op_[l_, r_]]] := op[evaluate[l], evaluate[r]];
<syntaxhighlight lang=Mathematica>evaluate[HoldForm[op_[l_, r_]]] := op[evaluate[l], evaluate[r]];
evaluate[x_] := x;
evaluate[x_] := x;
combine[l_, r_ /; evaluate[r] != 0] := {HoldForm[Plus[l, r]],
combine[l_, r_ /; evaluate[r] != 0] := {HoldForm[Plus[l, r]],
Line 5,834: Line 5,834:
solveMaintainOrder[1/5, Range[2, 5]]
solveMaintainOrder[1/5, Range[2, 5]]
solveCanPermute[1/5, Range[2, 5]]
solveCanPermute[1/5, Range[2, 5]]
solveSubsets[1/5, Range[2, 5]]</lang>
solveSubsets[1/5, Range[2, 5]]</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
Line 5,841: Line 5,841:
{{works with|Nim Compiler|0.19.4}}
{{works with|Nim Compiler|0.19.4}}


<lang nim>import algorithm, sequtils, strformat
<syntaxhighlight lang=nim>import algorithm, sequtils, strformat


type
type
Line 5,896: Line 5,896:
echo fmt"solve({nums}) -> {solve(nums)}"
echo fmt"solve({nums}) -> {solve(nums)}"


when isMainModule: main()</lang>
when isMainModule: main()</syntaxhighlight>


{{out}}
{{out}}
Line 5,915: Line 5,915:
=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>type expression =
<syntaxhighlight lang=ocaml>type expression =
| Const of float
| Const of float
| Sum of expression * expression (* e1 + e2 *)
| Sum of expression * expression (* e1 + e2 *)
Line 5,984: Line 5,984:
| x::xs -> comp x xs
| x::xs -> comp x xs
| [] -> assert false
| [] -> assert false
) all</lang>
) all</syntaxhighlight>


<pre>
<pre>
Line 6,000: Line 6,000:


Note: the <code>permute</code> function was taken from [http://faq.perl.org/perlfaq4.html#How_do_I_permute_N_e here]
Note: the <code>permute</code> function was taken from [http://faq.perl.org/perlfaq4.html#How_do_I_permute_N_e here]
<lang Perl># Fischer-Krause ordered permutation generator
<syntaxhighlight lang=Perl># Fischer-Krause ordered permutation generator
# http://faq.perl.org/perlfaq4.html#How_do_I_permute_N_e
# http://faq.perl.org/perlfaq4.html#How_do_I_permute_N_e
sub permute (&@) {
sub permute (&@) {
Line 6,053: Line 6,053:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>E:\Temp>24solve.pl
<pre>E:\Temp>24solve.pl
Line 6,082: Line 6,082:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\24_game_solve.exw</span>
<span style="color: #000080;font-style:italic;">-- demo\rosetta\24_game_solve.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 6,198: Line 6,198:
--solve24({6,9,7,4})</span>
--solve24({6,9,7,4})</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 6,214: Line 6,214:


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>main =>
<syntaxhighlight lang=Picat>main =>
foreach (_ in 1..10)
foreach (_ in 1..10)
Nums = [D : _ in 1..4, D = random() mod 9 + 1],
Nums = [D : _ in 1..4, D = random() mod 9 + 1],
Line 6,233: Line 6,233:
Exp3 =.. [Op,Exp1,Exp2],
Exp3 =.. [Op,Exp1,Exp2],
solve([(Num3,Exp3)|NumExps2]).
solve([(Num3,Exp3)|NumExps2]).
</syntaxhighlight>
</lang>


{{trans|Raku}}
{{trans|Raku}}
<lang Picat>import util.
<syntaxhighlight lang=Picat>import util.


main =>
main =>
Line 6,279: Line 6,279:
R := replace(R, F,T.to_string())
R := replace(R, F,T.to_string())
end,
end,
Res = R.</lang>
Res = R.</syntaxhighlight>


{{out}}
{{out}}
Line 6,313: Line 6,313:
Another approach:
Another approach:


<lang Picat>import util.
<syntaxhighlight lang=Picat>import util.


main =>
main =>
Line 6,358: Line 6,358:
check(A,X,B,Y,C,Z,D,Target,Expr) =>
check(A,X,B,Y,C,Z,D,Target,Expr) =>
Expr = [A,X,"(","(",B,Y,C,")", Z,D,")"].to_string2(),
Expr = [A,X,"(","(",B,Y,C,")", Z,D,")"].to_string2(),
Target =:= Expr.eval().</lang>
Target =:= Expr.eval().</syntaxhighlight>


{{out}}
{{out}}
Line 6,383: Line 6,383:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
We use Pilog (PicoLisp Prolog) to solve this task
We use Pilog (PicoLisp Prolog) to solve this task
<lang PicoLisp>(be play24 (@Lst @Expr) # Define Pilog rule
<syntaxhighlight lang=PicoLisp>(be play24 (@Lst @Expr) # Define Pilog rule
(permute @Lst (@A @B @C @D))
(permute @Lst (@A @B @C @D))
(member @Op1 (+ - * /))
(member @Op1 (+ - * /))
Line 6,400: Line 6,400:
(println @X) ) )
(println @X) ) )


(play24 5 6 7 8) # Call 'play24' function</lang>
(play24 5 6 7 8) # Call 'play24' function</syntaxhighlight>
{{out}}
{{out}}
<pre>(* (+ 5 7) (- 8 6))
<pre>(* (+ 5 7) (- 8 6))
Line 6,419: Line 6,419:
Note
Note
This example uses the math module:
This example uses the math module:
<lang ProDOS>editvar /modify -random- = <10
<syntaxhighlight lang=ProDOS>editvar /modify -random- = <10
:a
:a
editvar /newvar /withothervar /value=-random- /title=1
editvar /newvar /withothervar /value=-random- /title=1
Line 6,453: Line 6,453:
printline you could have done it by doing -c-
printline you could have done it by doing -c-
stoptask
stoptask
goto :b</lang>
goto :b</syntaxhighlight>


{{out}}
{{out}}
Line 6,474: Line 6,474:
rdiv/2 is use instead of //2 to enable the program to solve difficult cases as [3 3 8 8].
rdiv/2 is use instead of //2 to enable the program to solve difficult cases as [3 3 8 8].


<lang Prolog>play24(Len, Range, Goal) :-
<syntaxhighlight lang=Prolog>play24(Len, Range, Goal) :-
game(Len, Range, Goal, L, S),
game(Len, Range, Goal, L, S),
maplist(my_write, L),
maplist(my_write, L),
Line 6,564: Line 6,564:


my_write(V) :-
my_write(V) :-
format('~w ', [V]).</lang>
format('~w ', [V]).</syntaxhighlight>
{{out}}
{{out}}
<pre>?- play24(4,9, 24).
<pre>?- play24(4,9, 24).
Line 6,624: Line 6,624:
{{Works with|GNU Prolog|1.4.4}}
{{Works with|GNU Prolog|1.4.4}}
Little efforts to remove duplicates (e.g. output for [4,6,9,9]).
Little efforts to remove duplicates (e.g. output for [4,6,9,9]).
<lang prolog>:- initialization(main).
<syntaxhighlight lang=prolog>:- initialization(main).


solve(N,Xs,Ast) :-
solve(N,Xs,Ast) :-
Line 6,645: Line 6,645:


test(T) :- solve(24, [2,3,8,9], T).
test(T) :- solve(24, [2,3,8,9], T).
main :- forall(test(T), (write(T), nl)), halt.</lang>
main :- forall(test(T), (write(T), nl)), halt.</syntaxhighlight>
{{Output}}
{{Output}}
<pre>(9-3)*8//2
<pre>(9-3)*8//2
Line 6,665: Line 6,665:
The function is called '''solve''', and is integrated into the game player.
The function is called '''solve''', and is integrated into the game player.
The docstring of the solve function shows examples of its use when isolated at the Python command line.
The docstring of the solve function shows examples of its use when isolated at the Python command line.
<lang Python>'''
<syntaxhighlight lang=Python>'''
The 24 Game Player
The 24 Game Player
Line 6,823: Line 6,823:
print ("Thank you and goodbye")
print ("Thank you and goodbye")
main()</lang>
main()</syntaxhighlight>


{{out}}
{{out}}
Line 6,877: Line 6,877:
==={{header|Python}} Succinct===
==={{header|Python}} Succinct===
Based on the Julia example above.
Based on the Julia example above.
<lang python># -*- coding: utf-8 -*-
<syntaxhighlight lang=python># -*- coding: utf-8 -*-
import operator
import operator
from itertools import product, permutations
from itertools import product, permutations
Line 6,915: Line 6,915:
[3,3,8,8], # Difficult case requiring precise division
[3,3,8,8], # Difficult case requiring precise division
]:
]:
print(f"solve24({nums}) -> {solve24(nums)}")</lang>
print(f"solve24({nums}) -> {solve24(nums)}")</syntaxhighlight>


{{out}}
{{out}}
Line 6,932: Line 6,932:
==={{header|Python}} Recursive ===
==={{header|Python}} Recursive ===
This works for any amount of numbers by recursively picking two and merging them using all available operands until there is only one value left.
This works for any amount of numbers by recursively picking two and merging them using all available operands until there is only one value left.
<lang python># -*- coding: utf-8 -*-
<syntaxhighlight lang=python># -*- coding: utf-8 -*-
# Python 3
# Python 3
from operator import mul, sub, add
from operator import mul, sub, add
Line 6,976: Line 6,976:
except StopIteration:
except StopIteration:
print("No solution found")
print("No solution found")
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 6,993: Line 6,993:
===Python: using tkinter===
===Python: using tkinter===


<lang python>
<syntaxhighlight lang=python>
''' Python 3.6.5 code using Tkinter graphical user interface.
''' Python 3.6.5 code using Tkinter graphical user interface.
Combination of '24 game' and '24 game/Solve'
Combination of '24 game' and '24 game/Solve'
Line 7,353: Line 7,353:
g = Game(root)
g = Game(root)
root.mainloop()
root.mainloop()
</syntaxhighlight>
</lang>


=={{header|Quackery}}==
=={{header|Quackery}}==
Line 7,359: Line 7,359:
<code>permutations</code> is defined at [[Permutations#Quackery]] and <code>uniquewith</code> is defined at [[Remove duplicate elements#Quackery]].
<code>permutations</code> is defined at [[Permutations#Quackery]] and <code>uniquewith</code> is defined at [[Remove duplicate elements#Quackery]].


<lang Quackery> [ ' [ 0 1 2 3 ]
<syntaxhighlight lang=Quackery> [ ' [ 0 1 2 3 ]
permutations ] constant is numorders ( --> [ )
permutations ] constant is numorders ( --> [ )


Line 7,422: Line 7,422:
unbuild
unbuild
2 split nip
2 split nip
-2 split drop nest$ 90 wrap$ ] is solve ( n n n n --> )</lang>
-2 split drop nest$ 90 wrap$ ] is solve ( n n n n --> )</syntaxhighlight>


{{out}}
{{out}}
Line 7,452: Line 7,452:
=={{header|R}}==
=={{header|R}}==
This uses exhaustive search and makes use of R's ability to work with expressions as data. It is in principle general for any set of operands and binary operators.
This uses exhaustive search and makes use of R's ability to work with expressions as data. It is in principle general for any set of operands and binary operators.
<syntaxhighlight lang=r>
<lang r>
library(gtools)
library(gtools)


Line 7,487: Line 7,487:
return(NA)
return(NA)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<syntaxhighlight lang=r>
<lang r>
> solve24()
> solve24()
8 * (4 - 2 + 1)
8 * (4 - 2 + 1)
Line 7,502: Line 7,502:
> solve24(ops=c('-', '/')) #restricted set of operators
> solve24(ops=c('-', '/')) #restricted set of operators
(8 - 2)/(1/4)
(8 - 2)/(1/4)
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
The sequence of all possible variants of expressions with given numbers ''n1, n2, n3, n4'' and operations ''o1, o2, o3''.
The sequence of all possible variants of expressions with given numbers ''n1, n2, n3, n4'' and operations ''o1, o2, o3''.
<lang racket>
<syntaxhighlight lang=racket>
(define (in-variants n1 o1 n2 o2 n3 o3 n4)
(define (in-variants n1 o1 n2 o2 n3 o3 n4)
(let ([o1n (object-name o1)]
(let ([o1n (object-name o1)]
Line 7,523: Line 7,523:
`(,n1 ,o1n ((,n2 ,o3n ,n3) ,o2n ,n4))
`(,n1 ,o1n ((,n2 ,o3n ,n3) ,o2n ,n4))
`(,n1 ,o1n (,n2 ,o2n (,n3 ,o3n ,n4))))))))
`(,n1 ,o1n (,n2 ,o2n (,n3 ,o3n ,n4))))))))
</syntaxhighlight>
</lang>


Search for all solutions using brute force:
Search for all solutions using brute force:
<lang racket>
<syntaxhighlight lang=racket>
(define (find-solutions numbers (goal 24))
(define (find-solutions numbers (goal 24))
(define in-operations (list + - * /))
(define in-operations (list + - * /))
Line 7,542: Line 7,542:


(define (remove-from numbers . n) (foldr remq numbers n))
(define (remove-from numbers . n) (foldr remq numbers n))
</syntaxhighlight>
</lang>


Examples:
Examples:
Line 7,573: Line 7,573:
Since Raku uses Rational numbers for division (whenever possible) there is no loss of precision as is common with floating point division. So a comparison like (1 + 7) / (1 / 3) == 24 "Just Works"<sup>&trade;</sup>
Since Raku uses Rational numbers for division (whenever possible) there is no loss of precision as is common with floating point division. So a comparison like (1 + 7) / (1 / 3) == 24 "Just Works"<sup>&trade;</sup>


<lang perl6>use MONKEY-SEE-NO-EVAL;
<syntaxhighlight lang=perl6>use MONKEY-SEE-NO-EVAL;


my @digits;
my @digits;
Line 7,616: Line 7,616:
my %h = map { $_.Str => $_ }, @array;
my %h = map { $_.Str => $_ }, @array;
%h.values;
%h.values;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 7,668: Line 7,668:
Alternately, a version that doesn't use EVAL. More general case. Able to handle 3 or 4 integers, able to select the goal value.
Alternately, a version that doesn't use EVAL. More general case. Able to handle 3 or 4 integers, able to select the goal value.


<lang perl6>my %*SUB-MAIN-OPTS = :named-anywhere;
<syntaxhighlight lang=perl6>my %*SUB-MAIN-OPTS = :named-anywhere;


sub MAIN (*@parameters, Int :$goal = 24) {
sub MAIN (*@parameters, Int :$goal = 24) {
Line 7,757: Line 7,757:
demo and will show this message.\e[0m
demo and will show this message.\e[0m
========================================================================
========================================================================
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
When supplied 1399 on the command line:
When supplied 1399 on the command line:
Line 7,771: Line 7,771:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program helps the user find solutions to the game of 24. */
<syntaxhighlight lang=rexx>/*REXX program helps the user find solutions to the game of 24. */
/* start-of-help
/* start-of-help
┌───────────────────────────────────────────────────────────────────────┐
┌───────────────────────────────────────────────────────────────────────┐
Line 8,033: Line 8,033:
ger: say= '***error*** for argument:' y; say arg(1); errCode= 1; return 0
ger: say= '***error*** for argument:' y; say arg(1); errCode= 1; return 0
p: return word( arg(1), 1)
p: return word( arg(1), 1)
s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1)</lang>
s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1)</syntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here ──► &nbsp; &nbsp; [[CHANGESTR.REX]].
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here ──► &nbsp; &nbsp; [[CHANGESTR.REX]].
<br><br>
<br><br>
Line 8,146: Line 8,146:
{{trans|Tcl}}
{{trans|Tcl}}
{{works with|Ruby|2.1}}
{{works with|Ruby|2.1}}
<lang ruby>class TwentyFourGame
<syntaxhighlight lang=ruby>class TwentyFourGame
EXPRESSIONS = [
EXPRESSIONS = [
'((%dr %s %dr) %s %dr) %s %dr',
'((%dr %s %dr) %s %dr) %s %dr',
Line 8,186: Line 8,186:
puts "found #{solutions.size} solutions, including #{solutions.first}"
puts "found #{solutions.size} solutions, including #{solutions.first}"
puts solutions.sort
puts solutions.sort
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 8,220: Line 8,220:
=={{header|Rust}}==
=={{header|Rust}}==
{{works with|Rust|1.17}}
{{works with|Rust|1.17}}
<lang rust>#[derive(Clone, Copy, Debug)]
<syntaxhighlight lang=rust>#[derive(Clone, Copy, Debug)]
enum Operator {
enum Operator {
Sub,
Sub,
Line 8,385: Line 8,385:
[numbers[order[0]], numbers[order[1]], numbers[order[2]], numbers[order[3]]]
[numbers[order[0]], numbers[order[1]], numbers[order[2]], numbers[order[3]]]
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 8,399: Line 8,399:
A non-interactive player.
A non-interactive player.


<lang scala>def permute(l: List[Double]): List[List[Double]] = l match {
<syntaxhighlight lang=scala>def permute(l: List[Double]): List[List[Double]] = l match {
case Nil => List(Nil)
case Nil => List(Nil)
case x :: xs =>
case x :: xs =>
Line 8,423: Line 8,423:
}
}


def hasSolution(l: List[Double]) = permute(l) flatMap computeAllOperations filter (_._1 == 24) map (_._2)</lang>
def hasSolution(l: List[Double]) = permute(l) flatMap computeAllOperations filter (_._1 == 24) map (_._2)</syntaxhighlight>


Example:
Example:
Line 8,457: Line 8,457:
This version outputs an S-expression that will '''eval''' to 24 (rather than converting to infix notation).
This version outputs an S-expression that will '''eval''' to 24 (rather than converting to infix notation).


<lang scheme>
<syntaxhighlight lang=scheme>
#!r6rs
#!r6rs


Line 8,504: Line 8,504:
(filter evaluates-to-24
(filter evaluates-to-24
(map* tree (iota 6) ops ops ops perms))))
(map* tree (iota 6) ops ops ops perms))))
</syntaxhighlight>
</lang>


Example output:
Example output:
<lang scheme>
<syntaxhighlight lang=scheme>
> (solve 1 3 5 7)
> (solve 1 3 5 7)
((* (+ 1 5) (- 7 3))
((* (+ 1 5) (- 7 3))
Line 8,521: Line 8,521:
> (solve 3 4 9 10)
> (solve 3 4 9 10)
()
()
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
Line 8,527: Line 8,527:
'''With eval():'''
'''With eval():'''


<lang ruby>var formats = [
<syntaxhighlight lang=ruby>var formats = [
'((%d %s %d) %s %d) %s %d',
'((%d %s %d) %s %d) %s %d',
'(%d %s (%d %s %d)) %s %d',
'(%d %s (%d %s %d)) %s %d',
Line 8,559: Line 8,559:
}
}
}
}
}</lang>
}</syntaxhighlight>


'''Without eval():'''
'''Without eval():'''
<lang ruby>var formats = [
<syntaxhighlight lang=ruby>var formats = [
{|a,b,c|
{|a,b,c|
Hash(
Hash(
Line 8,619: Line 8,619:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 8,636: Line 8,636:


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BEGIN
<syntaxhighlight lang=simula>BEGIN




Line 8,933: Line 8,933:
OUTIMAGE;
OUTIMAGE;
END.
END.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 8,952: Line 8,952:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>
<syntaxhighlight lang=swift>
import Darwin
import Darwin
import Foundation
import Foundation
Line 9,124: Line 9,124:
} else {
} else {
println("Congratulations, you found a solution!")
println("Congratulations, you found a solution!")
}</lang>
}</syntaxhighlight>


{{out}}The program in action:
{{out}}The program in action:
Line 9,171: Line 9,171:
This is a complete Tcl script, intended to be invoked from the command line.
This is a complete Tcl script, intended to be invoked from the command line.
{{tcllib|struct::list}}
{{tcllib|struct::list}}
<lang tcl>package require struct::list
<syntaxhighlight lang=tcl>package require struct::list
# Encoding the various expression trees that are possible
# Encoding the various expression trees that are possible
set patterns {
set patterns {
Line 9,232: Line 9,232:
}
}
}
}
print24GameSolutionFor $argv</lang>
print24GameSolutionFor $argv</syntaxhighlight>
{{out}}
{{out}}
Demonstrating it in use:
Demonstrating it in use:
Line 9,253: Line 9,253:
non-terminal nodes of a tree in every possible way. The <code>value</code> function evaluates a tree and the
non-terminal nodes of a tree in every possible way. The <code>value</code> function evaluates a tree and the
<code>format</code> function displays it in a readable form.
<code>format</code> function displays it in a readable form.
<lang Ursala>#import std
<syntaxhighlight lang=Ursala>#import std
#import nat
#import nat
#import rat
#import rat
Line 9,263: Line 9,263:
format = *^ ~&v?\-+~&h,%zP@d+- ^H/mat@d *v ~&t?\~& :/`(+ --')'
format = *^ ~&v?\-+~&h,%zP@d+- ^H/mat@d *v ~&t?\~& :/`(+ --')'


game"n" "d" = format* value==("n",1)*~ with_roots/'+-*/' with_leaves/"d"*-1 tree_shapes length "d"</lang>
game"n" "d" = format* value==("n",1)*~ with_roots/'+-*/' with_leaves/"d"*-1 tree_shapes length "d"</syntaxhighlight>
test program:
test program:
<lang Ursala>#show+
<syntaxhighlight lang=Ursala>#show+


test_games = mat` * pad` *K7 pad0 game24* <<2,3,8,9>,<5,7,4,1>,<5,6,7,8>></lang>
test_games = mat` * pad` *K7 pad0 game24* <<2,3,8,9>,<5,7,4,1>,<5,6,7,8>></syntaxhighlight>
output:
output:
<pre>
<pre>
Line 9,303: Line 9,303:
{{trans|Kotlin}}
{{trans|Kotlin}}
{{libheader|Wren-dynamic}}
{{libheader|Wren-dynamic}}
<lang ecmascript>import "random" for Random
<syntaxhighlight lang=ecmascript>import "random" for Random
import "/dynamic" for Tuple, Enum, Struct
import "/dynamic" for Tuple, Enum, Struct


Line 9,397: Line 9,397:
System.write(": ")
System.write(": ")
System.print(solve24.call(n) ? "" : "No solution")
System.print(solve24.call(n) ? "" : "No solution")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 9,415: Line 9,415:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>operators$ = "*+-/"
<syntaxhighlight lang=Yabasic>operators$ = "*+-/"
space$ = " "
space$ = " "


Line 9,593: Line 9,593:
next n
next n
return true
return true
end sub</lang>
end sub</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
Line 9,599: Line 9,599:


File solve24.zkl:
File solve24.zkl:
<lang zkl>var [const] H=Utils.Helpers;
<syntaxhighlight lang=zkl>var [const] H=Utils.Helpers;
fcn u(xs){ xs.reduce(fcn(us,s){us.holds(s) and us or us.append(s) },L()) }
fcn u(xs){ xs.reduce(fcn(us,s){us.holds(s) and us or us.append(s) },L()) }
var ops=u(H.combosK(3,"+-*/".split("")).apply(H.permute).flatten());
var ops=u(H.combosK(3,"+-*/".split("")).apply(H.permute).flatten());
Line 9,624: Line 9,624:
catch(MathError){ False } };
catch(MathError){ False } };
{ f2s(digits4,ops3,f) }]];
{ f2s(digits4,ops3,f) }]];
}</lang>
}</syntaxhighlight>
<lang zkl>solutions:=u(game24Solver(ask(0,"digits: ")));
<syntaxhighlight lang=zkl>solutions:=u(game24Solver(ask(0,"digits: ")));
println(solutions.len()," solutions:");
println(solutions.len()," solutions:");
solutions.apply2(Console.println);</lang>
solutions.apply2(Console.println);</syntaxhighlight>
One trick used is to look at the solving functions name and use the digit in it to index into the formats list.
One trick used is to look at the solving functions name and use the digit in it to index into the formats list.
{{out}}
{{out}}