Idea thanks to @MartinBüttner from a discussion in chat
Mahjong is a tile game that is immensely popular in Asia. It is typically played with four players, and the goal of the game is to be the first person to complete a valid hand using the tiles. For this challenge, we will consider a simplified version of the game — PPCG mahjong.
In PPCG mahjong, there are three suits –
s – and the tiles are numbered from
9. There are exactly four copies of each tile, and the tiles are denoted by its number followed by its suit (e.g.
A completed PPCG mahjong hand consists of four sets of three and a pair, for a total of 14 tiles.
A set of three can be either:
- Three of the same tile (e.g.
4s 4s 4s, but not
4m 4p 4s), or
- A sequence of three consecutive tiles in the same suit (e.g.
1s 2s 3sor
6p 7p 8pbut not
3s 4m 5mor
3p 5p 7p). Sequences do not wrap (so
9m 1m 2mis invalid).
A pair is simply two identical tiles (e.g.
Your program will receive a space-separated hand of 13 tiles, with each tile appearing no more than four times. You may write either a full program or a function which takes in a string.
Your task is to find all possible 14th tiles ("waits") which, when added to the hand, would form a completed PPCG mahjong hand. The outputted tiles should be space-separated, but can be in any order. Leading or trailing whitespace is allowed.
Your program should run in a reasonable amount of time, no longer than a minute.
Input: 1m 1m 1m 4s 4s 4s 7p 7p 7p 3m 3m 3m 9s
Input: 1m 1m 1m 3m 3m 3m 5m 5m 5m 2s 3s 7p 8p
Input: 1m 2m 2m 3m 3m 3m 3m 4m 1s 1s 9s 9s 9s
Input: 1m 1m 1m 2m 3m 4m 5m 6m 7m 8m 9m 9m 9m
Output: 1m 2m 3m 4m 5m 6m 7m 8m 9m
Input: 1m 1m 1m 5p 2m 3m 5p 7s 8s 5p 9s 9s 9s
Output: 1m 4m 6s 9s
In the first example, the
1m 4s 7p 3m all form existing triplets, leaving the lone
9s to form a pair.
In the second example, the
2s 3s and
7p 8p can only form sequences, and the remaining tiles can only form triplets. Hence no pair can be formed, and there is no output.
In the third example, the hand splits into
1m2m3m 2m3m4m 3m3m 1s1s 9s9s9s. Normally this would be a wait for
3m 1s, but as all four
3m have been used, the only available wait is
In the fourth example, all of the
m tiles complete the hand. For example, for
1m, one could have
1m1m1m 1m2m3m 4m5m6m 7m8m9m 9m9m which is a completed hand.
Try to work out the rest of the fourth example and the fifth example :)