Skip to content

Instantly share code, notes, and snippets.

@DrewDahlman
Last active August 29, 2015 14:22
Show Gist options
  • Save DrewDahlman/ab2d2d5469df2ad466f3 to your computer and use it in GitHub Desktop.
Save DrewDahlman/ab2d2d5469df2ad466f3 to your computer and use it in GitHub Desktop.
Pirates
#!/usr/bin/python
#---------------------------------------------------------------------------
#
# Pirates
#
# We need to find the number of pirates to talk to before we loop.
# Each pirate will refer us to another pirate, eventually we will find a
# pirate that directs us back to the original pirate, and we can exit.
#
#---------------------------------------------------------------------------
def answer(numbers):
## Our pirates
pirates = []
## Ask the first pirate who to talk to
pirates.append(numbers[numbers[0]])
## Start looping the numbers
for i in numbers:
## Our last pirate said to talk to numbers[X] Have we talked to them yet?
## If yes then quit and you found the loop
if numbers[pirates[-1]] in pirates:
print "pirates: " + str(len(pirates))
return
## We haven't talked to this pirate yet so lets add them to our pirates
if numbers[pirates[-1]] not in pirates:
pirates.append(numbers[pirates[-1]])
answer([1, 0]) # 2
answer([1, 2, 1]) # 2
answer([1, 3, 0, 1]) # 2
answer([2, 1, 3, 2]) # 2
answer([2, 2, 4, 4, 0]) # 3
answer([2, 3, 1, 4, 5, 0]) # 6
answer([1, 7, 1, 4, 5, 0, 7, 6]) # 2
answer([19, 3, 1, 21, 22, 11, 13, 12, 8, 20, 32, 27, 2, 4, 23, 9, 36, 25, 39, 0, 15, 16, 38, 26, 37, 33, 7, 17, 29, 10, 34, 6, 35, 31, 24, 18, 30, 4, 14, 3]) # 2
answer([5, 9, 5, 1, 6, 3, 6, 7, 2, 3, 0, 1]) # 3
answer([12, 47, 7, 58, 53, 28, 9, 10, 5, 21, 27, 1, 13, 30, 38, 19, 18, 35, 57, 26, 36, 20, 33, 32, 6, 2, 24, 29, 8, 52, 54, 0, 44, 39, 23, 37, 4, 51, 40, 45, 55, 22, 34, 59, 43, 46, 49, 3, 14, 41, 42, 25, 56, 11, 15, 16, 50, 17, 48, 31]) #50
answer([22, 19, 65, 76, 60, 3, 15, 27, 53, 1, 23, 45, 38, 72, 54, 73, 29, 78, 47, 21, 0, 42, 63, 39, 13, 7, 59, 28, 51, 36, 11, 18, 74, 6, 50, 8, 17, 33, 64, 4, 12, 9, 79, 24, 62, 56, 14, 70, 41, 69, 67, 5, 48, 16, 71, 52, 58, 34, 68, 49, 40, 43, 26, 30, 32, 66, 35, 10, 20, 2, 61, 31, 77, 55, 37, 25, 46, 75, 57, 44]) # 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment