24 game/Solve: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 13: Line 13:
{{trans|Nim}}
{{trans|Nim}}


<syntaxhighlight 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 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}}
<syntaxhighlight 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 526: Line 526:


Note: the permute function was locally from [[Permutations#ABAP|here]]
Note: the permute function was locally from [[Permutations#ABAP|here]]
<syntaxhighlight 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 1,016: Line 1,016:
=={{header|Argile}}==
=={{header|Argile}}==
{{works with|Argile|1.0.0}}
{{works with|Argile|1.0.0}}
<syntaxhighlight 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,127: Line 1,127:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM Assembly>
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program game24Solver.s */
/* program game24Solver.s */
Line 1,543: Line 1,543:
{{works with|AutoHotkey_L}}
{{works with|AutoHotkey_L}}
Output is in RPN.
Output is in RPN.
<syntaxhighlight 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,665: Line 1,665:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<syntaxhighlight lang=bbcbasic>
<syntaxhighlight lang="bbcbasic">
PROCsolve24("1234")
PROCsolve24("1234")
PROCsolve24("6789")
PROCsolve24("6789")
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>


<syntaxhighlight 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,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.


<syntaxhighlight lang=cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include <ratio>
#include <ratio>
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}}
<syntaxhighlight 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,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.
<syntaxhighlight lang=ceylon>import ceylon.random {
<syntaxhighlight lang="ceylon">import ceylon.random {
DefaultRandom
DefaultRandom
}
}
Line 2,460: Line 2,460:


=={{header|Clojure}}==
=={{header|Clojure}}==
<syntaxhighlight 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,490: Line 2,490:


=={{header|COBOL}}==
=={{header|COBOL}}==
<syntaxhighlight 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,965: Line 2,965:


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<syntaxhighlight 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,076: Line 3,076:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


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


(defun digits ()
(defun digits ()
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}}
<syntaxhighlight 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,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.


<syntaxhighlight 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,352: Line 3,352:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Ruby}}
{{trans|Ruby}}
<syntaxhighlight lang=elixir>defmodule Game24 do
<syntaxhighlight lang="elixir">defmodule Game24 do
@expressions [ ["((", "", ")", "", ")", ""],
@expressions [ ["((", "", ")", "", ")", ""],
["(", "(", "", "", "))", ""],
["(", "(", "", "", "))", ""],
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".
<syntaxhighlight lang=ERR>
<syntaxhighlight lang="err">
PROGRAM 24SOLVE
PROGRAM 24SOLVE


Line 3,753: Line 3,753:
Via brute force.
Via brute force.


<syntaxhighlight lang=Euler Math Toolbox>
<syntaxhighlight lang="euler math toolbox">
>function try24 (v) ...
>function try24 (v) ...
$n=cols(v);
$n=cols(v);
Line 3,778: Line 3,778:
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight 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,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.
<syntaxhighlight 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,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.
<syntaxhighlight 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,987: Line 3,987:


=={{header|Fortran}}==
=={{header|Fortran}}==
<syntaxhighlight lang=Fortran>program solve_24
<syntaxhighlight lang="fortran">program solve_24
use helpers
use helpers
implicit none
implicit none
Line 4,057: Line 4,057:
end program solve_24</syntaxhighlight>
end program solve_24</syntaxhighlight>


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


contains
contains
Line 4,145: Line 4,145:


=={{header|GAP}}==
=={{header|GAP}}==
<syntaxhighlight 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,231: Line 4,231:


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


import (
import (
Line 4,416: Line 4,416:


=={{header|Gosu}}==
=={{header|Gosu}}==
<syntaxhighlight lang=Gosu>
<syntaxhighlight lang="gosu">
uses java.lang.Integer
uses java.lang.Integer
uses java.lang.Double
uses java.lang.Double
Line 4,531: Line 4,531:
=={{header|Haskell}}==
=={{header|Haskell}}==


<syntaxhighlight 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,598: Line 4,598:
(8 / (2 / (9 - 3)))</pre>
(8 / (2 / (9 - 3)))</pre>
===Alternative version===
===Alternative version===
<syntaxhighlight 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,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.


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


Line 4,740: Line 4,740:


=={{header|J}}==
=={{header|J}}==
<syntaxhighlight 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,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.


<syntaxhighlight 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,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.
<syntaxhighlight lang=java>import java.util.*;
<syntaxhighlight lang="java">import java.util.*;


public class Game24Player {
public class Game24Player {
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.
<syntaxhighlight 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,224: Line 5,224:


'''Infrastructure:'''
'''Infrastructure:'''
<syntaxhighlight 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,263: Line 5,263:
end;</syntaxhighlight>
end;</syntaxhighlight>
'''Evaluation and pretty-printing of allowed expressions'''
'''Evaluation and pretty-printing of allowed expressions'''
<syntaxhighlight 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,288: Line 5,288:


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


# Input: an array of 4 digits
# Input: an array of 4 digits
Line 5,310: Line 5,310:
solve(24), "Please try again."</syntaxhighlight>
solve(24), "Please try again."</syntaxhighlight>
{{out}}
{{out}}
<syntaxhighlight 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,330: Line 5,330:


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.
<syntaxhighlight 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,367: Line 5,367:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|C}}
{{trans|C}}
<syntaxhighlight lang=scala>// version 1.1.3
<syntaxhighlight lang="scala">// version 1.1.3


import java.util.Random
import java.util.Random
Line 5,482: Line 5,482:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight 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,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.


<syntaxhighlight 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,725: Line 5,725:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The code:
The code:
<syntaxhighlight 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,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:


<syntaxhighlight lang=Mathematica>game24play[RandomInteger[{1, 9}, 4]]</syntaxhighlight>
<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.


<syntaxhighlight 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,841: Line 5,841:
{{works with|Nim Compiler|0.19.4}}
{{works with|Nim Compiler|0.19.4}}


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


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


<syntaxhighlight 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 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]
<syntaxhighlight 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,082: Line 6,082:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight 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,214: Line 6,214:


=={{header|Picat}}==
=={{header|Picat}}==
<syntaxhighlight 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,236: Line 6,236:


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


main =>
main =>
Line 6,313: Line 6,313:
Another approach:
Another approach:


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


main =>
main =>
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
<syntaxhighlight 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,419: Line 6,419:
Note
Note
This example uses the math module:
This example uses the math module:
<syntaxhighlight 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,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].


<syntaxhighlight 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,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]).
<syntaxhighlight lang=prolog>:- initialization(main).
<syntaxhighlight lang="prolog">:- initialization(main).


