24 Game
Real-world version: Four Chips to Twenty-FourThe statement here is our own: the same inputs, outputs and technique.
A tabletop puzzle deals four numbered chips, given in cards, each showing a digit from 1 to 9.
The aim is to write an arithmetic line worth exactly 24 under these rules:
- Each chip's number is used once and once only. The chips may be taken in any order.
- The four numbers are joined by three operators, each chosen freely from
+,-,*and/, and brackets may be placed however you like. - Division is ordinary division, not whole-number division, so a partial value such as one third is perfectly legal as long as the line finishes at 24. Dividing by zero is not allowed, and a zero can turn up as a partial value, for instance from a chip subtracted from an equal chip.
- No two chips may be written side by side to make a two-digit number, and no number may be given a leading minus sign of its own.
All arithmetic is exact, and the line has to come to 24 exactly rather than close to it. Return true when such a line exists and false otherwise.
Examples
Example 1
- Input
- cards = [5, 5, 5, 1]
- Output
- true
The line 5 * (5 - 1 / 5) is worth 24, since 1 / 5 is one fifth, 5 minus one fifth is four and four fifths, and five times that is 24.
Example 2
- Input
- cards = [1, 1, 1, 1]
- Output
- false
Every line that can be written from four ones is worth at most 4, so 24 is out of reach.
Example 3
- Input
- cards = [1, 2, 3, 4]
- Output
- true
The line 1 * 2 * 3 * 4 is worth 24.
Constraints
- cards.length == 4
- 1 <= cards[i] <= 9
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def judge_point24(cards: list[int]) -> bool:public boolean judgePoint24(int[] cards)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 13 test cases: 13 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's