Gem Purchase Simulator with Color-Based Discounts
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests stateful simulation with resource tracking, discount accumulation, and transactional updates.
You are building a gem-trading game simulator where players buy cards using colored gems.
Five gem colors exist: BLUE, WHITE, GREEN, RED, and YELLOW.
Each card is represented as a dictionary with:
"color": a string indicating which color discount this card provides once purchased"cost": a dictionary mapping gem colors to the quantity required to buy this card
You must simulate a sequence of operations on a player's state. The player begins with:
- A starting inventory of gems (given as a dictionary mapping colors to quantities)
- No purchased cards
- Zero discount in every color
Discount Mechanic:
When purchasing a card, the player receives a discount equal to the number of cards they already own in each gem color. Specifically, if the player owns d cards of a particular color, they pay d fewer gems of that color. The effective cost for any color cannot drop below zero.
Operations:
You will process two types of operations:
-
"canPurchase": Check whether the player can currently afford the specified card (after applying discounts). Returntrueorfalse. This operation does not modify any state. -
"purchase": Attempt to buy the specified card. If the player cannot afford it after discounts, returnfalseand make no changes to state. If affordable:- Deduct the discounted gem cost from the player's inventory
- Increment the discount counter for the purchased card's color by 1
- Return
true
Function Signature:
Implement process_gem_operations(starting_gems, card_list, operation_types, operation_args):
starting_gems: Dictionary mapping color names to initial gem quantities. Colors not present have quantity 0.card_list: List of card dictionaries (each with"color"and"cost"keys). Missing cost entries mean 0.operation_types: List of operation names ("canPurchase"or"purchase").operation_args: List of argument lists. Each inner list contains one integer: the index intocard_list.
Return a list of booleans, one result per operation in order.
Constraints:
- 1 ≤ number of operations ≤ 100
- 0 ≤ number of cards ≤ 50
- 0 ≤ gem quantities ≤ 100
- 0 ≤ cost values ≤ 100
- All color names are from the five valid colors
- Card indices in operations are valid
- All operations are either
"canPurchase"or"purchase"
Examples
Example 1
Input: process_gem_operations({'WHITE': 3, 'RED': 1}, [{'color': 'BLUE', 'cost': {'WHITE': 4, 'RED': 1}}], ['canPurchase', 'purchase', 'canPurchase'], [[0], [0], [0]])
Output: [False, False, False]
Example 2
Input: process_gem_operations({'WHITE': 5, 'RED': 1}, [{'color': 'WHITE', 'cost': {'WHITE': 4}}, {'color': 'RED', 'cost': {'WHITE': 2, 'RED': 1}}], ['purchase', 'canPurchase', 'purchase', 'canPurchase'], [[0], [1], [1], [1]])
Output: [True, True, True, False]
Example 3
Input: process_gem_operations({'BLUE': 0, 'WHITE': 0, 'GREEN': 0, 'RED': 0, 'YELLOW': 0}, [{'color': 'GREEN', 'cost': {}}], ['canPurchase', 'purchase', 'canPurchase'], [[0], [0], [0]])
Output: [True, True, True]
Hints
Hint 1
Calculate the effective cost for each color as max(0, base_cost - owned_cards_of_that_color) to ensure costs never go negative.
Hint 2
Validate affordability across all colors before modifying any state in a purchase operation to maintain atomicity.
Hint 3
The purchased card only grants its discount to future purchases, not to itself.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a stateful simulation problem focused on correct resource accounting and transactional updates.
The core mechanic is that each purchased card of a given color reduces future costs by one gem of that color. When evaluating whether a card is affordable, compute the effective cost for each color as max(0, base_cost - discount_count). The max function ensures costs never become negative, preventing players from gaining gems through purchases.
Track two pieces of state:
- Current gem inventory (one counter per color)
- Discount counters (number of owned cards per color)
For each operation:
- canPurchase: Check if the player has enough gems of each color to cover the discounted cost. This is a pure read operation with no side effects.
- purchase: First check affordability using the same logic. If unaffordable, return false and change nothing. If affordable, deduct the discounted cost from the gem inventory, increment the discount counter for the purchased card's color, and return true.
The key correctness requirement is atomicity: a purchase either fully succeeds (deducting all costs and updating discounts) or fails completely with no state changes. Validate affordability across all five colors before making any deductions.
Why It Works
- The discount calculation
max(0, cost - discount)prevents negative costs, which would incorrectly add gems - Checking all colors before deducting any ensures atomic transactions
- The discount from a card applies only to subsequent purchases, not to buying itself
- Normalizing all five colors up front handles missing dictionary keys cleanly
Complexity
- Time: O(1) per operation since there are only 5 colors. O(n) total for n operations.
- Space: O(1) for state tracking (fixed-size maps), plus O(n) for the result list.
Solution
from typing import Dict, List
def process_gem_operations(starting_gems: Dict[str, int], card_list: List[Dict[str, object]], operation_types: List[str], operation_args: List[List[int]]) -> List[bool]:
colors = ["BLUE", "WHITE", "GREEN", "RED", "YELLOW"]
gems = {color: starting_gems.get(color, 0) for color in colors}
discount_map = {color: 0 for color in colors}
result = []
def affordable(card):
cost = card.get("cost", {})
for color in colors:
discounted = max(0, cost.get(color, 0) - discount_map[color])
if gems[color] < discounted:
return False
return True
for operation, arg in zip(operation_types, operation_args):
card = card_list[arg[0]]
if operation == "canPurchase":
result.append(affordable(card))
elif operation == "purchase":
if not affordable(card):
result.append(False)
continue
cost = card.get("cost", {})
for color in colors:
discounted = max(0, cost.get(color, 0) - discount_map[color])
gems[color] -= discounted
card_color = card["color"]
discount_map[card_color] += 1
result.append(True)
else:
raise ValueError("unknown operation")
return result