24 game/Solve: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 13:
{{trans|Nim}}
 
<syntaxhighlight lang="11l">[Char = ((Float, Float) -> Float)] op
op[Char(‘+’)] = (x, y) -> x + y
op[Char(‘-’)] = (x, y) -> x - y
Line 71:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program game24Solvex64.s */
Line 526:
 
Note: the permute function was locally from [[Permutations#ABAP|here]]
<syntaxhighlight lang=ABAP"abap">data: lv_flag type c,
lv_number type i,
lt_numbers type table of i.
Line 1,016:
=={{header|Argile}}==
{{works with|Argile|1.0.0}}
<syntaxhighlight lang=Argile"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,127:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
/* ARM assembly Raspberry PI */
/* program game24Solver.s */
Line 1,543:
{{works with|AutoHotkey_L}}
Output is in RPN.
<syntaxhighlight lang=AHK"ahk">#NoEnv
InputBox, NNNN ; user input 4 digits
NNNN := RegExReplace(NNNN, "(\d)(?=\d)", "$1,") ; separate with commas for the sort command
Line 1,665:
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic">
PROCsolve24("1234")
PROCsolve24("6789")
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>
 
<syntaxhighlight lang="c">#include <stdio.h>
 
typedef struct {int val, op, left, right;} Node;
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.
 
<syntaxhighlight lang="cpp">
#include <iostream>
#include <ratio>
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}}
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
Line 2,325:
=={{header|Ceylon}}==
Don't forget to import ceylon.random in your module.ceylon file.
<syntaxhighlight lang="ceylon">import ceylon.random {
DefaultRandom
}
Line 2,460:
 
=={{header|Clojure}}==
<syntaxhighlight lang=Clojure"clojure">(ns rosettacode.24game.solve
(:require [clojure.math.combinatorics :as c]
[clojure.walk :as w]))
Line 2,490:
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> >>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This is GNUCobol 2.0
Line 2,965:
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">
# This program tries to find some way to turn four digits into an arithmetic
# expression that adds up to 24.
Line 3,076:
=={{header|Common Lisp}}==
 
