Skip to content

Instantly share code, notes, and snippets.

@jbush001
Created July 29, 2012 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbush001/3195493 to your computer and use it in GitHub Desktop.
Save jbush001/3195493 to your computer and use it in GitHub Desktop.
# Rack-O simulation
import random
class GreedyHeuristicPlayer():
def getScore(self, rack):
return 1
def choose(self, rack, newCard):
bestScore = self.getScore(rack)
bestIndex = -1
for index in range(10):
candidate = rack[:]
candidate[index] = newCard
newScore = self.getScore(candidate)
if newScore > bestScore:
bestScore = newScore
bestIndex = index
return bestIndex
# Try to move cards to their natural positions (slot * 6)
class NaturalDistributionPlayer(GreedyHeuristicPlayer):
def getScore(self, rack):
score = 0
for x in range(10):
score += (rack[x] - x * 6) ** 2
return 1.0 / (score + 1.0)
# Find the longest run
class LongestRunPlayer(GreedyHeuristicPlayer):
def getScore(self, rack):
longestRun = 0
lastCard = -1
for x in rack:
if x > lastCard:
longestRun += 1
else:
longestRun = 1
lastCard = x
return longestRun
# The passed in player object will be used to make selections
def runSim(player):
# Create the initial configuration
deck = [ x + 1 for x in range(60) ]
random.shuffle(deck)
rack = deck[:10]
deck = deck[10:]
# Draw some cards to simulate the other players holding them
deck = deck[30:]
# Run some number of turns for the player
for iterations in range(100): # Give up after 100 iterations
iterations += 1
drawn = deck.pop(0)
slot = player.choose(rack, drawn)
if slot != -1:
# Replace the card in the rack with this one.
deck.append(rack[slot])
rack[slot] = drawn
# In order now?
if rack == sorted(rack):
return iterations
else:
# Discard: put it on the bottom of the deck
deck.append(drawn)
return 100
player = NaturalDistributionPlayer()
NUMTRIALS = 50
iterations = 0
for trial in range(NUMTRIALS):
iterations += runSim(player)
print 'average', iterations / NUMTRIALS, 'iterations'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment