Find a card after drawing
A card game draws a number of cards from the top of a deck. Find which card ends up at a given position in the remaining stack.
- Discard the top draws cards from the deck.
- Return the card at the given position index in what remains.
- If the position does not exist in the remaining deck, return -1.
cardPosition(deck: list<int>, draws: int, position: int) → int
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func cardPosition(deck []int, draws int, position int) int {
}
Worked examples
| Call | Result |
|---|---|
cardPosition([]int{10, 20, 30, 40, 50}, 2, 1) | 40 |
cardPosition([]int{1, 2, 3}, 0, 0) | 1 |
cardPosition([]int{1, 2, 3}, 3, 0) | -1 |
cardPosition([]int{5, 6, 7, 8}, 3, 0) | 8 |
Hint
The answer lives at index draws + position in the original deck, if that index is in bounds.
Reference solution in Go
func cardPosition(deck []int, draws int, position int) int {
idx := draws + position
if idx < len(deck) {
return deck[idx]
}
return -1
}