Jump to content

24 game/Solve: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 13:
{{trans|Nim}}
 
<langsyntaxhighlight lang=11l>[Char = ((Float, Float) -> Float)] op
op[Char(‘+’)] = (x, y) -> x + y
op[Char(‘-’)] = (x, y) -> x - y
Line 52:
[5, 7, 9, 7],
[3, 3, 8, 8]]
print(‘solve(’nums‘) -> ’solve(nums))</langsyntaxhighlight>
 
{{out}}
Line 71:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<langsyntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program game24Solvex64.s */
Line 502:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 526:
 
Note: the permute function was locally from [[Permutations#ABAP|here]]
<langsyntaxhighlight lang=ABAP>data: lv_flag type c,
lv_number type i,
lt_numbers type table of i.
Line 723:
modify iv_set index lv_perm from lv_temp_2.
modify iv_set index lv_len from lv_temp.
endform.</langsyntaxhighlight>
 
Sample Runs:
Line 1,016:
=={{header|Argile}}==
{{works with|Argile|1.0.0}}
<langsyntaxhighlight 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 \
Line 1,113:
(roperators[(rrop[rpn][2])]) (rdigits[3]);
return buffer as text
nil</langsyntaxhighlight>
Examples:
<pre>$ arc 24_game_solve.arg -o 24_game_solve.c
Line 1,127:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<langsyntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI */
/* program game24Solver.s */
Line 1,514:
.include "../affichage.inc"
 
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 1,543:
{{works with|AutoHotkey_L}}
Output is in RPN.
<langsyntaxhighlight lang=AHK>#NoEnv
InputBox, NNNN ; user input 4 digits
NNNN := RegExReplace(NNNN, "(\d)(?=\d)", "$1,") ; separate with commas for the sort command
Line 1,650:
o := A_LoopField o
return o
}</langsyntaxhighlight>
{{out}}for 1127:
<pre>
Line 1,665:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang=bbcbasic>
PROCsolve24("1234")
PROCsolve24("6789")
Line 1,722:
IF I% > 4 PRINT "No solution found"
ENDPROC
</syntaxhighlight>
</lang>
{{out}}
<pre>
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>
 
<langsyntaxhighlight lang=c>#include <stdio.h>
 
typedef struct {int val, op, left, right;} Node;
Line 1,820:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
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.
 
<langsyntaxhighlight lang=cpp>
#include <iostream>
#include <ratio>
Line 1,919:
return 0;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,975:
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}}
<langsyntaxhighlight lang=csharp>using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
Line 2,289:
$"{(wrapLeft ? $"({Left})" : $"{Left}")} {Symbol} {(wrapRight ? $"({Right})" : $"{Right}")}";
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,325:
=={{header|Ceylon}}==
Don't forget to import ceylon.random in your module.ceylon file.
<langsyntaxhighlight lang=ceylon>import ceylon.random {
DefaultRandom
}
Line 2,457:
expressions.each(print);
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang=Clojure>(ns rosettacode.24game.solve
(:require [clojure.math.combinatorics :as c]
[clojure.walk :as w]))
Line 2,484:
(map println)
doall
count))</langsyntaxhighlight>
 
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:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang=cobol> >>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This is GNUCobol 2.0
Line 2,935:
end-perform
.
end program twentyfoursolve.</langsyntaxhighlight>
 
{{out}}
Line 2,965:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang=coffeescript>
# This program tries to find some way to turn four digits into an arithmetic
# expression that adds up to 24.
Line 3,053:
solution = solve_24_game a, b, c, d
console.log "Solution for #{[a,b,c,d]}: #{solution ? 'no solution'}"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,076:
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang=lisp>(defconstant +ops+ '(* / + -))
 
(defun digits ()
Line 3,131:
digits which evaluates to 24. The first form found is returned, or
NIL if there is no solution."
(solvable-p digits))</langsyntaxhighlight>
 
{{out}}
Line 3,149:
This uses the Rational struct and permutations functions of two other Rosetta Code Tasks.
{{trans|Scala}}
<langsyntaxhighlight lang=d>import std.stdio, std.algorithm, std.range, std.conv, std.string,
std.concurrency, permutations2, arithmetic_rational;
 
Line 3,184:
foreach (const prob; [[6, 7, 9, 5], [3, 3, 8, 8], [1, 1, 1, 1]])
writeln(prob, ": ", solve(24, prob));
}</langsyntaxhighlight>
{{out}}
<pre>[6, 7, 9, 5]: (6+(9*(7-5)))
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.
 
