Playing Cards
For this question, we ask you to design a card game using the traditional 52-card deck. We divide this question into three parts, so you can complete them in order.
Part One
For the first part, you must design a Game
class representing the game, and
these following functions associated with the class.
add_card(suit, value)
: Creates a new card object with a suit from one of the following strings:Hearts
,Spades
,Clubs
,Diamonds
, and a value from one of the following strings:A
,2
~10
,J
,Q
,K
. This card is represented byi
, wherei
is an integer indicating how many cards have been created before.card_string(card)
: Returns the string representation of the card represented byi
. It follows the format<value> of <suit>
. For example, a card created byadd_card("Spades", "3")
should have a string representation of3 of Spades
.card_beats(card_a, card_b)
: Check if the card represented bycard_a
beats the one represented bycard_b
. A card beats another card if and only if it has a greater value. The value of the cards are ordered fromA
toK
.
You may implement these however you like. However, preferably this should be easily expandable to accommodate new requirements.
Try it yourself
Solution
There are numerous approaches we can take to design this problem. The sample solution will provide an object-oriented approach, since it allows us to easily add new types of cards to accommodate new requirements.
Different languages have different tools, but the most basic concept in object oriented programming is inheritance, which is a class deriving from a superclass and inheriting its methods. In this situation, a playing card from the 52 is a card. The reason for this design is that we can easily add other types of cards if we want.
Below is an implementation:
1from enum import Enum, auto
2
3class Card:
4 @property
5 def card_value(self) -> int:
6 raise NotImplementedError()
7
8 def __lt__(self, other):
9 return self.card_value < other.card_value
10
11class Suit(Enum):
12 CLUBS = auto()
13 DIAMONDS = auto()
14 HEARTS = auto()
15 SPADES = auto()
16
17class PlayingCard(Card):
18 SUITS = {
19 "Clubs": Suit.CLUBS,
20 "Diamonds": Suit.DIAMONDS,
21 "Hearts": Suit.HEARTS,
22 "Spades": Suit.SPADES,
23 }
24 SUIT_NAMES = {e: n for n, e in SUITS.items()}
25 VALUES = {
26 "A": 1,
27 **{str(i): i for i in range(2, 11)},
28 "J": 11,
29 "Q": 12,
30 "K": 13,
31 }
32 VALUE_NAMES = {e: n for n, e in VALUES.items()}
33
34 def __init__(self, suit: str, value: str):
35 super().__init__()
36 self.__suit = self.SUITS[suit]
37 self.__value = self.VALUES[value]
38
39 @property
40 def card_value(self) -> int:
41 return self.__value
42
43 def __str__(self) -> str:
44 value = self.VALUE_NAMES[self.__value]
45 suit = self.SUIT_NAMES[self.__suit]
46 return f"{value} of {suit}"
47
48class Game:
49 def __init__(self) -> None:
50 self.__cards: list[Card] = []
51
52 def add_card(self, suit: str, value: str) -> None:
53 self.__cards.append(PlayingCard(suit, value))
54
55 def card_string(self, card: int) -> str:
56 return str(self.__cards[card])
57
58 def card_beats(self, card_a: int, card_b: int) -> bool:
59 return self.__cards[card_a] > self.__cards[card_b]
60
61if __name__ == "__main__":
62 game = Game()
63 suit, value = input().split()
64 game.add_card(suit, value)
65 print(game.card_string(0))
66 suit, value = input().split()
67 game.add_card(suit, value)
68 print(game.card_string(1))
69 print("true" if game.card_beats(0, 1) else "false")
70
1import java.util.ArrayList;
2import java.util.HashMap;
3import java.util.Map;
4import java.util.Map.Entry;
5import java.util.Scanner;
6import java.util.stream.Collectors;
7
8class Solution {
9 public static abstract class Card implements Comparable<Card> {
10 public abstract int getValue();
11
12 @Override
13 public int compareTo(Card o) {
14 return Integer.compare(getValue(), o.getValue());
15 }
16 }
17
18 public enum Suit {
19 SPADES,
20 HEARTS,
21 DIAMONDS,
22 CLUBS,
23 }
24
25 public static class PlayingCard extends Card {
26 private Suit suit;
27 private int value;
28
29 public static final Map<String, Suit> SUITS = Map.of(
30 "Spades", Suit.SPADES,
31 "Hearts", Suit.HEARTS,
32 "Diamonds", Suit.DIAMONDS,
33 "Clubs", Suit.CLUBS);
34
35 // Inverts the above map to convert back to string.
36 public static final Map<Suit, String> SUIT_NAMES = SUITS.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
37
38 // Map.of is limited to 10 entries, so we initialize a static map instead
39 public static final Map<String, Integer> VALUES = new HashMap<>();
40 static {
41 VALUES.put("A", 1);
42 for (int i = 2; i <= 10; i++) {
43 VALUES.put(String.valueOf(i), i);
44 }
45 VALUES.put("J", 11);
46 VALUES.put("Q", 12);
47 VALUES.put("K", 13);
48 }
49 // Inverts the above map to convert back to string.
50 public static final Map<Integer, String> VALUE_NAMES = VALUES.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
51
52 public PlayingCard(String suit, String value) {
53 this.suit = SUITS.get(suit);
54 this.value = VALUES.get(value);
55 }
56
57 @Override
58 public int getValue() {
59 return value;
60 }
61
62 @Override
63 public String toString() {
64 return String.format("%s of %s", VALUE_NAMES.get(value), SUIT_NAMES.get(suit));
65 }
66 }
67
68 public static class Game {
69 private ArrayList<Card> cards;
70
71 public Game() {
72 cards = new ArrayList<>();
73 }
74
75 public void addCard(String suit, String value) {
76 cards.add(new PlayingCard(suit, value));
77 }
78
79 public String cardString(int card) {
80 return cards.get(card).toString();
81 }
82
83 public boolean cardBeats(int cardA, int cardB) {
84 return cards.get(cardA).compareTo(cards.get(cardB)) > 0;
85 }
86 }
87
88 public static void main(String[] args) {
89 Scanner scanner = new Scanner(System.in);
90 Game game = new Game();
91 String[] segs = scanner.nextLine().split(" ");
92 game.addCard(segs[0], segs[1]);
93 System.out.println(game.cardString(0));
94 segs = scanner.nextLine().split(" ");
95 game.addCard(segs[0], segs[1]);
96 System.out.println(game.cardString(1));
97 System.out.println(game.cardBeats(0, 1));
98 scanner.close();
99 }
100}
101
1using System;
2using System.Linq;
3
4class Solution
5{
6 public abstract class Card
7 {
8 public abstract int CardValue { get; }
9 }
10
11 public enum Suit
12 {
13 Clubs,
14 Diamonds,
15 Hearts,
16 Spades
17 }
18
19 public class PlayingCard : Card
20 {
21 private Suit suit;
22 private int value;
23
24 public static readonly Dictionary<string, Suit> SUITS = new Dictionary<string, Suit>
25 {
26 {"Clubs", Suit.Clubs},
27 {"Diamonds", Suit.Diamonds},
28 {"Hearts", Suit.Hearts},
29 {"Spades", Suit.Spades}
30 };
31
32 public static readonly Dictionary<Suit, string> SUIT_NAMES = new Dictionary<Suit, string>
33 {
34 {Suit.Clubs, "Clubs"},
35 {Suit.Diamonds, "Diamonds"},
36 {Suit.Hearts, "Hearts"},
37 {Suit.Spades, "Spades"}
38 };
39
40 public static readonly Dictionary<string, int> VALUES = new Dictionary<string, int>
41 {
42 {"A", 1},
43 {"2", 2}, {"3", 3}, {"4", 4}, {"5", 5}, {"6", 6}, {"7", 7}, {"8", 8}, {"9", 9}, {"10", 10},
44 {"J", 11},
45 {"Q", 12},
46 {"K", 13}
47 };
48
49 public static readonly Dictionary<int, string> VALUE_NAMES = new Dictionary<int, string>
50 {
51 {1, "A"}, {2, "2"}, {3, "3"}, {4, "4"}, {5, "5"}, {6, "6"}, {7, "7"}, {8, "8"}, {9, "9"}, {10, "10"},
52 {11, "J"}, {12, "Q"}, {13, "K"}
53 };
54
55 public PlayingCard(string suit, string value)
56 {
57 this.suit = SUITS[suit];
58 this.value = VALUES[value];
59 }
60
61 public override int CardValue => value;
62
63 public override string ToString()
64 {
65 return $"{VALUE_NAMES[value]} of {SUIT_NAMES[suit]}";
66 }
67 }
68
69 public class Game
70 {
71 private List<Card> cards;
72
73 public Game()
74 {
75 cards = new List<Card>();
76 }
77
78 public void AddCard(string suit, string value)
79 {
80 cards.Add(new PlayingCard(suit, value));
81 }
82
83 public string CardString(int card)
84 {
85 return cards[card].ToString();
86 }
87
88 public bool CardBeats(int cardA, int cardB)
89 {
90 return cards[cardA].CardValue > cards[cardB].CardValue;
91 }
92 }
93
94 public static void Main()
95 {
96 Game game = new Game();
97 string[] segs = Console.ReadLine().Split(' ');
98 game.AddCard(segs[0], segs[1]);
99 Console.WriteLine(game.CardString(0));
100 segs = Console.ReadLine().Split(' ');
101 game.AddCard(segs[0], segs[1]);
102 Console.WriteLine(game.CardString(1));
103 Console.WriteLine(game.CardBeats(0, 1) ? "true" : "false");
104 }
105}
106
1"use strict";
2
3class Card {
4 get cardValue() {
5 throw new Error("Not implemented");
6 }
7}
8
9class PlayingCard extends Card {
10 constructor(suit, value) {
11 super();
12 this.suit = suit;
13 this.value = value;
14 }
15
16 static SUITS = {
17 "Clubs": "Clubs",
18 "Diamonds": "Diamonds",
19 "Hearts": "Hearts",
20 "Spades": "Spades"
21 };
22
23 static VALUES = {
24 "A": 1,
25 "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10,
26 "J": 11,
27 "Q": 12,
28 "K": 13
29 };
30
31 static VALUE_NAMES = {
32 1: "A", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "10",
33 11: "J", 12: "Q", 13: "K"
34 };
35
36 get cardValue() {
37 return PlayingCard.VALUES[this.value];
38 }
39
40 toString() {
41 const valueName = PlayingCard.VALUE_NAMES[PlayingCard.VALUES[this.value]];
42 return `${valueName} of ${this.suit}`;
43 }
44}
45
46class Game {
47 constructor() {
48 this.cards = [];
49 }
50
51 addCard(suit, value) {
52 this.cards.push(new PlayingCard(suit, value));
53 }
54
55 cardString(card) {
56 return this.cards[card].toString();
57 }
58
59 cardBeats(cardA, cardB) {
60 return this.cards[cardA].cardValue > this.cards[cardB].cardValue;
61 }
62}
63
64function* main() {
65 const game = new Game();
66 let [suit, value] = (yield).split(" ");
67 game.addCard(suit, value);
68 console.log(game.cardString(0));
69 [suit, value] = (yield).split(" ");
70 game.addCard(suit, value);
71 console.log(game.cardString(1));
72 console.log(game.cardBeats(0, 1));
73}
74
75class EOFError extends Error {}
76{
77 const gen = main();
78 const next = (line) => gen.next(line).done && process.exit();
79 let buf = "";
80 next();
81 process.stdin.setEncoding("utf8");
82 process.stdin.on("data", (data) => {
83 const lines = (buf + data).split("\n");
84 buf = lines.pop();
85 lines.forEach(next);
86 });
87 process.stdin.on("end", () => {
88 buf && next(buf);
89 gen.throw(new EOFError());
90 });
91}
92
1abstract class Card {
2 abstract get cardValue(): number;
3}
4
5enum Suit {
6 CLUBS,
7 DIAMONDS,
8 HEARTS,
9 SPADES
10}
11
12class PlayingCard extends Card {
13 private suit: Suit;
14 private value: number;
15
16 static readonly SUITS: { [key: string]: Suit } = {
17 "Clubs": Suit.CLUBS,
18 "Diamonds": Suit.DIAMONDS,
19 "Hearts": Suit.HEARTS,
20 "Spades": Suit.SPADES
21 };
22
23 static readonly SUIT_NAMES: { [key: number]: string } = {
24 [Suit.CLUBS]: "Clubs",
25 [Suit.DIAMONDS]: "Diamonds",
26 [Suit.HEARTS]: "Hearts",
27 [Suit.SPADES]: "Spades"
28 };
29
30 static readonly VALUES: { [key: string]: number } = {
31 "A": 1,
32 "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10,
33 "J": 11,
34 "Q": 12,
35 "K": 13
36 };
37
38 static readonly VALUE_NAMES: { [key: number]: string } = {
39 1: "A", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "10",
40 11: "J", 12: "Q", 13: "K"
41 };
42
43 constructor(suit: string, value: string) {
44 super();
45 this.suit = PlayingCard.SUITS[suit];
46 this.value = PlayingCard.VALUES[value];
47 }
48
49 get cardValue(): number {
50 return this.value;
51 }
52
53 toString(): string {
54 const valueName = PlayingCard.VALUE_NAMES[this.value];
55 const suitName = PlayingCard.SUIT_NAMES[this.suit];
56 return `${valueName} of ${suitName}`;
57 }
58}
59
60class Game {
61 private cards: Card[] = [];
62
63 constructor() {
64 // Implement initializer here
65 }
66
67 addCard(suit: string, value: string): void {
68 this.cards.push(new PlayingCard(suit, value));
69 }
70
71 cardString(card: number): string {
72 return this.cards[card].toString();
73 }
74
75 cardBeats(cardA: number, cardB: number): boolean {
76 return this.cards[cardA].cardValue > this.cards[cardB].cardValue;
77 }
78}
79
80function* main() {
81 const game = new Game();
82 let [suit, value] = (yield).split(" ");
83 game.addCard(suit, value);
84 console.log(game.cardString(0));
85 [suit, value] = (yield).split(" ");
86 game.addCard(suit, value);
87 console.log(game.cardString(1));
88 console.log(game.cardBeats(0, 1));
89}
90
91class EOFError extends Error {}
92{
93 const gen = main();
94 const next = (line?: string) => gen.next(line ?? "").done && process.exit();
95 let buf = "";
96 next();
97 process.stdin.setEncoding("utf8");
98 process.stdin.on("data", (data) => {
99 const lines = (buf + data).split("\n");
100 buf = lines.pop() ?? "";
101 lines.forEach(next);
102 });
103 process.stdin.on("end", () => {
104 buf && next(buf);
105 gen.throw(new EOFError());
106 });
107}
108
1package main
2
3import (
4 "bufio"
5 "fmt"
6 "os"
7 "strings"
8)
9
10type Card interface {
11 CardValue() int
12}
13
14type Suit int
15
16const (
17 Clubs Suit = iota
18 Diamonds
19 Hearts
20 Spades
21)
22
23var (
24 SUITS = map[string]Suit{
25 "Clubs": Clubs,
26 "Diamonds": Diamonds,
27 "Hearts": Hearts,
28 "Spades": Spades,
29 }
30
31 SUIT_NAMES = map[Suit]string{
32 Clubs: "Clubs",
33 Diamonds: "Diamonds",
34 Hearts: "Hearts",
35 Spades: "Spades",
36 }
37
38 VALUES = map[string]int{
39 "A": 1,
40 "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10,
41 "J": 11,
42 "Q": 12,
43 "K": 13,
44 }
45
46 VALUE_NAMES = map[int]string{
47 1: "A", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "10",
48 11: "J", 12: "Q", 13: "K",
49 }
50)
51
52type PlayingCard struct {
53 suit Suit
54 value int
55}
56
57func NewPlayingCard(suit string, value string) *PlayingCard {
58 return &PlayingCard{
59 suit: SUITS[suit],
60 value: VALUES[value],
61 }
62}
63
64func (pc *PlayingCard) CardValue() int {
65 return pc.value
66}
67
68func (pc *PlayingCard) String() string {
69 return fmt.Sprintf("%s of %s", VALUE_NAMES[pc.value], SUIT_NAMES[pc.suit])
70}
71
72type Game struct {
73 cards []Card
74}
75
76func NewGame() *Game {
77 return &Game{
78 cards: make([]Card, 0),
79 }
80}
81
82func (g *Game) addCard(suit string, value string) {
83 g.cards = append(g.cards, NewPlayingCard(suit, value))
84}
85
86func (g *Game) cardString(card int) string {
87 return g.cards[card].(*PlayingCard).String()
88}
89
90func (g *Game) cardBeats(cardA int, cardB int) bool {
91 return g.cards[cardA].CardValue() > g.cards[cardB].CardValue()
92}
93
94func main() {
95 scanner := bufio.NewScanner(os.Stdin)
96 scanner.Scan()
97 var segs []string
98 segs = strings.Fields(scanner.Text())
99 game := Game{}
100 game.addCard(segs[0], segs[1])
101 fmt.Println(game.cardString(0))
102 scanner.Scan()
103 segs = strings.Fields(scanner.Text())
104 game.addCard(segs[0], segs[1])
105 fmt.Println(game.cardString(1))
106 fmt.Println(game.cardBeats(0, 1))
107}
108
1class Card
2 def card_value
3 raise NotImplementedError
4 end
5end
6
7class Suit
8 CLUBS = :clubs
9 DIAMONDS = :diamonds
10 HEARTS = :hearts
11 SPADES = :spades
12end
13
14class PlayingCard < Card
15 SUITS = {
16 "Clubs" => Suit::CLUBS,
17 "Diamonds" => Suit::DIAMONDS,
18 "Hearts" => Suit::HEARTS,
19 "Spades" => Suit::SPADES
20 }
21
22 SUIT_NAMES = SUITS.invert
23
24 VALUES = {
25 "A" => 1,
26 "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, "10" => 10,
27 "J" => 11,
28 "Q" => 12,
29 "K" => 13
30 }
31
32 VALUE_NAMES = VALUES.invert
33
34 def initialize(suit, value)
35 @suit = SUITS[suit]
36 @value = VALUES[value]
37 end
38
39 def card_value
40 @value
41 end
42
43 def to_s
44 "#{VALUE_NAMES[@value]} of #{SUIT_NAMES[@suit]}"
45 end
46end
47
48class Game
49 def initialize
50 @cards = []
51 end
52
53 def add_card(suit, value)
54 @cards << PlayingCard.new(suit, value)
55 end
56
57 def card_string(card)
58 @cards[card].to_s
59 end
60
61 def card_beats(card_a, card_b)
62 @cards[card_a].card_value > @cards[card_b].card_value
63 end
64end
65
66if __FILE__ == $0
67 game = Game.new
68 suit, value = gets.split
69 game.add_card(suit, value)
70 puts game.card_string(0)
71 suit, value = gets.split
72 game.add_card(suit, value)
73 puts game.card_string(1)
74 puts game.card_beats(0, 1)
75end
76
The Game
class stores a list of cards
which takes O(n)
space where n
is the number of cards added.
Each method (add_card
, card_string
, card_beats
) uses O(1)
time and O(1)
space.
Part Two
For this part, we ask you to implement the Jokers into the system.
In addition to the functionalities above, also implement the following functions:
add_joker(color)
: Creates a Joker card withcolor
of eitherRed
orBlack
.- Joker beats everything else except other jokers. This card is represented by
i
, wherei
is an integer indicating how many cards have been created before, including both normal cards and jokers. - A joker's string representation is
Red Joker
orBlack Joker
, depending on the color.
- Joker beats everything else except other jokers. This card is represented by
You may copy the code from the previous question here.
Try it yourself
Solution
We add a Joker
class that inherits the base Card
. For the purpose of this question,
its value is 14
, which is greater than other cards. We do not need to write extra logic
for comparing Jokers with other cards, since that logic is already there under Card
.
Below is the updated implementation:
1from enum import Enum, auto
2
3class Card:
4 @property
5 def card_value(self) -> int:
6 raise NotImplementedError()
7
8 def __lt__(self, other):
9 return self.card_value < other.card_value
10
11class Suit(Enum):
12 CLUBS = auto()
13 DIAMONDS = auto()
14 HEARTS = auto()
15 SPADES = auto()
16
17class PlayingCard(Card):
18 SUITS = {
19 "Clubs": Suit.CLUBS,
20 "Diamonds": Suit.DIAMONDS,
21 "Hearts": Suit.HEARTS,
22 "Spades": Suit.SPADES,
23 }
24 SUIT_NAMES = {e: n for n, e in SUITS.items()}
25 VALUES = {
26 "A": 1,
27 **{str(i): i for i in range(2, 11)},
28 "J": 11,
29 "Q": 12,
30 "K": 13,
31 }
32 VALUE_NAMES = {e: n for n, e in VALUES.items()}
33
34 def __init__(self, suit: str, value: str):
35 super().__init__()
36 self.__suit = self.SUITS[suit]
37 self.__value = self.VALUES[value]
38
39 @property
40 def card_value(self) -> int:
41 return self.__value
42
43 def __str__(self) -> str:
44 value = self.VALUE_NAMES[self.__value]
45 suit = self.SUIT_NAMES[self.__suit]
46 return f"{value} of {suit}"
47
48class JokerColor(Enum):
49 RED = auto()
50 BLACK = auto()
51
52class Joker(Card):
53 COLORS = {
54 "Red": JokerColor.RED,
55 "Black": JokerColor.BLACK,
56 }
57
58 COLOR_NAMES = {e: n for n, e in COLORS.items()}
59
60 def __init__(self, color: str):
61 super().__init__()
62 self.__color = self.COLORS[color]
63
64 @property
65 def card_value(self):
66 return 14
67
68 def __str__(self) -> str:
69 return f"{self.COLOR_NAMES[self.__color]} Joker"
70
71class Game:
72 def __init__(self):
73 self.__cards: list[Card] = []
74
75 def add_card(self, suit: str, value: str) -> None:
76 self.__cards.append(PlayingCard(suit, value))
77
78 def card_string(self, card: int) -> str:
79 return str(self.__cards[card])
80
81 def card_beats(self, card_a: int, card_b: int) -> bool:
82 return self.__cards[card_a] > self.__cards[card_b]
83
84 def add_joker(self, color: str) -> None:
85 self.__cards.append(Joker(color))
86
87if __name__ == "__main__":
88 game = Game()
89 suit, value = input().split()
90 game.add_joker(value) if suit == "Joker" else game.add_card(suit, value)
91 print(game.card_string(0))
92 suit, value = input().split()
93 game.add_joker(value) if suit == "Joker" else game.add_card(suit, value)
94 print(game.card_string(1))
95 print("true" if game.card_beats(0, 1) else "false")
96
1import java.util.ArrayList;
2import java.util.HashMap;
3import java.util.Map;
4import java.util.Map.Entry;
5import java.util.Scanner;
6import java.util.stream.Collectors;
7
8class Solution {
9 public static abstract class Card implements Comparable<Card> {
10 public abstract int getValue();
11
12 @Override
13 public int compareTo(Card o) {
14 return Integer.compare(getValue(), o.getValue());
15 }
16 }
17
18 public enum Suit {
19 SPADES,
20 HEARTS,
21 DIAMONDS,
22 CLUBS,
23 }
24
25 public static class PlayingCard extends Card {
26 private Suit suit;
27 private int value;
28
29 public static final Map<String, Suit> SUITS = Map.of(
30 "Spades", Suit.SPADES,
31 "Hearts", Suit.HEARTS,
32 "Diamonds", Suit.DIAMONDS,
33 "Clubs", Suit.CLUBS);
34
35 // Inverts the above map to convert back to string.
36 public static final Map<Suit, String> SUIT_NAMES = SUITS.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
37
38 // Map.of is limited to 10 entries, so we initialize a static map instead
39 public static final Map<String, Integer> VALUES = new HashMap<>();
40 static {
41 VALUES.put("A", 1);
42 for (int i = 2; i <= 10; i++) {
43 VALUES.put(String.valueOf(i), i);
44 }
45 VALUES.put("J", 11);
46 VALUES.put("Q", 12);
47 VALUES.put("K", 13);
48 }
49 // Inverts the above map to convert back to string.
50 public static final Map<Integer, String> VALUE_NAMES = VALUES.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
51
52 public PlayingCard(String suit, String value) {
53 this.suit = SUITS.get(suit);
54 this.value = VALUES.get(value);
55 }
56
57 @Override
58 public int getValue() {
59 return value;
60 }
61
62 @Override
63 public String toString() {
64 return String.format("%s of %s", VALUE_NAMES.get(value), SUIT_NAMES.get(suit));
65 }
66 }
67
68 public enum JokerColor {
69 RED,
70 BLACK,
71 }
72
73 public static class Joker extends Card {
74 private JokerColor color;
75
76 public static final Map<String, JokerColor> COLORS = Map.of(
77 "Red", JokerColor.RED,
78 "Black", JokerColor.BLACK);
79
80 // Inverts the above map to convert back to string.
81 public static final Map<JokerColor, String> COLOR_NAMES = COLORS.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
82
83 public Joker(String color) {
84 this.color = COLORS.get(color);
85 }
86
87 @Override
88 public int getValue() {
89 return 14;
90 }
91
92 @Override
93 public String toString() {
94 return String.format("%s Joker", COLOR_NAMES.get(color));
95 }
96 }
97
98 public static class Game {
99 private ArrayList<Card> cards;
100
101 public Game() {
102 cards = new ArrayList<>();
103 }
104
105 public void addCard(String suit, String value) {
106 cards.add(new PlayingCard(suit, value));
107 }
108
109 public String cardString(int card) {
110 return cards.get(card).toString();
111 }
112
113 public boolean cardBeats(int cardA, int cardB) {
114 return cards.get(cardA).compareTo(cards.get(cardB)) > 0;
115 }
116
117 public void addJoker(String color) {
118 cards.add(new Joker(color));
119 }
120 }
121
122 public static void main(String[] args) {
123 Scanner scanner = new Scanner(System.in);
124 Game game = new Game();
125 String[] segs = scanner.nextLine().split(" ");
126 if (segs[0].equals("Joker"))
127 game.addJoker(segs[1]);
128 else
129 game.addCard(segs[0], segs[1]);
130 System.out.println(game.cardString(0));
131 segs = scanner.nextLine().split(" ");
132 if (segs[0].equals("Joker"))
133 game.addJoker(segs[1]);
134 else
135 game.addCard(segs[0], segs[1]);
136 System.out.println(game.cardString(1));
137 System.out.println(game.cardBeats(0, 1));
138 scanner.close();
139 }
140}
141
1"use strict";
2
3class Card {
4 get cardValue() {
5 throw new Error("Not implemented");
6 }
7}
8
9class PlayingCard extends Card {
10 constructor(suit, value) {
11 super();
12 this.suit = suit;
13 this.value = value;
14 }
15
16 static SUITS = {
17 "Clubs": "Clubs",
18 "Diamonds": "Diamonds",
19 "Hearts": "Hearts",
20 "Spades": "Spades"
21 };
22
23 static VALUES = {
24 "A": 1,
25 "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10,
26 "J": 11,
27 "Q": 12,
28 "K": 13
29 };
30
31 static VALUE_NAMES = {
32 1: "A", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "10",
33 11: "J", 12: "Q", 13: "K"
34 };
35
36 get cardValue() {
37 return PlayingCard.VALUES[this.value];
38 }
39
40 toString() {
41 const valueName = PlayingCard.VALUE_NAMES[PlayingCard.VALUES[this.value]];
42 return `${valueName} of ${this.suit}`;
43 }
44}
45
46class Joker extends Card {
47 constructor(color) {
48 super();
49 this.color = color;
50 }
51
52 static COLORS = {
53 "Red": "Red",
54 "Black": "Black"
55 };
56
57 get cardValue() {
58 return 14;
59 }
60
61 toString() {
62 return `${this.color} Joker`;
63 }
64}
65
66class Game {
67 constructor() {
68 this.cards = [];
69 }
70
71 addCard(suit, value) {
72 this.cards.push(new PlayingCard(suit, value));
73 }
74
75 cardString(card) {
76 return this.cards[card].toString();
77 }
78
79 cardBeats(cardA, cardB) {
80 return this.cards[cardA].cardValue > this.cards[cardB].cardValue;
81 }
82
83 addJoker(color) {
84 this.cards.push(new Joker(color));
85 }
86}
87
88function* main() {
89 const game = new Game();
90 let [suit, value] = (yield).split(" ");
91 if (suit == "Joker") {
92 game.addJoker(value);
93 } else {
94 game.addCard(suit, value);
95 }
96 console.log(game.cardString(0));
97 [suit, value] = (yield).split(" ");
98 if (suit == "Joker") {
99 game.addJoker(value);
100 } else {
101 game.addCard(suit, value);
102 }
103 console.log(game.cardString(1));
104 console.log(game.cardBeats(0, 1));
105}
106
107class EOFError extends Error {}
108{
109 const gen = main();
110 const next = (line) => gen.next(line).done && process.exit();
111 let buf = "";
112 next();
113 process.stdin.setEncoding("utf8");
114 process.stdin.on("data", (data) => {
115 const lines = (buf + data).split("\n");
116 buf = lines.pop();
117 lines.forEach(next);
118 });
119 process.stdin.on("end", () => {
120 buf && next(buf);
121 gen.throw(new EOFError());
122 });
123}
124
1abstract class Card {
2 abstract get cardValue(): number;
3}
4
5enum Suit {
6 CLUBS,
7 DIAMONDS,
8 HEARTS,
9 SPADES
10}
11
12enum JokerColor {
13 RED,
14 BLACK
15}
16
17class PlayingCard extends Card {
18 private suit: Suit;
19 private value: number;
20
21 static readonly SUITS: { [key: string]: Suit } = {
22 "Clubs": Suit.CLUBS,
23 "Diamonds": Suit.DIAMONDS,
24 "Hearts": Suit.HEARTS,
25 "Spades": Suit.SPADES
26 };
27
28 static readonly SUIT_NAMES: { [key: number]: string } = {
29 [Suit.CLUBS]: "Clubs",
30 [Suit.DIAMONDS]: "Diamonds",
31 [Suit.HEARTS]: "Hearts",
32 [Suit.SPADES]: "Spades"
33 };
34
35 static readonly VALUES: { [key: string]: number } = {
36 "A": 1,
37 "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10,
38 "J": 11,
39 "Q": 12,
40 "K": 13
41 };
42
43 static readonly VALUE_NAMES: { [key: number]: string } = {
44 1: "A", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "10",
45 11: "J", 12: "Q", 13: "K"
46 };
47
48 constructor(suit: string, value: string) {
49 super();
50 this.suit = PlayingCard.SUITS[suit];
51 this.value = PlayingCard.VALUES[value];
52 }
53
54 get cardValue(): number {
55 return this.value;
56 }
57
58 toString(): string {
59 const valueName = PlayingCard.VALUE_NAMES[this.value];
60 const suitName = PlayingCard.SUIT_NAMES[this.suit];
61 return `${valueName} of ${suitName}`;
62 }
63}
64
65class Joker extends Card {
66 private color: JokerColor;
67
68 static readonly COLORS: { [key: string]: JokerColor } = {
69 "Red": JokerColor.RED,
70 "Black": JokerColor.BLACK
71 };
72
73 static readonly COLOR_NAMES: { [key: number]: string } = {
74 [JokerColor.RED]: "Red",
75 [JokerColor.BLACK]: "Black"
76 };
77
78 constructor(color: string) {
79 super();
80 this.color = Joker.COLORS[color];
81 }
82
83 get cardValue(): number {
84 return 14;
85 }
86
87 toString(): string {
88 const colorName = Joker.COLOR_NAMES[this.color];
89 return `${colorName} Joker`;
90 }
91}
92
93class Game {
94 private cards: Card[] = [];
95
96 constructor() {
97 // Implement initializer here
98 }
99
100 addCard(suit: string, value: string): void {
101 this.cards.push(new PlayingCard(suit, value));
102 }
103
104 cardString(card: number): string {
105 return this.cards[card].toString();
106 }
107
108 cardBeats(cardA: number, cardB: number): boolean {
109 return this.cards[cardA].cardValue > this.cards[cardB].cardValue;
110 }
111
112 addJoker(color: string): void {
113 this.cards.push(new Joker(color));
114 }
115}
116
117function* main() {
118 const game = new Game();
119 let [suit, value] = (yield).split(" ");
120 if (suit == "Joker") {
121 game.addJoker(value);
122 } else {
123 game.addCard(suit, value);
124 }
125 console.log(game.cardString(0));
126 [suit, value] = (yield).split(" ");
127 if (suit == "Joker") {
128 game.addJoker(value);
129 } else {
130 game.addCard(suit, value);
131 }
132 console.log(game.cardString(1));
133 console.log(game.cardBeats(0, 1));
134}
135
136class EOFError extends Error {}
137{
138 const gen = main();
139 const next = (line?: string) => gen.next(line ?? "").done && process.exit();
140 let buf = "";
141 next();
142 process.stdin.setEncoding("utf8");
143 process.stdin.on("data", (data) => {
144 const lines = (buf + data).split("\n");
145 buf = lines.pop() ?? "";
146 lines.forEach(next);
147 });
148 process.stdin.on("end", () => {
149 buf && next(buf);
150 gen.throw(new EOFError());
151 });
152}
153
1class Card
2 def card_value
3 raise NotImplementedError
4 end
5end
6
7class Suit
8 CLUBS = :clubs
9 DIAMONDS = :diamonds
10 HEARTS = :hearts
11 SPADES = :spades
12end
13
14class JokerColor
15 RED = :red
16 BLACK = :black
17end
18
19class PlayingCard < Card
20 SUITS = {
21 "Clubs" => Suit::CLUBS,
22 "Diamonds" => Suit::DIAMONDS,
23 "Hearts" => Suit::HEARTS,
24 "Spades" => Suit::SPADES
25 }
26
27 SUIT_NAMES = SUITS.invert
28
29 VALUES = {
30 "A" => 1,
31 "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, "10" => 10,
32 "J" => 11,
33 "Q" => 12,
34 "K" => 13
35 }
36
37 VALUE_NAMES = VALUES.invert
38
39 def initialize(suit, value)
40 @suit = SUITS[suit]
41 @value = VALUES[value]
42 end
43
44 def card_value
45 @value
46 end
47
48 def to_s
49 "#{VALUE_NAMES[@value]} of #{SUIT_NAMES[@suit]}"
50 end
51end
52
53class Joker < Card
54 COLORS = {
55 "Red" => JokerColor::RED,
56 "Black" => JokerColor::BLACK
57 }
58
59 COLOR_NAMES = COLORS.invert
60
61 def initialize(color)
62 @color = COLORS[color]
63 end
64
65 def card_value
66 14
67 end
68
69 def to_s
70 "#{COLOR_NAMES[@color]} Joker"
71 end
72end
73
74class Game
75 def initialize
76 @cards = []
77 end
78
79 def add_card(suit, value)
80 @cards << PlayingCard.new(suit, value)
81 end
82
83 def card_string(card)
84 @cards[card].to_s
85 end
86
87 def card_beats(card_a, card_b)
88 @cards[card_a].card_value > @cards[card_b].card_value
89 end
90
91 def add_joker(color)
92 @cards << Joker.new(color)
93 end
94end
95
96if __FILE__ == $0
97 game = Game.new
98 suit, value = gets.split
99 if suit == "Joker"
100 game.add_joker(value)
101 else
102 game.add_card(suit, value)
103 end
104 puts game.card_string(0)
105 suit, value = gets.split
106 if suit == "Joker"
107 game.add_joker(value)
108 else
109 game.add_card(suit, value)
110 end
111 puts game.card_string(1)
112 puts game.card_beats(0, 1)
113end
114
The method add_joker
uses O(1)
time and O(1)
space.
Part Three
This game also involve a concept of a Hand
and comparing the size of the two hands.
For this part, add these following functions to the Game
class:
add_hand(card_indices)
: Create a newHand
with cards represented by the list of integer representation of cardscard_indices
. The hand can be represented byi
, wherei
is the number of hands added before.hand_string(hand)
: Return the string representation of the hand represented byhand
. It is a list of string representation of cards by their insertion order, separated by", "
. For example, ifhand
has a 9 of Clubs, K of Hearts, and a Black Joker, the string representation is"9 of Clubs, K of Hearts, Black Joker"
.beats_hand(hand_a, hand_b)
: Check if the hand represented byhand_a
beats the hand represented byhand_b
according to the following rules:- Starting from the largest card in each hand, compare them. If a card beats another, that hand beats the other hand. Otherwise, compare the next largest card.
- Repeat this process until one hand beats the other, or one hand runs out of cards. If a hand runs out of cards, neither hand beat each other.
Try it yourself
Solution
For this part, we implement the Hand
class by having it contain a list of cards. When we
compare two hands, because we defined a comparison function between two cards, we can
sort them using the default sorting algorithm.
Below is the implementation:
1from enum import Enum, auto
2
3class Card:
4 @property
5 def card_value(self) -> int:
6 raise NotImplementedError()
7
8 def __lt__(self, other):
9 return self.card_value < other.card_value
10
11class Suit(Enum):
12 CLUBS = auto()
13 DIAMONDS = auto()
14 HEARTS = auto()
15 SPADES = auto()
16
17class PlayingCard(Card):
18 SUITS = {
19 "Clubs": Suit.CLUBS,
20 "Diamonds": Suit.DIAMONDS,
21 "Hearts": Suit.HEARTS,
22 "Spades": Suit.SPADES,
23 }
24 SUIT_NAMES = {e: n for n, e in SUITS.items()}
25 VALUES = {
26 "A": 1,
27 **{str(i): i for i in range(2, 11)},
28 "J": 11,
29 "Q": 12,
30 "K": 13,
31 }
32 VALUE_NAMES = {e: n for n, e in VALUES.items()}
33
34 def __init__(self, suit: str, value: str) -> None:
35 super().__init__()
36 self.__suit = self.SUITS[suit]
37 self.__value = self.VALUES[value]
38
39 @property
40 def card_value(self) -> int:
41 return self.__value
42
43 def __str__(self) -> str:
44 value = self.VALUE_NAMES[self.__value]
45 suit = self.SUIT_NAMES[self.__suit]
46 return f"{value} of {suit}"
47
48class JokerColor(Enum):
49 RED = auto()
50 BLACK = auto()
51
52class Joker(Card):
53 COLORS = {
54 "Red": JokerColor.RED,
55 "Black": JokerColor.BLACK,
56 }
57
58 COLOR_NAMES = {e: n for n, e in COLORS.items()}
59
60 def __init__(self, color: str) -> None:
61 super().__init__()
62 self.__color = self.COLORS[color]
63
64 @property
65 def card_value(self) -> int:
66 return 14
67
68 def __str__(self) -> str:
69 return f"{self.COLOR_NAMES[self.__color]} Joker"
70
71class Hand:
72 def __init__(self, cards: list[Card]) -> None:
73 super().__init__()
74 self.cards = list(cards)
75
76 def __str__(self) -> str:
77 return ", ".join(str(card) for card in self.cards)
78
79 def __lt__(self, other):
80 for card_a, card_b in zip(
81 sorted(self.cards, reverse=True),
82 sorted(other.cards, reverse=True),
83 ):
84 if card_a < card_b:
85 return True
86 elif card_b < card_a:
87 return False
88 return False
89
90class Game:
91 def __init__(self):
92 self.__cards: list[Card] = []
93 self.__hands: list[Hand] = []
94
95 def add_card(self, suit: str, value: str) -> None:
96 self.__cards.append(PlayingCard(suit, value))
97
98 def card_string(self, card: int) -> str:
99 return str(self.__cards[card])
100
101 def card_beats(self, card_a: int, card_b: int) -> bool:
102 return self.__cards[card_a] > self.__cards[card_b]
103
104 def add_joker(self, color: str) -> None:
105 self.__cards.append(Joker(color))
106
107 def add_hand(self, card_indices: list[int]) -> None:
108 self.__hands.append(Hand([self.__cards[i] for i in card_indices]))
109
110 def hand_string(self, hand: int) -> str:
111 return str(self.__hands[hand])
112
113 def hand_beats(self, hand_a: int, hand_b: int) -> bool:
114 return self.__hands[hand_a] > self.__hands[hand_b]
115
116if __name__ == "__main__":
117 game = Game()
118 offset = 0
119 for hand in range(2):
120 hand_list = []
121 n = int(input())
122 for i in range(n):
123 suit, value = input().split()
124 if suit == "Joker":
125 game.add_joker(value)
126 else:
127 game.add_card(suit, value)
128 hand_list.append(offset + i)
129 offset += n
130 game.add_hand(hand_list)
131 print(game.hand_string(hand))
132 print("true" if game.hand_beats(0, 1) else "false")
133
1import java.util.ArrayList;
2import java.util.Collections;
3import java.util.HashMap;
4import java.util.List;
5import java.util.Map;
6import java.util.Map.Entry;
7import java.util.Scanner;
8import java.util.stream.Collectors;
9
10class Solution {
11 public static abstract class Card implements Comparable<Card> {
12 public abstract int getValue();
13
14 @Override
15 public int compareTo(Card o) {
16 return Integer.compare(getValue(), o.getValue());
17 }
18 }
19
20 public enum Suit {
21 SPADES,
22 HEARTS,
23 DIAMONDS,
24 CLUBS,
25 }
26
27 public static class PlayingCard extends Card {
28 private Suit suit;
29 private int value;
30
31 public static final Map<String, Suit> SUITS = Map.of(
32 "Spades", Suit.SPADES,
33 "Hearts", Suit.HEARTS,
34 "Diamonds", Suit.DIAMONDS,
35 "Clubs", Suit.CLUBS);
36
37 // Inverts the above map to convert back to string.
38 public static final Map<Suit, String> SUIT_NAMES = SUITS.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
39
40 // Map.of is limited to 10 entries, so we initialize a static map instead
41 public static final Map<String, Integer> VALUES = new HashMap<>();
42 static {
43 VALUES.put("A", 1);
44 for (int i = 2; i <= 10; i++) {
45 VALUES.put(String.valueOf(i), i);
46 }
47 VALUES.put("J", 11);
48 VALUES.put("Q", 12);
49 VALUES.put("K", 13);
50 }
51 // Inverts the above map to convert back to string.
52 public static final Map<Integer, String> VALUE_NAMES = VALUES.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
53
54 public PlayingCard(String suit, String value) {
55 this.suit = SUITS.get(suit);
56 this.value = VALUES.get(value);
57 }
58
59 @Override
60 public int getValue() {
61 return value;
62 }
63
64 @Override
65 public String toString() {
66 return String.format("%s of %s", VALUE_NAMES.get(value), SUIT_NAMES.get(suit));
67 }
68 }
69
70 public enum JokerColor {
71 RED,
72 BLACK,
73 }
74
75 public static class Joker extends Card {
76 private JokerColor color;
77
78 public static final Map<String, JokerColor> COLORS = Map.of(
79 "Red", JokerColor.RED,
80 "Black", JokerColor.BLACK);
81
82 // Inverts the above map to convert back to string.
83 public static final Map<JokerColor, String> COLOR_NAMES = COLORS.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
84
85 public Joker(String color) {
86 this.color = COLORS.get(color);
87 }
88
89 @Override
90 public int getValue() {
91 return 14;
92 }
93
94 @Override
95 public String toString() {
96 return String.format("%s Joker", COLOR_NAMES.get(color));
97 }
98 }
99
100 public static class Hand implements Comparable<Hand> {
101 public ArrayList<Card> cards;
102
103 public Hand(List<Card> cards) {
104 this.cards = new ArrayList<>(cards);
105 }
106
107 @Override
108 public String toString() {
109 return cards.stream().map(String::valueOf).collect(Collectors.joining(", "));
110 }
111
112 @Override
113 public int compareTo(Hand o) {
114 ArrayList<Card> selfCards = new ArrayList<>(cards);
115 ArrayList<Card> otherCards = new ArrayList<>(o.cards);
116 Collections.sort(selfCards);
117 Collections.sort(otherCards);
118 for (int i = selfCards.size() - 1, j = otherCards.size() - 1; i >= 0 && j >= 0; i--, j--) {
119 int res = selfCards.get(i).compareTo(otherCards.get(j));
120 if (res != 0) {
121 return res;
122 }
123 }
124 return 0;
125 }
126 }
127
128 public static class Game {
129 private ArrayList<Card> cards;
130 private ArrayList<Hand> hands;
131
132 public Game() {
133 cards = new ArrayList<>();
134 hands = new ArrayList<>();
135 }
136
137 public void addCard(String suit, String value) {
138 cards.add(new PlayingCard(suit, value));
139 }
140
141 public String cardString(int card) {
142 return cards.get(card).toString();
143 }
144
145 public boolean cardBeats(int cardA, int cardB) {
146 return cards.get(cardA).compareTo(cards.get(cardB)) > 0;
147 }
148
149 public void addJoker(String color) {
150 cards.add(new Joker(color));
151 }
152
153 public void addHand(List<Integer> cardIndices) {
154 ArrayList<Card> cardObjects = new ArrayList<>();
155 for (int i : cardIndices) {
156 cardObjects.add(cards.get(i));
157 }
158 hands.add(new Hand(cardObjects));
159 }
160
161 public String handString(int hand) {
162 return hands.get(hand).toString();
163 }
164
165 public boolean handBeats(int handA, int handB) {
166 return hands.get(handA).compareTo(hands.get(handB)) > 0;
167 }
168 }
169
170 public static void main(String[] args) {
171 Scanner scanner = new Scanner(System.in);
172 Game game = new Game();
173 int i = 0;
174 int end = 0;
175 for (int hand = 0; hand < 2; hand++) {
176 ArrayList<Integer> handList = new ArrayList<>();
177 end += Integer.parseInt(scanner.nextLine());
178 for (; i < end; i++) {
179 String[] segs = scanner.nextLine().split(" ");
180 if (segs[0].equals("Joker"))
181 game.addJoker(segs[1]);
182 else
183 game.addCard(segs[0], segs[1]);
184 handList.add(i);
185 }
186 game.addHand(handList);
187 System.out.println(game.handString(hand));
188 }
189 System.out.println(game.handBeats(0, 1));
190 scanner.close();
191 }
192}
193
1"use strict";
2
3class Card {
4 get cardValue() {
5 throw new Error("Not implemented");
6 }
7}
8
9class PlayingCard extends Card {
10 constructor(suit, value) {
11 super();
12 this.suit = suit;
13 this.value = value;
14 }
15
16 static SUITS = {
17 "Clubs": "Clubs",
18 "Diamonds": "Diamonds",
19 "Hearts": "Hearts",
20 "Spades": "Spades"
21 };
22
23 static VALUES = {
24 "A": 1,
25 "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10,
26 "J": 11,
27 "Q": 12,
28 "K": 13
29 };
30
31 static VALUE_NAMES = {
32 1: "A", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "10",
33 11: "J", 12: "Q", 13: "K"
34 };
35
36 get cardValue() {
37 return PlayingCard.VALUES[this.value];
38 }
39
40 toString() {
41 const valueName = PlayingCard.VALUE_NAMES[PlayingCard.VALUES[this.value]];
42 return `${valueName} of ${this.suit}`;
43 }
44}
45
46class Joker extends Card {
47 constructor(color) {
48 super();
49 this.color = color;
50 }
51
52 static COLORS = {
53 "Red": "Red",
54 "Black": "Black"
55 };
56
57 get cardValue() {
58 return 14;
59 }
60
61 toString() {
62 return `${this.color} Joker`;
63 }
64}
65
66class Hand {
67 constructor(cards) {
68 this.cards = [...cards];
69 }
70
71 toString() {
72 return this.cards.map(card => card.toString()).join(", ");
73 }
74
75 compareTo(other) {
76 const selfCards = [...this.cards].sort((a, b) => b.cardValue - a.cardValue);
77 const otherCards = [...other.cards].sort((a, b) => b.cardValue - a.cardValue);
78
79 for (let i = 0; i < Math.min(selfCards.length, otherCards.length); i++) {
80 const diff = selfCards[i].cardValue - otherCards[i].cardValue;
81 if (diff !== 0) {
82 return diff;
83 }
84 }
85 return 0;
86 }
87}
88
89class Game {
90 constructor() {
91 this.cards = [];
92 this.hands = [];
93 }
94
95 addCard(suit, value) {
96 this.cards.push(new PlayingCard(suit, value));
97 }
98
99 cardString(card) {
100 return this.cards[card].toString();
101 }
102
103 cardBeats(cardA, cardB) {
104 return this.cards[cardA].cardValue > this.cards[cardB].cardValue;
105 }
106
107 addJoker(color) {
108 this.cards.push(new Joker(color));
109 }
110
111 addHand(cardIndices) {
112 const handCards = cardIndices.map(i => this.cards[i]);
113 this.hands.push(new Hand(handCards));
114 }
115
116 handString(hand) {
117 return this.hands[hand].toString();
118 }
119
120 handBeats(handA, handB) {
121 return this.hands[handA].compareTo(this.hands[handB]) > 0;
122 }
123}
124
125function* main() {
126 const game = new Game();
127 let i = 0;
128 let end = 0;
129 for (let hand = 0; hand < 2; hand++) {
130 const handList = [];
131 end += parseInt(yield);
132 for (; i < end; i++) {
133 const [suit, value] = (yield).split(" ");
134 if (suit == "Joker") {
135 game.addJoker(value);
136 } else {
137 game.addCard(suit, value);
138 }
139 handList.push(i);
140 }
141 game.addHand(handList);
142 console.log(game.handString(hand));
143 }
144 console.log(game.handBeats(0, 1));
145}
146
147class EOFError extends Error {}
148{
149 const gen = main();
150 const next = (line) => gen.next(line).done && process.exit();
151 let buf = "";
152 next();
153 process.stdin.setEncoding("utf8");
154 process.stdin.on("data", (data) => {
155 const lines = (buf + data).split("\n");
156 buf = lines.pop();
157 lines.forEach(next);
158 });
159 process.stdin.on("end", () => {
160 buf && next(buf);
161 gen.throw(new EOFError());
162 });
163}
164
1abstract class Card {
2 abstract get cardValue(): number;
3}
4
5enum Suit {
6 CLUBS,
7 DIAMONDS,
8 HEARTS,
9 SPADES
10}
11
12enum JokerColor {
13 RED,
14 BLACK
15}
16
17class PlayingCard extends Card {
18 private suit: Suit;
19 private value: number;
20
21 static readonly SUITS: { [key: string]: Suit } = {
22 "Clubs": Suit.CLUBS,
23 "Diamonds": Suit.DIAMONDS,
24 "Hearts": Suit.HEARTS,
25 "Spades": Suit.SPADES
26 };
27
28 static readonly SUIT_NAMES: { [key: number]: string } = {
29 [Suit.CLUBS]: "Clubs",
30 [Suit.DIAMONDS]: "Diamonds",
31 [Suit.HEARTS]: "Hearts",
32 [Suit.SPADES]: "Spades"
33 };
34
35 static readonly VALUES: { [key: string]: number } = {
36 "A": 1,
37 "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10,
38 "J": 11,
39 "Q": 12,
40 "K": 13
41 };
42
43 static readonly VALUE_NAMES: { [key: number]: string } = {
44 1: "A", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "10",
45 11: "J", 12: "Q", 13: "K"
46 };
47
48 constructor(suit: string, value: string) {
49 super();
50 this.suit = PlayingCard.SUITS[suit];
51 this.value = PlayingCard.VALUES[value];
52 }
53
54 get cardValue(): number {
55 return this.value;
56 }
57
58 toString(): string {
59 const valueName = PlayingCard.VALUE_NAMES[this.value];
60 const suitName = PlayingCard.SUIT_NAMES[this.suit];
61 return `${valueName} of ${suitName}`;
62 }
63}
64
65class Joker extends Card {
66 private color: JokerColor;
67
68 static readonly COLORS: { [key: string]: JokerColor } = {
69 "Red": JokerColor.RED,
70 "Black": JokerColor.BLACK
71 };
72
73 static readonly COLOR_NAMES: { [key: number]: string } = {
74 [JokerColor.RED]: "Red",
75 [JokerColor.BLACK]: "Black"
76 };
77
78 constructor(color: string) {
79 super();
80 this.color = Joker.COLORS[color];
81 }
82
83 get cardValue(): number {
84 return 14;
85 }
86
87 toString(): string {
88 const colorName = Joker.COLOR_NAMES[this.color];
89 return `${colorName} Joker`;
90 }
91}
92
93class Hand {
94 private cards: Card[];
95
96 constructor(cards: Card[]) {
97 this.cards = [...cards];
98 }
99
100 toString(): string {
101 return this.cards.map(card => card.toString()).join(", ");
102 }
103
104 compareTo(other: Hand): number {
105 const selfCards = [...this.cards].sort((a, b) => b.cardValue - a.cardValue);
106 const otherCards = [...other.cards].sort((a, b) => b.cardValue - a.cardValue);
107
108 for (let i = 0; i < Math.min(selfCards.length, otherCards.length); i++) {
109 const diff = selfCards[i].cardValue - otherCards[i].cardValue;
110 if (diff !== 0) {
111 return diff;
112 }
113 }
114 return 0;
115 }
116}
117
118class Game {
119 private cards: Card[] = [];
120 private hands: Hand[] = [];
121
122 constructor() {
123 // Implement initializer here
124 }
125
126 addCard(suit: string, value: string): void {
127 this.cards.push(new PlayingCard(suit, value));
128 }
129
130 cardString(card: number): string {
131 return this.cards[card].toString();
132 }
133
134 cardBeats(cardA: number, cardB: number): boolean {
135 return this.cards[cardA].cardValue > this.cards[cardB].cardValue;
136 }
137
138 addJoker(color: string): void {
139 this.cards.push(new Joker(color));
140 }
141
142 addHand(cardIndices: number[]): void {
143 const handCards = cardIndices.map(i => this.cards[i]);
144 this.hands.push(new Hand(handCards));
145 }
146
147 handString(hand: number): string {
148 return this.hands[hand].toString();
149 }
150
151 handBeats(handA: number, handB: number): boolean {
152 return this.hands[handA].compareTo(this.hands[handB]) > 0;
153 }
154}
155
156function* main() {
157 const game = new Game();
158 let i = 0;
159 let end = 0;
160 for (let hand = 0; hand < 2; hand++) {
161 const handList = [];
162 end += parseInt(yield);
163 for (; i < end; i++) {
164 const [suit, value] = (yield).split(" ");
165 if (suit == "Joker") {
166 game.addJoker(value);
167 } else {
168 game.addCard(suit, value);
169 }
170 handList.push(i);
171 }
172 game.addHand(handList);
173 console.log(game.handString(hand));
174 }
175 console.log(game.handBeats(0, 1));
176}
177
178class EOFError extends Error {}
179{
180 const gen = main();
181 const next = (line?: string) => gen.next(line ?? "").done && process.exit();
182 let buf = "";
183 next();
184 process.stdin.setEncoding("utf8");
185 process.stdin.on("data", (data) => {
186 const lines = (buf + data).split("\n");
187 buf = lines.pop() ?? "";
188 lines.forEach(next);
189 });
190 process.stdin.on("end", () => {
191 buf && next(buf);
192 gen.throw(new EOFError());
193 });
194}
195
1class Card
2 def card_value
3 raise NotImplementedError
4 end
5end
6
7class Suit
8 CLUBS = :clubs
9 DIAMONDS = :diamonds
10 HEARTS = :hearts
11 SPADES = :spades
12end
13
14class JokerColor
15 RED = :red
16 BLACK = :black
17end
18
19class PlayingCard < Card
20 SUITS = {
21 "Clubs" => Suit::CLUBS,
22 "Diamonds" => Suit::DIAMONDS,
23 "Hearts" => Suit::HEARTS,
24 "Spades" => Suit::SPADES
25 }
26
27 SUIT_NAMES = SUITS.invert
28
29 VALUES = {
30 "A" => 1,
31 "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, "10" => 10,
32 "J" => 11,
33 "Q" => 12,
34 "K" => 13
35 }
36
37 VALUE_NAMES = VALUES.invert
38
39 def initialize(suit, value)
40 @suit = SUITS[suit]
41 @value = VALUES[value]
42 end
43
44 def card_value
45 @value
46 end
47
48 def to_s
49 "#{VALUE_NAMES[@value]} of #{SUIT_NAMES[@suit]}"
50 end
51end
52
53class Joker < Card
54 COLORS = {
55 "Red" => JokerColor::RED,
56 "Black" => JokerColor::BLACK
57 }
58
59 COLOR_NAMES = COLORS.invert
60
61 def initialize(color)
62 @color = COLORS[color]
63 end
64
65 def card_value
66 14
67 end
68
69 def to_s
70 "#{COLOR_NAMES[@color]} Joker"
71 end
72end
73
74class Hand
75 def initialize(cards)
76 @cards = cards.dup
77 end
78
79 def to_s
80 @cards.map(&:to_s).join(", ")
81 end
82
83 def <=>(other)
84 self_cards = @cards.sort_by(&:card_value).reverse
85 other_cards = other.instance_variable_get(:@cards).sort_by(&:card_value).reverse
86
87 [self_cards.length, other_cards.length].min.times do |i|
88 diff = self_cards[i].card_value - other_cards[i].card_value
89 return diff if diff != 0
90 end
91 0
92 end
93
94 protected
95 attr_reader :cards
96end
97
98class Game
99 def initialize
100 @cards = []
101 @hands = []
102 end
103
104 def add_card(suit, value)
105 @cards << PlayingCard.new(suit, value)
106 end
107
108 def card_string(card)
109 @cards[card].to_s
110 end
111
112 def card_beats(card_a, card_b)
113 @cards[card_a].card_value > @cards[card_b].card_value
114 end
115
116 def add_joker(color)
117 @cards << Joker.new(color)
118 end
119
120 def add_hand(card_indices)
121 hand_cards = card_indices.map { |i| @cards[i] }
122 @hands << Hand.new(hand_cards)
123 end
124
125 def hand_string(hand)
126 @hands[hand].to_s
127 end
128
129 def hand_beats(hand_a, hand_b)
130 (@hands[hand_a] <=> @hands[hand_b]) > 0
131 end
132end
133
134if __FILE__ == $0
135 game = Game.new
136 i = 0
137 end_idx = 0
138 for hand in 0...2
139 hand_list = []
140 end_idx += gets.to_i
141 while i < end_idx
142 suit, value = gets.split
143 if suit == "Joker"
144 game.add_joker(value)
145 else
146 game.add_card(suit, value)
147 end
148 hand_list << i
149 i += 1
150 end
151 game.add_hand(hand_list)
152 puts game.hand_string(hand)
153 end
154 puts game.hand_beats(0, 1)
155end
156
add_hand
is to initialize a Hand
instance; it uses O(n)
time complexity and stores the list of cards using O(n)
space, where n
is the number of cards given to the hand.
both hand_string
and hand_beats
take O(1)
space.
hand_string
takes O(1)
time and hand_beats
takes O(min(n,m))
time where n
and m
are the size of the two hands respectively.