|
| 1 | +"""Kata - Poker cards encoder/decoder |
| 2 | +
|
| 3 | +completed at: 2024-11-03 18:33:16 |
| 4 | +by: Jakub Červinka |
| 5 | +
|
| 6 | +Consider a deck of 52 cards, which are represented by a string containing their suit and face value. |
| 7 | +
|
| 8 | +Your task is to write two functions ```encode``` and ```decode``` that translate an array of cards to/from an array of integer codes. |
| 9 | +
|
| 10 | +* function ```encode``` : |
| 11 | +
|
| 12 | + input : array of strings (symbols) |
| 13 | +
|
| 14 | + output : array of integers (codes) sorted in ascending order |
| 15 | + |
| 16 | +* function ```decode``` : |
| 17 | +
|
| 18 | + input : array of integers (codes) |
| 19 | + |
| 20 | + output : array of strings (symbols) sorted by code values |
| 21 | +
|
| 22 | +``` javascript |
| 23 | +['Ac', 'Ks', '5h', 'Td', '3c'] -> [0, 2 ,22, 30, 51] //encoding |
| 24 | +[0, 51, 30, 22, 2] -> ['Ac', '3c', 'Td', '5h', 'Ks'] //decoding |
| 25 | +``` |
| 26 | +
|
| 27 | +The returned array must be sorted from lowest to highest priority (value or precedence order, see below). |
| 28 | +
|
| 29 | +## Card suits: |
| 30 | +
|
| 31 | +``` |
| 32 | +name | symbol | precedence |
| 33 | +--------------------------------- |
| 34 | +club c 0 |
| 35 | +diamond d 1 |
| 36 | +heart h 2 |
| 37 | +spade s 3 |
| 38 | +``` |
| 39 | +
|
| 40 | +## 52-card deck: |
| 41 | +
|
| 42 | +``` |
| 43 | + c | d | h | s |
| 44 | +---------------------------------------- |
| 45 | + 0: A 13: A 26: A 39: A |
| 46 | + 1: 2 14: 2 27: 2 40: 2 |
| 47 | + 2: 3 15: 3 28: 3 41: 3 |
| 48 | + 3: 4 16: 4 29: 4 42: 4 |
| 49 | + 4: 5 17: 5 30: 5 43: 5 |
| 50 | + 5: 6 18: 6 31: 6 44: 6 |
| 51 | + 6: 7 19: 7 32: 7 45: 7 |
| 52 | + 7: 8 20: 8 33: 8 46: 8 |
| 53 | + 8: 9 21: 9 34: 9 47: 9 |
| 54 | + 9: T 22: T 35: T 48: T |
| 55 | +10: J 23: J 36: J 49: J |
| 56 | +11: Q 24: Q 37: Q 50: Q |
| 57 | +12: K 25: K 38: K 51: K |
| 58 | +``` |
| 59 | +
|
| 60 | +
|
| 61 | +
|
| 62 | +## My other kata about poker : |
| 63 | +
|
| 64 | +<a href="/dojo/katas/52ef1c60a863b919ef00025f">Poker cards reducer</a> |
| 65 | +""" |
| 66 | + |
| 67 | +suits = { |
| 68 | + 's': 39, |
| 69 | + 'h': 26, |
| 70 | + 'd': 13, |
| 71 | + 'c': 0, |
| 72 | +} |
| 73 | +values = [ |
| 74 | + 'A', |
| 75 | + *list(map(str, range(2, 10))), |
| 76 | + 'T', |
| 77 | + 'J', |
| 78 | + 'Q', |
| 79 | + 'K', |
| 80 | +] |
| 81 | + |
| 82 | + |
| 83 | +def encode(cards): |
| 84 | + return sorted( |
| 85 | + values.index(val) + suits[suit] |
| 86 | + for val, suit in cards |
| 87 | + ) |
| 88 | + |
| 89 | +def decode(cards): |
| 90 | + cards.sort() |
| 91 | + result = [] |
| 92 | + for num in cards: |
| 93 | + for suit, val in suits.items(): |
| 94 | + if (res := (num - val)) >= 0: |
| 95 | + result.append(f'{values[res]}{suit}') |
| 96 | + break |
| 97 | + return result |
| 98 | + |
| 99 | + |
0 commit comments