<syntaxhighlight lang="lisp">(defconstant +ops+ '(* / + -))
 
(defun digits ()
Line 3,149:
This uses the Rational struct and permutations functions of two other Rosetta Code Tasks.
{{trans|Scala}}
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.conv, std.string,
std.concurrency, permutations2, arithmetic_rational;
 
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.
 
<syntaxhighlight lang="scheme">
;; use task [[RPN_to_infix_conversion#EchoLisp]] to print results
(define (rpn->string rpn)
Line 3,352:
=={{header|Elixir}}==
{{trans|Ruby}}
<syntaxhighlight lang="elixir">defmodule Game24 do
@expressions [ ["((", "", ")", "", ")", ""],
["(", "(", "", "", "))", ""],
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".
<syntaxhighlight lang=ERR"err">
PROGRAM 24SOLVE
 
Line 3,753:
Via brute force.
 
<syntaxhighlight lang=Euler"euler Mathmath Toolboxtoolbox">
>function try24 (v) ...
$n=cols(v);
Line 3,778:
</syntaxhighlight>
 
<syntaxhighlight lang=Euler"euler Mathmath Toolboxtoolbox">
>try24([1,2,3,4]);
Solved the problem
Line 3,805:
It eliminates all duplicate solutions which result from transposing equal digits.
The basic solution is an adaption of the OCaml program.
<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)
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.
<syntaxhighlight lang="factor">USING: continuations grouping io kernel math math.combinatorics
prettyprint quotations random sequences sequences.deep ;
IN: rosetta-code.24-game
Line 3,987:
 
=={{header|Fortran}}==
<syntaxhighlight lang=Fortran"fortran">program solve_24
use helpers
implicit none
Line 4,057:
end program solve_24</syntaxhighlight>
 
<syntaxhighlight lang=Fortran"fortran">module helpers
 
contains
Line 4,145:
 
=={{header|GAP}}==
<syntaxhighlight lang="gap"># Solution in '''RPN'''
check := function(x, y, z)
local r, c, s, i, j, k, a, b, p;
Line 4,231:
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import (
Line 4,416:
 
=={{header|Gosu}}==
<syntaxhighlight lang=Gosu"gosu">
uses java.lang.Integer
uses java.lang.Double
Line 4,531:
=={{header|Haskell}}==
 
<syntaxhighlight lang="haskell">import Data.List
import Data.Ratio
import Control.Monad
Line 4,598:
(8 / (2 / (9 - 3)))</pre>
===Alternative version===
<syntaxhighlight lang="haskell">import Control.Applicative
import Data.List
import Text.PrettyPrint
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.
 
<syntaxhighlight lang=Icon"icon">invocable all
link strings # for csort, deletec, permutes
 
Line 4,740:
 
=={{header|J}}==
<syntaxhighlight lang=J"j">perm=: (A.&i.~ !) 4
ops=: ' ',.'+-*%' {~ >,{i.each 4 4 4
cmask=: 1 + 0j1 * i.@{:@$@[ e. ]
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.
 
<syntaxhighlight lang=J"j">ops=: > , { 3#<'+-*%'
perms=: [: ":"0 [: ~. i.@!@# A. ]
build=: 1 : '(#~ 24 = ".) @: u'
Line 4,800:
 
Note that this version does not extend to different digit ranges.
<syntaxhighlight lang="java">import java.util.*;
 
public class Game24Player {
Line 5,107:
=={{header|JavaScript}}==
This is a translation of the C code.
<syntaxhighlight lang="javascript">var ar=[],order=[0,1,2],op=[],val=[];
var NOVAL=9999,oper="+-*/",out;
 
Line 5,224:
 
'''Infrastructure:'''
<syntaxhighlight lang="jq"># Generate a stream of the permutations of the input array.
def permutations:
if length == 0 then []
Line 5,263:
end;</syntaxhighlight>
'''Evaluation and pretty-printing of allowed expressions'''
<syntaxhighlight lang="jq"># Evaluate the input, which must be a number or a triple: [x, op, y]
def eval:
if type == "array" then
Line 5,288:
 
'''24 Game''':
<syntaxhighlight lang="jq">def OPERATORS: ["+", "-", "*", "/"];
 
# Input: an array of 4 digits
Line 5,310:
solve(24), "Please try again."</syntaxhighlight>
{{out}}
<syntaxhighlight 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,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.
<syntaxhighlight lang="julia">function solve24(nums)
length(nums) != 4 && error("Input must be a 4-element Array")
syms = [+,-,*,/]
Line 5,367:
=={{header|Kotlin}}==
{{trans|C}}
<syntaxhighlight lang="scala">// version 1.1.3
 
import java.util.Random
Line 5,482:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">dim d(4)
input "Enter 4 digits: "; a$
nD=0
Line 5,610:
Generic solver: pass card of any size with 1st argument and target number with second.
 
<syntaxhighlight lang="lua">
local SIZE = #arg[1]
local GOAL = tonumber(arg[2]) or 24
Line 5,725:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The code:
<syntaxhighlight lang=Mathematica"mathematica">
treeR[n_] := Table[o[trees[a], trees[n - a]], {a, 1, n - 1}]
treeR[1] := n
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:
 
<syntaxhighlight lang=Mathematica"mathematica">game24play[RandomInteger[{1, 9}, 4]]</syntaxhighlight>
 
{{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.
 
<syntaxhighlight lang=Mathematica"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,841:
{{works with|Nim Compiler|0.19.4}}
 
<syntaxhighlight lang="nim">import algorithm, sequtils, strformat
 
type
Line 5,915:
=={{header|OCaml}}==
 
<syntaxhighlight lang="ocaml">type expression =
| Const of float
| Sum of expression * expression (* e1 + e2 *)
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]
<syntaxhighlight lang=Perl"perl"># Fischer-Krause ordered permutation generator
# http://faq.perl.org/perlfaq4.html#How_do_I_permute_N_e
sub permute (&@) {
Line 6,082:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang=Phix"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,214:
 
=={{header|Picat}}==
<syntaxhighlight lang=Picat"picat">main =>
foreach (_ in 1..10)
Nums = [D : _ in 1..4, D = random() mod 9 + 1],
Line 6,236:
 
{{trans|Raku}}
<syntaxhighlight lang=Picat"picat">import util.
 
main =>
Line 6,313:
Another approach:
 
<syntaxhighlight lang=Picat"picat">import util.
 
main =>
Line 6,383:
=={{header|PicoLisp}}==
We use Pilog (PicoLisp Prolog) to solve this task
<syntaxhighlight lang=PicoLisp"picolisp">(be play24 (@Lst @Expr) # Define Pilog rule
(permute @Lst (@A @B @C @D))
(member @Op1 (+ - * /))
Line 6,419:
Note
This example uses the math module:
<syntaxhighlight lang=ProDOS"prodos">editvar /modify -random- = <10
:a
editvar /newvar /withothervar /value=-random- /title=1
Line 6,474:
rdiv/2 is use instead of //2 to enable the program to solve difficult cases as [3 3 8 8].
 
<syntaxhighlight lang=Prolog"prolog">play24(Len, Range, Goal) :-
game(Len, Range, Goal, L, S),
maplist(my_write, L),
Line 6,624:
{{Works with|GNU Prolog|1.4.4}}
Little efforts to remove duplicates (e.g. output for [4,6,9,9]).
<syntaxhighlight lang="prolog">:- initialization(main).
 
solve(N,Xs,Ast) :-
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.
<syntaxhighlight lang=Python"python">'''
The 24 Game Player
Line 6,877:
==={{header|Python}} Succinct===
Based on the Julia example above.
<syntaxhighlight lang="python"># -*- coding: utf-8 -*-
import operator
from itertools import product, permutations
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.
<syntaxhighlight lang="python"># -*- coding: utf-8 -*-
# Python 3
from operator import mul, sub, add
Line 6,993:
===Python: using tkinter===
 
<syntaxhighlight lang="python">
''' Python 3.6.5 code using Tkinter graphical user interface.
Combination of '24 game' and '24 game/Solve'
Line 7,359:
<code>permutations</code> is defined at [[Permutations#Quackery]] and <code>uniquewith</code> is defined at [[Remove duplicate elements#Quackery]].
 
<syntaxhighlight lang=Quackery"quackery"> [ ' [ 0 1 2 3 ]
permutations ] constant is numorders ( --> [ )
 
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">
library(gtools)
 
Line 7,489:
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="r">
> solve24()
8 * (4 - 2 + 1)
Line 7,506:
=={{header|Racket}}==
The sequence of all possible variants of expressions with given numbers ''n1, n2, n3, n4'' and operations ''o1, o2, o3''.
<syntaxhighlight lang="racket">
(define (in-variants n1 o1 n2 o2 n3 o3 n4)
(let ([o1n (object-name o1)]
Line 7,526:
 
Search for all solutions using brute force:
<syntaxhighlight lang="racket">
(define (find-solutions numbers (goal 24))
(define in-operations (list + - * /))
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>
 
<syntaxhighlight lang=perl6"raku" line>use MONKEY-SEE-NO-EVAL;
 
my @digits;
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.
 
<syntaxhighlight lang=perl6"raku" line>my %*SUB-MAIN-OPTS = :named-anywhere;
 
sub MAIN (*@parameters, Int :$goal = 24) {
Line 7,771:
 
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/*REXX program helps the user find solutions to the game of 24. */
/* start-of-help
┌───────────────────────────────────────────────────────────────────────┐
Line 8,146:
{{trans|Tcl}}
{{works with|Ruby|2.1}}
<syntaxhighlight lang="ruby">class TwentyFourGame
EXPRESSIONS = [
'((%dr %s %dr) %s %dr) %s %dr',
Line 8,220:
=={{header|Rust}}==
{{works with|Rust|1.17}}
<syntaxhighlight lang="rust">#[derive(Clone, Copy, Debug)]
enum Operator {
Sub,
Line 8,399:
A non-interactive player.
 
<syntaxhighlight lang="scala">def permute(l: List[Double]): List[List[Double]] = l match {
case Nil => List(Nil)
case x :: xs =>
Line 8,457:
This version outputs an S-expression that will '''eval''' to 24 (rather than converting to infix notation).
 
<syntaxhighlight lang="scheme">
#!r6rs
 
Line 8,507:
 
Example output:
<syntaxhighlight lang="scheme">
> (solve 1 3 5 7)
((* (+ 1 5) (- 7 3))
Line 8,527:
'''With eval():'''
 
<syntaxhighlight lang="ruby">var formats = [
'((%d %s %d) %s %d) %s %d',
'(%d %s (%d %s %d)) %s %d',
Line 8,562:
 
'''Without eval():'''
<syntaxhighlight lang="ruby">var formats = [
{|a,b,c|
Hash(
Line 8,636:
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
 
 
Line 8,952:
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">
import Darwin
import Foundation
Line 9,171:
This is a complete Tcl script, intended to be invoked from the command line.
{{tcllib|struct::list}}
<syntaxhighlight lang="tcl">package require struct::list
# Encoding the various expression trees that are possible
set patterns {
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.
<syntaxhighlight lang=Ursala"ursala">#import std
#import nat
#import rat
Line 9,265:
game"n" "d" = format* value==("n",1)*~ with_roots/'+-*/' with_leaves/"d"*-1 tree_shapes length "d"</syntaxhighlight>
test program:
<syntaxhighlight lang=Ursala"ursala">#show+
 
test_games = mat` * pad` *K7 pad0 game24* <<2,3,8,9>,<5,7,4,1>,<5,6,7,8>></syntaxhighlight>
Line 9,303:
{{trans|Kotlin}}
{{libheader|Wren-dynamic}}
<syntaxhighlight lang="ecmascript">import "random" for Random
import "/dynamic" for Tuple, Enum, Struct
 
Line 9,415:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">operators$ = "*+-/"
space$ = " "
 
Line 9,599:
 
File solve24.zkl:
<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()) }
var ops=u(H.combosK(3,"+-*/".split("")).apply(H.permute).flatten());
Line 9,625:
{ f2s(digits4,ops3,f) }]];
}</syntaxhighlight>
<syntaxhighlight lang="zkl">solutions:=u(game24Solver(ask(0,"digits: ")));
println(solutions.len()," solutions:");
solutions.apply2(Console.println);</syntaxhighlight>
Line 9,652:
...
</pre>
 
[[Category:Puzzles]]
 
{{omit from|GUISS}}
{{omit from|ML/I}}
 
[[Category:Puzzles]]
10,327

edits