Your task is to build a small system that lets a player buy cards by spending colored gems.
There are exactly five gem colors: BLUE, WHITE, GREEN, RED, and YELLOW.
A Card carries two pieces of data:
color: the color the card itself belongs to.cost[color]: the number of gems of each color needed to acquire it. Any color not listed counts as 0.A Player carries:
gems[color]: how many gems of each color the player currently holds. Any color not listed counts as 0.hand: the list of cards the player already owns.Write canPurchase(player, card). It returns true when the player holds enough gems to cover what the card costs, and false when they do not.
Write purchase(player, card).
player.gems.player.hand.true.false.Extend the system so that cards already in the player's hand make new cards cheaper.
hand.For instance, suppose the hand contains 2 WHITE cards and 1 RED card. Then discount[WHITE]=2 and discount[RED]=1. Buying a card whose cost is WHITE=4, RED=1 requires paying WHITE=max(4-2,0)=2 and RED=max(1-1,0)=0, i.e. 2 WHITE gems in total.
Provide two functions (or equivalent methods):
canPurchase(player, card) -> boolpurchase(player, card) -> boolBoth player.gems and player.hand must be kept in a correct state across calls.
Example 1:
Input:
(conceptual)
Player gems: {RED:5}
Hand: []
Card: color=RED cost={RED:2}
Call: purchase
Output: true (after: RED=3, hand size +1)
Explanation: The player holds 5 RED gems, which covers the cost of 2, so the purchase succeeds, leaving 3 RED gems and one more card in hand.
Basic affordable
RED=5, hand emptyRED=2purchase=true; afterwards RED=3, hand grows by 1Basic not affordable
GREEN=1GREEN=2canPurchase=false, purchase=false; state is unchangedAffordable due to discount
WHITE=2discount[WHITE]=2)WHITE=4WHITE=2; purchase=true; afterwards WHITE=0Discount can reduce cost to zero
RED=0discount[RED]=3)RED=2RED=0; purchase=true; afterwards RED=0Multi-color discounts
WHITE=2, RED=0WHITE=4, RED=1WHITE=2, RED=0; purchase=trueConstraints:
gems[color] and cost[color] are non-negative integers and may be as large as (range ).hand may be large, yet every purchase check must run in time.