<langsyntaxhighlight lang=scheme>
;; use task [[RPN_to_infix_conversion#EchoLisp]] to print results
(define (rpn->string rpn)
Line 3,305:
(writeln digits '→ target)
(try-rpn digits target))
</langsyntaxhighlight>
 
{{out}}
Line 3,352:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang=elixir>defmodule Game24 do
@expressions [ ["((", "", ")", "", ")", ""],
["(", "(", "", "", "))", ""],
Line 3,397:
IO.puts "found #{length(solutions)} solutions, including #{hd(solutions)}"
IO.inspect Enum.sort(solutions)
end</langsyntaxhighlight>
 
{{out}}
Line 3,418:
=={{header|ERRE}}==
ERRE hasn't an "EVAL" function so we must write an evaluation routine; this task is solved via "brute-force".
<langsyntaxhighlight lang=ERR>
PROGRAM 24SOLVE
 
Line 3,730:
 
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,753:
Via brute force.
 
<langsyntaxhighlight lang=Euler Math Toolbox>
>function try24 (v) ...
$n=cols(v);
Line 3,776:
$return 0;
$endfunction
</syntaxhighlight>
</lang>
 
<langsyntaxhighlight lang=Euler Math Toolbox>
>try24([1,2,3,4]);
Solved the problem
Line 3,799:
-1+5=4
3-4=-1
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
Line 3,805:
It eliminates all duplicate solutions which result from transposing equal digits.
The basic solution is an adaption of the OCaml program.
<langsyntaxhighlight 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)
Line 3,913:
|> Seq.groupBy id
|> Seq.iter (fun x -> printfn "%s" (fst x))
0</langsyntaxhighlight>
{{out}}
<pre>>solve24 3 3 3 4
Line 3,942:
=={{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.
<langsyntaxhighlight lang=factor>USING: continuations grouping io kernel math math.combinatorics
prettyprint quotations random sequences sequences.deep ;
IN: rosetta-code.24-game
Line 3,959:
print expressions [ [ 24= ] [ 2drop ] recover ] each ;
24-game</langsyntaxhighlight>
{{out}}
<pre>
Line 3,987:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang=Fortran>program solve_24
use helpers
implicit none
Line 4,055:
end function op
 
end program solve_24</langsyntaxhighlight>
 
<langsyntaxhighlight lang=Fortran>module helpers
 
contains
Line 4,128:
end subroutine nextpermutation
 
end module helpers</langsyntaxhighlight>
{{out}} (using g95):
<pre> 3 6 7 9 : 3 *(( 6 - 7 )+ 9 )
Line 4,145:
 
=={{header|GAP}}==
<langsyntaxhighlight lang=gap># Solution in '''RPN'''
check := function(x, y, z)
local r, c, s, i, j, k, a, b, p;
Line 4,228:
# A tricky one:
Player24([3,3,8,8]);
"8383/-/"</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang=go>package main
 
import (
Line 4,401:
}
}
}</langsyntaxhighlight>
{{out}}
<pre> 8 6 7 6: No solution
Line 4,416:
 
=={{header|Gosu}}==
<langsyntaxhighlight lang=Gosu>
uses java.lang.Integer
uses java.lang.Double
Line 4,527:
print( "No solution!" )
}
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight lang=haskell>import Data.List
import Data.Ratio
import Control.Monad
Line 4,580:
nub $ permutations $ map Constant r4
 
main = getArgs >>= mapM_ print . solve 24 . map (toEnum . read)</langsyntaxhighlight>
 
Example use:
Line 4,598:
(8 / (2 / (9 - 3)))</pre>
===Alternative version===
<langsyntaxhighlight lang=haskell>import Control.Applicative
import Data.List
import Text.PrettyPrint
Line 4,639:
 
main = mapM_ (putStrLn . render . toDoc) $ solve 24 [2,3,8,9]</langsyntaxhighlight>
{{out}}
<pre>((8 / 2) * (9 - 3))
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.
 
<langsyntaxhighlight lang=Icon>invocable all
link strings # for csort, deletec, permutes
 
Line 4,733:
suspend 2(="(", E(), =")") | # parenthesized subexpression, or ...
tab(any(&digits)) # just a value
end</langsyntaxhighlight>
 
 
Line 4,740:
 
=={{header|J}}==
<langsyntaxhighlight lang=J>perm=: (A.&i.~ !) 4
ops=: ' ',.'+-*%' {~ >,{i.each 4 4 4
cmask=: 1 + 0j1 * i.@{:@$@[ e. ]
Line 4,748:
parens=: ], 0 paren 3, 0 paren 5, 2 paren 5, [: 0 paren 7 (0 paren 3)
all=: [: parens [:,/ ops ,@,."1/ perm { [:;":each
answer=: ({.@#~ 24 = ".)@all</langsyntaxhighlight>
 
This implementation tests all 7680 candidate sentences.
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.
 
<langsyntaxhighlight lang=J>ops=: > , { 3#<'+-*%'
perms=: [: ":"0 [: ~. i.@!@# A. ]
build=: 1 : '(#~ 24 = ".) @: u'
Line 4,779:
if. 0 = #es do. es =. ([: ,/ [: ,/ ops combp"1 2/ perms) build y end.
es -."1 ' '
)</langsyntaxhighlight>
 
{{out}}
Line 4,800:
 
Note that this version does not extend to different digit ranges.
<langsyntaxhighlight lang=java>import java.util.*;
 
public class Game24Player {
Line 5,063:
res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));
}
}</langsyntaxhighlight>
 
{{out}}
Line 5,107:
=={{header|JavaScript}}==
This is a translation of the C code.
<langsyntaxhighlight lang=javascript>var ar=[],order=[0,1,2],op=[],val=[];
var NOVAL=9999,oper="+-*/",out;
 
Line 5,210:
solve24("1234");
solve24("6789");
solve24("1127");</langsyntaxhighlight>
 
Examples:
Line 5,224:
 
'''Infrastructure:'''
<langsyntaxhighlight lang=jq># Generate a stream of the permutations of the input array.
def permutations:
if length == 0 then []
Line 5,261:
| ($in[$i+1:] | triples) as $tail
| [$head, $in[$i], $tail]
end;</langsyntaxhighlight>
'''Evaluation and pretty-printing of allowed expressions'''
<langsyntaxhighlight lang=jq># Evaluate the input, which must be a number or a triple: [x, op, y]
def eval:
if type == "array" then
Line 5,285:
 
def pp:
"\(.)" | explode | map([.] | implode | if . == "," then " " elif . == "\"" then "" else . end) | join("");</langsyntaxhighlight>
 
'''24 Game''':
<langsyntaxhighlight lang=jq>def OPERATORS: ["+", "-", "*", "/"];
 
# Input: an array of 4 digits
Line 5,308:
;
 
solve(24), "Please try again."</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang=sh>$ jq -r -f Solve.jq
[1,2,3,4]
That was too easy. I found 242 answers, e.g. [4 * [1 + [2 + 3]]]
Line 5,325:
[1,2,3,4,5,6]
That was too easy. I found 197926 answers, e.g. [[2 * [1 + 4]] + [3 + [5 + 6]]]
Please try again.</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang=julia>function solve24(nums)
length(nums) != 4 && error("Input must be a 4-element Array")
syms = [+,-,*,/]
Line 5,348:
end
return "0"
end</langsyntaxhighlight>
{{out}}
<pre>julia> for i in 1:10
Line 5,367:
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang=scala>// version 1.1.3
 
import java.util.Random
Line 5,465:
println(if (solve24(n)) "" else "No solution")
}
}</langsyntaxhighlight>
 
Sample output:
Line 5,482:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang=lb>dim d(4)
input "Enter 4 digits: "; a$
nD=0
Line 5,604:
exit function
[handler]
end function</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 5,610:
Generic solver: pass card of any size with 1st argument and target number with second.
 
<langsyntaxhighlight lang=lua>
local SIZE = #arg[1]
local GOAL = tonumber(arg[2]) or 24
Line 5,685:
 
permgen(input, SIZE)
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,725:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The code:
<langsyntaxhighlight lang=Mathematica>
treeR[n_] := Table[o[trees[a], trees[n - a]], {a, 1, n - 1}]
treeR[1] := n
Line 5,741:
Permutations[Array[v, 4]], 1]],
Quiet[(# /. v[q_] :> val[[q]]) == 24] &] /.
Table[v[q] -> val[[q]], {q, 4}])]</langsyntaxhighlight>
 
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:
**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:
 
<langsyntaxhighlight lang=Mathematica>game24play[RandomInteger[{1, 9}, 4]]</langsyntaxhighlight>
 
{{out}}
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.
 
<langsyntaxhighlight lang=Mathematica>evaluate[HoldForm[op_[l_, r_]]] := op[evaluate[l], evaluate[r]];
evaluate[x_] := x;
combine[l_, r_ /; evaluate[r] != 0] := {HoldForm[Plus[l, r]],
Line 5,834:
solveMaintainOrder[1/5, Range[2, 5]]
solveCanPermute[1/5, Range[2, 5]]
solveSubsets[1/5, Range[2, 5]]</langsyntaxhighlight>
 
=={{header|Nim}}==
Line 5,841:
{{works with|Nim Compiler|0.19.4}}
 
<langsyntaxhighlight lang=nim>import algorithm, sequtils, strformat
 
type
Line 5,896:
echo fmt"solve({nums}) -> {solve(nums)}"
 
when isMainModule: main()</langsyntaxhighlight>
 
{{out}}
Line 5,915:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang=ocaml>type expression =
| Const of float
| Sum of expression * expression (* e1 + e2 *)
Line 5,984:
| x::xs -> comp x xs
| [] -> assert false
) all</langsyntaxhighlight>
 
<pre>
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]
<langsyntaxhighlight lang=Perl># Fischer-Krause ordered permutation generator
# http://faq.perl.org/perlfaq4.html#How_do_I_permute_N_e
sub permute (&@) {
Line 6,053:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>E:\Temp>24solve.pl
Line 6,082:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<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>
Line 6,198:
--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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 6,214:
 
=={{header|Picat}}==
<langsyntaxhighlight lang=Picat>main =>
foreach (_ in 1..10)
Nums = [D : _ in 1..4, D = random() mod 9 + 1],
Line 6,233:
Exp3 =.. [Op,Exp1,Exp2],
solve([(Num3,Exp3)|NumExps2]).
</syntaxhighlight>
</lang>
 
{{trans|Raku}}
<langsyntaxhighlight lang=Picat>import util.
 
main =>
Line 6,279:
R := replace(R, F,T.to_string())
end,
Res = R.</langsyntaxhighlight>
 
{{out}}
Line 6,313:
Another approach:
 
<langsyntaxhighlight lang=Picat>import util.
 
main =>
Line 6,358:
check(A,X,B,Y,C,Z,D,Target,Expr) =>
Expr = [A,X,"(","(",B,Y,C,")", Z,D,")"].to_string2(),
Target =:= Expr.eval().</langsyntaxhighlight>
 
{{out}}
Line 6,383:
=={{header|PicoLisp}}==
We use Pilog (PicoLisp Prolog) to solve this task
<langsyntaxhighlight lang=PicoLisp>(be play24 (@Lst @Expr) # Define Pilog rule
(permute @Lst (@A @B @C @D))
(member @Op1 (+ - * /))
Line 6,400:
(println @X) ) )
 
(play24 5 6 7 8) # Call 'play24' function</langsyntaxhighlight>
{{out}}
<pre>(* (+ 5 7) (- 8 6))
Line 6,419:
Note
This example uses the math module:
<langsyntaxhighlight lang=ProDOS>editvar /modify -random- = <10
:a
editvar /newvar /withothervar /value=-random- /title=1
Line 6,453:
printline you could have done it by doing -c-
stoptask
goto :b</langsyntaxhighlight>
 
{{out}}
Line 6,474:
rdiv/2 is use instead of //2 to enable the program to solve difficult cases as [3 3 8 8].
 
<langsyntaxhighlight lang=Prolog>play24(Len, Range, Goal) :-
game(Len, Range, Goal, L, S),
maplist(my_write, L),
Line 6,564:
 
my_write(V) :-
format('~w ', [V]).</langsyntaxhighlight>
{{out}}
<pre>?- play24(4,9, 24).
Line 6,624:
{{Works with|GNU Prolog|1.4.4}}
Little efforts to remove duplicates (e.g. output for [4,6,9,9]).
<langsyntaxhighlight lang=prolog>:- initialization(main).
 
solve(N,Xs,Ast) :-
Line 6,645:
 
test(T) :- solve(24, [2,3,8,9], T).
main :- forall(test(T), (write(T), nl)), halt.</langsyntaxhighlight>
{{Output}}
<pre>(9-3)*8//2
Line 6,665:
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.
<langsyntaxhighlight lang=Python>'''
The 24 Game Player
Line 6,823:
print ("Thank you and goodbye")
main()</langsyntaxhighlight>
 
{{out}}
Line 6,877:
==={{header|Python}} Succinct===
Based on the Julia example above.
<langsyntaxhighlight lang=python># -*- coding: utf-8 -*-
import operator
from itertools import product, permutations
Line 6,915:
[3,3,8,8], # Difficult case requiring precise division
]:
print(f"solve24({nums}) -> {solve24(nums)}")</langsyntaxhighlight>
 
{{out}}
Line 6,932:
==={{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.
<langsyntaxhighlight lang=python># -*- coding: utf-8 -*-
# Python 3
from operator import mul, sub, add
Line 6,976:
except StopIteration:
print("No solution found")
</syntaxhighlight>
</lang>
 
{{out}}
Line 6,993:
===Python: using tkinter===
 
<langsyntaxhighlight lang=python>
''' Python 3.6.5 code using Tkinter graphical user interface.
Combination of '24 game' and '24 game/Solve'
Line 7,353:
g = Game(root)
root.mainloop()
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
Line 7,359:
<code>permutations</code> is defined at [[Permutations#Quackery]] and <code>uniquewith</code> is defined at [[Remove duplicate elements#Quackery]].
 
<langsyntaxhighlight lang=Quackery> [ ' [ 0 1 2 3 ]
permutations ] constant is numorders ( --> [ )
 
Line 7,422:
unbuild
2 split nip
-2 split drop nest$ 90 wrap$ ] is solve ( n n n n --> )</langsyntaxhighlight>
 
{{out}}
Line 7,452:
=={{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.
<syntaxhighlight lang=r>
<lang r>
library(gtools)
 
Line 7,487:
return(NA)
}
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang=r>
<lang r>
> solve24()
8 * (4 - 2 + 1)
Line 7,502:
> solve24(ops=c('-', '/')) #restricted set of operators
(8 - 2)/(1/4)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
The sequence of all possible variants of expressions with given numbers ''n1, n2, n3, n4'' and operations ''o1, o2, o3''.
<langsyntaxhighlight lang=racket>
(define (in-variants n1 o1 n2 o2 n3 o3 n4)
(let ([o1n (object-name o1)]
Line 7,523:
`(,n1 ,o1n ((,n2 ,o3n ,n3) ,o2n ,n4))
`(,n1 ,o1n (,n2 ,o2n (,n3 ,o3n ,n4))))))))
</syntaxhighlight>
</lang>
 
Search for all solutions using brute force:
<langsyntaxhighlight lang=racket>
(define (find-solutions numbers (goal 24))
(define in-operations (list + - * /))
Line 7,542:
 
(define (remove-from numbers . n) (foldr remq numbers n))
</syntaxhighlight>
</lang>
 
Examples:
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>
 
<langsyntaxhighlight lang=perl6>use MONKEY-SEE-NO-EVAL;
 
my @digits;
Line 7,616:
my %h = map { $_.Str => $_ }, @array;
%h.values;
}</langsyntaxhighlight>
 
{{out}}
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.
 
<langsyntaxhighlight lang=perl6>my %*SUB-MAIN-OPTS = :named-anywhere;
 
sub MAIN (*@parameters, Int :$goal = 24) {
Line 7,757:
demo and will show this message.\e[0m
========================================================================
}</langsyntaxhighlight>
{{out}}
When supplied 1399 on the command line:
Line 7,771:
 
=={{header|REXX}}==
<langsyntaxhighlight lang=rexx>/*REXX program helps the user find solutions to the game of 24. */
/* start-of-help
┌───────────────────────────────────────────────────────────────────────┐
Line 8,033:
ger: say= '***error*** for argument:' y; say arg(1); errCode= 1; return 0
p: return word( arg(1), 1)
s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1)</langsyntaxhighlight>
Some older REXXes don't have a &nbsp; '''changestr''' &nbsp; BIF, so one is included here ──► &nbsp; &nbsp; [[CHANGESTR.REX]].
<br><br>
Line 8,146:
{{trans|Tcl}}
{{works with|Ruby|2.1}}
<langsyntaxhighlight lang=ruby>class TwentyFourGame
EXPRESSIONS = [
'((%dr %s %dr) %s %dr) %s %dr',
Line 8,186:
puts "found #{solutions.size} solutions, including #{solutions.first}"
puts solutions.sort
end</langsyntaxhighlight>
 
{{out}}
Line 8,220:
=={{header|Rust}}==
{{works with|Rust|1.17}}
<langsyntaxhighlight lang=rust>#[derive(Clone, Copy, Debug)]
enum Operator {
Sub,
Line 8,385:
[numbers[order[0]], numbers[order[1]], numbers[order[2]], numbers[order[3]]]
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 8,399:
A non-interactive player.
 
<langsyntaxhighlight lang=scala>def permute(l: List[Double]): List[List[Double]] = l match {
case Nil => List(Nil)
case x :: xs =>
Line 8,423:
}
 
def hasSolution(l: List[Double]) = permute(l) flatMap computeAllOperations filter (_._1 == 24) map (_._2)</langsyntaxhighlight>
 
Example:
Line 8,457:
This version outputs an S-expression that will '''eval''' to 24 (rather than converting to infix notation).
 
<langsyntaxhighlight lang=scheme>
#!r6rs
 
Line 8,504:
(filter evaluates-to-24
(map* tree (iota 6) ops ops ops perms))))
</syntaxhighlight>
</lang>
 
Example output:
<langsyntaxhighlight lang=scheme>
> (solve 1 3 5 7)
((* (+ 1 5) (- 7 3))
Line 8,521:
> (solve 3 4 9 10)
()
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
Line 8,527:
'''With eval():'''
 
<langsyntaxhighlight lang=ruby>var formats = [
'((%d %s %d) %s %d) %s %d',
'(%d %s (%d %s %d)) %s %d',
Line 8,559:
}
}
}</langsyntaxhighlight>
 
'''Without eval():'''
<langsyntaxhighlight lang=ruby>var formats = [
{|a,b,c|
Hash(
Line 8,619:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 8,636:
 
=={{header|Simula}}==
<langsyntaxhighlight lang=simula>BEGIN
 
 
Line 8,933:
OUTIMAGE;
END.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 8,952:
=={{header|Swift}}==
 
<langsyntaxhighlight lang=swift>
import Darwin
import Foundation
Line 9,124:
} else {
println("Congratulations, you found a solution!")
}</langsyntaxhighlight>
 
{{out}}The program in action:
Line 9,171:
This is a complete Tcl script, intended to be invoked from the command line.
{{tcllib|struct::list}}
<langsyntaxhighlight lang=tcl>package require struct::list
# Encoding the various expression trees that are possible
set patterns {
Line 9,232:
}
}
print24GameSolutionFor $argv</langsyntaxhighlight>
{{out}}
Demonstrating it in use:
Line 9,253:
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.
<langsyntaxhighlight lang=Ursala>#import std
#import nat
#import rat
Line 9,263:
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"</langsyntaxhighlight>
test program:
<langsyntaxhighlight lang=Ursala>#show+
 
test_games = mat` * pad` *K7 pad0 game24* <<2,3,8,9>,<5,7,4,1>,<5,6,7,8>></langsyntaxhighlight>
output:
<pre>
Line 9,303:
{{trans|Kotlin}}
{{libheader|Wren-dynamic}}
<langsyntaxhighlight lang=ecmascript>import "random" for Random
import "/dynamic" for Tuple, Enum, Struct
 
Line 9,397:
System.write(": ")
System.print(solve24.call(n) ? "" : "No solution")
}</langsyntaxhighlight>
 
{{out}}
Line 9,415:
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang=Yabasic>operators$ = "*+-/"
space$ = " "
 
Line 9,593:
next n
return true
end sub</langsyntaxhighlight>
 
=={{header|zkl}}==
Line 9,599:
 
File solve24.zkl:
<langsyntaxhighlight 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()) }
var ops=u(H.combosK(3,"+-*/".split("")).apply(H.permute).flatten());
Line 9,624:
catch(MathError){ False } };
{ f2s(digits4,ops3,f) }]];
}</langsyntaxhighlight>
<langsyntaxhighlight lang=zkl>solutions:=u(game24Solver(ask(0,"digits: ")));
println(solutions.len()," solutions:");
solutions.apply2(Console.println);</langsyntaxhighlight>
One trick used is to look at the solving functions name and use the digit in it to index into the formats list.
{{out}}
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.