How to resolve the algorithm 24 game/Solve step by step in the Sidef programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm 24 game/Solve step by step in the Sidef programming language
Table of Contents
Problem Statement
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm 24 game/Solve step by step in the Sidef programming language
Source code in the sidef programming language
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)',
'%d %s (%d %s (%d %s %d))',
]
var op = %w( + - * / )
var operators = op.map { |a| op.map {|b| op.map {|c| "#{a} #{b} #{c}" } } }.flat
loop {
var input = read("Enter four integers or 'q' to exit: ", String)
input == 'q' && break
if (input !~ /^\h*[1-9]\h+[1-9]\h+[1-9]\h+[1-9]\h*$/) {
say "Invalid input!"
next
}
var n = input.split.map{.to_n}
var numbers = n.permutations
formats.each { |format|
numbers.each { |n|
operators.each { |operator|
var o = operator.split;
var str = (format % (n[0],o[0],n[1],o[1],n[2],o[2],n[3]))
eval(str) == 24 && say str
}
}
}
}
var formats = [
{|a,b,c|
Hash(
func => {|d,e,f,g| ((d.$a(e)).$b(f)).$c(g) },
format => "((%d #{a} %d) #{b} %d) #{c} %d"
)
},
{|a,b,c|
Hash(
func => {|d,e,f,g| (d.$a((e.$b(f)))).$c(g) },
format => "(%d #{a} (%d #{b} %d)) #{c} %d",
)
},
{|a,b,c|
Hash(
func => {|d,e,f,g| (d.$a(e)).$b(f.$c(g)) },
format => "(%d #{a} %d) #{b} (%d #{c} %d)",
)
},
{|a,b,c|
Hash(
func => {|d,e,f,g| (d.$a(e)).$b(f.$c(g)) },
format => "(%d #{a} %d) #{b} (%d #{c} %d)",
)
},
{|a,b,c|
Hash(
func => {|d,e,f,g| d.$a(e.$b(f.$c(g))) },
format => "%d #{a} (%d #{b} (%d #{c} %d))",
)
},
];
var op = %w( + - * / )
var blocks = op.map { |a| op.map { |b| op.map { |c| formats.map { |format|
format(a,b,c)
}}}}.flat
loop {
var input = Sys.scanln("Enter four integers or 'q' to exit: ");
input == 'q' && break;
if (input !~ /^\h*[1-9]\h+[1-9]\h+[1-9]\h+[1-9]\h*$/) {
say "Invalid input!"
next
}
var n = input.split.map{.to_n}
var numbers = n.permutations
blocks.each { |block|
numbers.each { |n|
if (block{:func}.call(n...) == 24) {
say (block{:format} % (n...))
}
}
}
}
You may also check:How to resolve the algorithm Empty program step by step in the LC3 Assembly programming language
You may also check:How to resolve the algorithm Factorial step by step in the Lasso programming language
You may also check:How to resolve the algorithm Verify distribution uniformity/Chi-squared test step by step in the OCaml programming language
You may also check:How to resolve the algorithm Loops/Foreach step by step in the Tailspin programming language
You may also check:How to resolve the algorithm Loops/With multiple ranges step by step in the Julia programming language