11
16 Comments

Can you imagine such a short code solving the 24-point game?

The 24 Point Game is a classic puzzle game played with playing cards. The rules of the game are as follows: Remove the Jokers from a deck of playing cards, leaving 52 cards, randomly draw 4 cards, and use the numbers on the cards (where J, Q, K, A represent 11, 12, 13, 1 respectively) in combination with addition, subtraction, multiplication, division, and parentheses to achieve a result of 24. Each card must be used once and only once.

Write code to calculate 24 for any given four cards, outputting the solution in text format.

output results in text format

try.DEMO

A1 sets the four cards to be used for calculation, B1 enumerates all possible permutations for the four cards, and C1 lists the available arithmetic operators.

Since three operators need to be placed between the four cards, and each can be chosen arbitrarily, D1 utilizes multi-layer loops to list all possible operator combinations. In SPL, the A.conj@r() function, when used at the outermost loop, can union all the results of all layers to a sequence. The results in D1 are as follows:

results in D1

If you don’t want to manually write the enumeration results in B1, you can generate them using an expression: =4.conj@r(4.(4.(4.([~,get(1),get(2),get(3)]).select(~.icount()==4).(~.concat())))). Unlike C1, this requires selecting permutations that use all four cards, with each card used exactly once.

A2 loops through each permutation of the cards. B2, based on that permutation, retrieves the four numbers needed to calculate 24. For convenience, C2 assigns the four numbers to virables a, b, c, and d.

B3 loops through each available operator for every group of numbers. C3 splits the operators into a sequence. D3 assigns each operator to the vairables x, y, and z respectively.

Given a combination of numbers and operators in the form a#b#c#d, there are five distinct orders of operations that can be expressed using parentheses: a#(b#(c#d)), a#((b#c)#d), (a#b)#(c#d), ((a#b)#c)#d, and (a#(b#c))#d.

Within the loop, try each of the five operation orders in sequence. For example, C4 constructs the expression for the operation order a#(b#(c#d)), and C5 uses eval to calculate the result of that expression. To avoid the effects of calculation errors, the results need to be rounded using the round function, keeping 4 decimal places here. If the result of the expression is exactly 24, it indicates the expression in C4 satisfies the requirement. In this case, record the result in D5. Similarly, C6, C8, C10, and C12 construct expressions for the other four operation orders, and expressions that evaluate to 24 are then recorded in D7, D9, D11, and D13 respectively.

Once the loop ends, A14 retrieves all the expressions that meet the requirement and concatenates them to a sequence using conj. Because the given cards might be repeated, identical expressions may exist in the results, and therefore deduplication using id is necessary. A14’s output is as follows:

A14’s output

In the above solution, when analyzing the five operation orders for a given combination of numbers and operators, similar processing and checks were actually performed. This can be further simplified using a loop, as shown below:

loop results

try.DEMO

A2 prepares to store the results, and B2 lists the expressions corresponding to the five operation orders, where each variable is represented by ?. Inside the loop, when C5 evaluates a given number and operator combination, it iterates through each operation order in B2. The eval(s, x1,x2,…) function can sequentially replace ? in the string s with the values of x1,x2, and so on. Here, by inputting the numbers and operators into the parameter list in the required order, the corresponding expression exp can be obtained. Using eval again, the result of the expression can be calculated, and if the result is 24, the expression is recorded in A2.

esProc SPL is open-sourced and now available here if you are interested in it: Open-Source Address.

on February 24, 2025
  1. 1

    Yes! A cleverly written short code can efficiently solve the 24-point game by evaluating all possible operations on given numbers. With optimized algorithms, even a few lines of code can generate solutions instantly.

    1. 1

      Thanks for your feedback! Absolutely—an optimized approach can significantly reduce the complexity while ensuring efficiency. And it’s always fascinating to see how concise code can achieve such complex problem-solving! I would try to tackle more cases like that. Feel free to follow up my next post!

  2. 1

    This is a well-structured and insightful breakdown of solving the 24-point game efficiently. The approach systematically explores all possible number and operator combinations while ensuring accuracy and eliminating duplicates.

    What’s Great?
    ✅ Logical Flow – The step-by-step explanation makes it easy to understand how each permutation is evaluated.
    ✅ Comprehensive Expression Handling – Covers all five possible order-of-operations scenarios, ensuring no valid solution is missed.
    ✅ Optimization & Efficiency – Initially, individual checks were done for each operation order, but later, a loop was introduced to simplify and streamline the process.
    ✅ Precision & Error Handling – The use of rounding functions and duplicate removal ensures clean and accurate results.
    ✅ Neat Use of SPL – Demonstrates how SPL can handle complex calculations in a concise manner.

    Possible Improvements?
    🔹 Consider optimizing performance further using memoization or dynamic programming.
    🔹 A comparison with other programming languages (Python, C++, Java) could highlight SPL’s efficiency and unique advantages.

    Overall, this is a solid and well-explained solution that effectively tackles the problem in a structured way. Great job! 🚀

    1. 1

      Thank you so much for thoughtful analysis! I'm thrilled you recognized the systematic approach and SPL's capabilities in solving the 24-point puzzles.
      Your feedback is gold to me!
      I'll definitely explore memoization/dynamic programming optimizations to push performance further.
      Comparing SPL with Python/Java is a brilliant idea. And I have tackled some cases before and would love to share them in the following posts. Please stay tuned for my follow-up articles. They would help developers/readers appreciate SPL's conciseness for combinatorial problems.
      Glad you liked the error-handling and deduplication steps!
      Thanks again for taking the time to dissect this so thoroughly!

    1. 1

      Thanks! Glad you found the explanation helpful!

  3. 1

    Major kudos for not only solving it but also explaining the approach so clearly! The 24-point game seems simple at first, but the sheer number of possibilities is what makes it tricky for a computer (and often for us humans too!).

    1. 1

      Thank you! Really appreciate your kind words! The 24-point game is indeed deceptively simple—until you start considering all the possible permutations. It’s always fascinating to see how a structured approach can break down what seems like a complex problem into a clear and efficient solution. Hope it inspires you in solving other problems.

  4. 1

    Thanks for sharing. Great solution!

    1. 1

      Thanks for your compliment! 😊 I'm thrilled to hear you found the solution helpful.

  5. 1

    It's really ingenious.

    1. 1

      Thanks! Feel free to reach out if you'd like to dive into some code details.

  6. 1

    I have to say that the 24-point problem is very complicated, and it is difficult to write it down in such a short time

    1. 1

      You are absolutely right. It definitely requires careful breakdown! Glad the approach simplifies the complexity.

Trending on Indie Hackers
Build AI Agents & SaaS Apps Visually : Powered by Simplita ai User Avatar 32 comments You don't need to write the same thing again User Avatar 23 comments No Install, No Cost, Just Code User Avatar 20 comments Let’s Talk: What’s Missing in Today’s App Builders? User Avatar 17 comments 15 Years of Designmodo User Avatar 14 comments The Season of Creation Is Here — Textideo Is Giving Away Free Credits to Spark Your Ideas User Avatar 12 comments