solve(N,Xs,Ast) :-
solve(N,Xs,Ast) :-
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.
<syntaxhighlight lang=Python>'''
<syntaxhighlight lang="python">'''
The 24 Game Player
The 24 Game Player
Line 6,877: Line 6,877:
==={{header|Python}} Succinct===
==={{header|Python}} Succinct===
Based on the Julia example above.
Based on the Julia example above.
<syntaxhighlight 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,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.
<syntaxhighlight 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,993: Line 6,993:
===Python: using tkinter===
===Python: using tkinter===


<syntaxhighlight 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,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]].


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


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>
<syntaxhighlight lang="r">
library(gtools)
library(gtools)


Line 7,489: Line 7,489:
</syntaxhighlight>
</syntaxhighlight>
{{out}}
{{out}}
<syntaxhighlight lang=r>
<syntaxhighlight lang="r">
> solve24()
> solve24()
8 * (4 - 2 + 1)
8 * (4 - 2 + 1)
Line 7,506: Line 7,506:
=={{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''.
<syntaxhighlight 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,526: Line 7,526:


Search for all solutions using brute force:
Search for all solutions using brute force:
<syntaxhighlight 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,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>


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


my @digits;
my @digits;
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.


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


sub MAIN (*@parameters, Int :$goal = 24) {
sub MAIN (*@parameters, Int :$goal = 24) {
Line 7,771: Line 7,771:


=={{header|REXX}}==
=={{header|REXX}}==
<syntaxhighlight 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,146: Line 8,146:
{{trans|Tcl}}
{{trans|Tcl}}
{{works with|Ruby|2.1}}
{{works with|Ruby|2.1}}
<syntaxhighlight 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,220: Line 8,220:
=={{header|Rust}}==
=={{header|Rust}}==
{{works with|Rust|1.17}}
{{works with|Rust|1.17}}
<syntaxhighlight lang=rust>#[derive(Clone, Copy, Debug)]
<syntaxhighlight lang="rust">#[derive(Clone, Copy, Debug)]
enum Operator {
enum Operator {
Sub,
Sub,
Line 8,399: Line 8,399:
A non-interactive player.
A non-interactive player.


<syntaxhighlight 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,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).


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


Line 8,507: Line 8,507:


Example output:
Example output:
<syntaxhighlight 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,527: Line 8,527:
'''With eval():'''
'''With eval():'''


<syntaxhighlight 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,562: Line 8,562:


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


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




Line 8,952: Line 8,952:
=={{header|Swift}}==
=={{header|Swift}}==


<syntaxhighlight lang=swift>
<syntaxhighlight lang="swift">
import Darwin
import Darwin
import Foundation
import Foundation
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}}
<syntaxhighlight 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,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.
<syntaxhighlight lang=Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat
#import rat
#import rat
Line 9,265: Line 9,265:
game"n" "d" = format* value==("n",1)*~ with_roots/'+-*/' with_leaves/"d"*-1 tree_shapes length "d"</syntaxhighlight>
game"n" "d" = format* value==("n",1)*~ with_roots/'+-*/' with_leaves/"d"*-1 tree_shapes length "d"</syntaxhighlight>
test program:
test program:
<syntaxhighlight 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>></syntaxhighlight>
test_games = mat` * pad` *K7 pad0 game24* <<2,3,8,9>,<5,7,4,1>,<5,6,7,8>></syntaxhighlight>
Line 9,303: Line 9,303:
{{trans|Kotlin}}
{{trans|Kotlin}}
{{libheader|Wren-dynamic}}
{{libheader|Wren-dynamic}}
<syntaxhighlight 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,415: Line 9,415:


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


Line 9,599: Line 9,599:


File solve24.zkl:
File solve24.zkl:
<syntaxhighlight 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,625: Line 9,625:
{ f2s(digits4,ops3,f) }]];
{ f2s(digits4,ops3,f) }]];
}</syntaxhighlight>
}</syntaxhighlight>
<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);</syntaxhighlight>
solutions.apply2(Console.println);</syntaxhighlight>
Line 9,652: Line 9,652:
...
...
</pre>
</pre>

[[Category:Puzzles]]


{{omit from|GUISS}}
{{omit from|GUISS}}
{{omit from|ML/I}}
{{omit from|ML/I}}

[[Category:Puzzles]]