Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- This problem was asked by Facebook.
- Given a function that generates perfectly random numbers between 1 and k (inclusive), where k is an input, write a function
- that shuffles a deck of cards represented as an array using only swaps.
- It should run in O(N) time.
- Hint: Make sure each one of the 52! permutations of the deck is equally likely.
- '''
- from random import randrange, shuffle
- # 1st Function
- def generateDeckOfCards():
- ace = "A"
- numbers = list()
- figures = "JQK"
- categories = ["heart", "spade", "diamond", "club"]
- for i in range(2, 11):
- numbers.append(str(i))
- values = list()
- # Generate all the 13 values
- values.append(ace)
- for number in numbers:
- values.append(number)
- for figure in figures:
- values.append(figure)
- # Now, I will generate all the cards (4 categories * 13 values)
- cards = list()
- for category in categories:
- for value in values:
- cards.append(str(value) + "-" + str(category))
- return cards
- # 2nd Function
- def random(k):
- if k > 52 * 51 / 2 / 2:
- return -1000
- # Here my swaps will be <= all the comparisons between my elements
- return randrange(1, k+1)
- # 3rd Function
- def doISwap():
- flag = randrange(0, 2)
- if flag == 0:
- return False
- return True
- # 4th Function
- def shuffleCards(cards, k):
- cards = generateDeckOfCards()
- K = random(k)
- # I will first shuffle cards with the given method and then I will begin the process with my extra
- shuffled = cards.copy()
- shuffle(shuffled)
- # print(shuffled)
- # Now, the variable "shuffled" contains a randomly shuffled version of "cards" list
- SUM = 0
- for i in range(len(shuffled)-1):
- for j in range(i, len(shuffled)):
- swap = doISwap()
- if SUM == K:
- break
- if swap == True:
- SUM += 1
- shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
- return shuffled
- # MAIN FUNCTION
- cards = generateDeckOfCards()
- shuffled = shuffleCards(cards, 10)
- print(shuffled)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement