Implement discounted card purchases
BrexSoftware Engineer · Technical ScreenLast updated
This question evaluates implementation-level skills in resource accounting and state management, specifically handling gem-cost mappings, per-color discounts, bounded arithmetic, and transactional updates to player state.
Implement purchase logic for a gem-based card game.
There are five gem colors: BLUE, WHITE, GREEN, RED, and YELLOW.
Each Card has:
- a
colorrepresenting the permanent discount it grants after purchase - a
costmap from gem color to required quantity
Each Player has:
- a
gemsmap from gem color to current quantity owned - a
handcontaining purchased cards - a
discountMapwherediscountMap[c]equals the number of previously purchased cards of colorc
Rules:
- When buying a card, the player gets a discount on each gem color equal to the number of owned cards of that same color.
- Example: if the player owns 2 white cards and 1 red card, then a card costing 4 white and 1 red has discounted cost 2 white and 0 red.
- A discounted cost for any color cannot go below 0.
canPurchase(card)should returntrueif the player can afford the card after applying discounts, otherwisefalse.purchase(card)should:
- return
falseand change nothing if the card is not affordable - otherwise deduct the discounted gem cost from the player's gems
- add the card to the player's hand
- increase the discount count for the purchased card's
colorby 1 - return
true
Write the logic for canPurchase and purchase correctly.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.