24 game/Solve: Difference between revisions

Added R code
m (→‎{{header|Tcl}}: Tart up the output for readability)
(Added R code)
Line 176:
Solution found: 6 - ( 5 - 7 ) * 9
Thank you and goodbye</pre>
 
=={{header|R}}==
<lang r>
solve24 <- function(values)
{
ops <- c("+", "-", "*", "/")
if(!require(gtools)) stop("The package gtools is needed")
digiperm <- unique(permutations(4, 4, values, set=FALSE))
opcomb <- permutations(4, 3, ops, repeats.allowed=TRUE)
brackets <- matrix(c( #Should really find a more general solution
"", "", "", "", "", "",
"(", "", ")", "", "", "",
"", "(", "", "", ")", "",
"", "", "", "(", "", ")",
"(", "", "", "", ")", "",
"", "(", "", "", "", ")",
"(", "", "", "", "", ")",
"(", "", ")", "(", "", ")"),
byrow=TRUE, ncol=6)
nd <- nrow(digiperm)
no <- nrow(opcomb)
nb <- nrow(brackets)
score <- NA
found_soln <- FALSE
ans <- ""
pos <- 1L
for(i in 1:nd) #may be possible to vectorise
{
d <- digiperm[i,]
for(j in 1:no)
{
o <- opcomb[j,]
for(k in 1:nb)
{
b <- brackets[k,]
expr <- paste(c(b[1], d[1], o[1], b[2], d[2], b[3], o[2], b[4], d[3], b[5], o[3], d[4], b[6]), collapse=" ") #again, this needs generalising
score <- try(eval(parse(text=expr)))
if(!is.nan(score) && score == 24) #if there was a divide by zero error then score is NaN
{
found_soln <- TRUE
ans <- expr
break
}
pos <- pos + 1L
}
if(found_soln) break
}
if(found_soln) break
}
if(found_soln)
{
cat("A solution is:", ans, "\n")
} else
{
cat("No solution could be found\n")
}
invisible(ans)
}
</lang>
 
<lang r>
solve24(c(6, 7, 9, 5)) # A solution is: 6 + ( 7 - 5 ) * 9
solve24(c(9, 9, 9, 9)) # No solution could be found
</lang>
 
=={{header|Tcl}}==