Play 24-point game with J language

fast prototyping a math card game with a powerful “vocabulary”

24-point is a math game played with a deck of regular playing cards. Once presented with 4 cards, players try to come up with a formula to reach 24, using 4 numbers and simple arithmetic, fastest one wins.

Here is all the possible 4-numbers out of 52 cards and the solutions (link).

For example, the 4 cards drawn are: 2, 4, 5, 8. Possible solutions are:

4 * 5 + 8 - 2
8 * (5 - 4 + 2)
8 * (2 * 4 - 5)
4 * (8 - 5) * 2
8 * 5 / 2 + 4

It’s easy to make a computer program exhaustive search all the combinations of four numbers, in combination with four arithmetic symbols and possible parentheses.

However, you can skip parentheses completely, which reduces the search space, if you choose to use RPN (HP calculator) expression, or even better J language (official website).

J doesn’t have operator precedence, in other words, the expression

8 * 5 + 2 - 4

will give 24, instead of the “normal” 38.

So given 4 numbers, the search space is the permutation of these 4 numbers: 24, times 3 positions, each with 4 possible arithmetic symbols (no parenthesis): 4³

24 * 64 = 1536 tries.

As a side note, human players usually look for simpler number patterns such as 4*6, 2*12, or 3*8 to reach 24, rather than exhaustively going through 1536 calculations in your head. So the lesson is not to play this game with a computer, but still a lot of fun playing with human opponents.

Now let’s come back to J language. Basically, we need to find J’s vocabulary for: permutation, outer product and making and executing math expressions.

J’s permutation of 4 numbers, 24 cases

card =: (i. !4) A. (<;._1) ' ', '2 4 5 8'┌─┬─┬─┬─┐
│2│4│5│8│
├─┼─┼─┼─┤
│2│4│8│5│
....

Next step is to produce 64 possible arrangements of the arithmetic operators

arth =: (4 4 4 #: i. 64) { '+-*%'+++
++-
++*
++%
....

Now we need a function to zip together the numbers with the operators as strings

fn =: 4 : 0
, (>x) ,. y , ' '
)

Then we outer product the card with arithmetic and execute the math expressions

table =: card (fn"1 1 /) arthindex =: 24 = ". table~. index (#"1 2) table2*4*8-5
4*2*8-5
4+5%2%8
4+5*8%2
4+8%2%5
4+8*5%2
8*2-4-5
8*2+5-4
8*5+2-4
8*5-4-2
8*5-4%2

11 possible solutions for the four cards 2, 4, 5, 8, which can be further simplified into three: 3*8, 4*6, 4+20 patterns

solve24 =: 3 : 0card =. (i. 24) A. (,;._1) ' ', yarth =. (4 4 4 #: i.64) { '+-*%'exp =. , @: ([ ,. ,&' ' @ ])table=. card (exp"2 1 /) arthindex=. 24 = ". table~. index (#"1 2) table)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store