| about | help | code help+videos | done | prefs |
war
War! What is it good for? Absolutely nothing! Except ... if you're talking about the children's card game, it is good for wasting time. War is a boring card game because players have no strategic choices -- every play is mandated by the rules. So let's write a program to get the game over with faster! The function war(A, B) plays a game of war where each player starts with a half-deck of cards, A and B, respectively. The half-deck is represented as a list of integers (2 for a 2, 3 for a 3, up to 14 for an Ace). On each turn, both players play the top (first) card from their deck onto the table. This is called a "battle." If one card is higher than the other, than the player who played the high card wins the battle, and places both cards at the end of their deck (with the card from A first and the card from B last). If the cards are identical, it is a "war." That means each player plays two cards without comparing them, then a third card which is compared (and counts as a new "battle"); the winner picks up all the cards (putting them at the end of their deck in the same order in which they were played--first card played by A first; then first card played by B, and so on, up to the last card played by B at the very end of the deck). If the battle cards are the same, it starts another war; this can repeat any number of times. If at any time a player runs out of cards (whether in the middle of a war or not), the other player wins. The function war(A, B) returns +1 if A wins, -1 if B wins, and 0 for a draw. How can a draw occur? Two ways: if the decks are very small, then both players may run out of cards simultaneously in the middle of a war. And if the game reaches the same state twice (by "state" I mean the cards that each player holds at the start of a battle) then the game is stuck in a loop and will never end. You need to detect that condition, and return 0 for a draw. war([3, 4, 5, 6, 7, 8, 9, 10], [2, 3, 4, 5, 6, 7, 8, 9]) → 1 war([14, 2, 2, 14], [14, 3, 3, 13]) → 1 war([4, 2], [2, 4]) → 0 ...Save, Compile, Run (ctrl-enter) |
Progress graphs:
Your progress graph for this problem
Random user progress graph for this problem
Random Epic Progress Graph
Difficulty: 512 Post-solution available
Copyright Nick Parlante 2017 - privacy