Brex | Staff | Telephonic Interview
Anonymous User
845
  1. We want to write a function can_purchase() such that, given a particular card and collection of gems for a player, we return true if the player can afford the card, and false if they cannot.

  2. We want to write a function purchase() such that, given a particular card and collection of gems for a player, we add the card to the player's hand and subtract the cost from the player's gems, if they are able to afford the card. The function should return true if the player can afford the card, and false if they cannot.

  3. We want to introduce a new concept: for each card in a player's hand of a given color, we want to reduce the cost of any new purchase by 1 gem for that held card's color. For example, if the player holds 2 (G)reen cards and 1 (R)ed, and we are considering a card that lists its cost as 4 (G)reen, 2 (R)ed, and 1 (B)lue, then the player should be able to purchase it for 2 G, 1 R, and 1 B.

class Card {
    String color;
    Map<String, Integer> gems;
    public Card(String color, Map<String, Integer> gems) {
        this.color = color;
        this.gems = gems;
    }
}
class Player {
    private Map<String, Integer> gems;
    private List<Card> cards;
    private Map<String, Integer> discountGems;
    public Player(Map<String, Integer> gems) {
        this.gems = gems;
        this.cards = new ArrayList<>();
        this.discountGems = new HashMap();
    }
    
    public boolean canPurchase(Card card) {
        for (String color : card.gems.keySet()) {
            int discount = discountGems.getOrDefault(color, 0);
            if (!gems.containsKey(color) || card.gems.get(color) - discount > gems.get(color) ) {
                return false;
            }
        }
        return true;
    }
    
    public boolean purchase(Card card) {
        if (canPurchase(card)) {
            for (String color : card.gems.keySet()) {
                int discount = discountGems.getOrDefault(color, 0);
                gems.put(color, gems.get(color) - max(card.gems.get(color) - discount, 0));
            }
            discountGems.put(card.color, discountGems.getOrDefault(card.color, 0) + 1);
            cards.add(card);
            return true;
        } else {
            return false;
        }
    }
}
Comments (0)