Skip to content

Instantly share code, notes, and snippets.

@pepasflo
Created September 12, 2018 20:30
Show Gist options
  • Save pepasflo/25af033ebe2fa60e4ac797b5bc03ecfb to your computer and use it in GitHub Desktop.
Save pepasflo/25af033ebe2fa60e4ac797b5bc03ecfb to your computer and use it in GitHub Desktop.
interviewcake.com problem: Detect if a given single-rifle shuffled deck is possible from the given two halves.
++ ./shuffle.py '[1]' '[2]' '[1,2]'
+ test True == True
++ ./shuffle.py '[1]' '[2]' '[2,1]'
+ test True == True
++ ./shuffle.py '[1,2]' '[3]' '[1,2,3]'
+ test True == True
++ ./shuffle.py '[1,2]' '[3]' '[1,3,2]'
+ test True == True
++ ./shuffle.py '[1,2]' '[3]' '[3,1,2]'
+ test True == True
++ ./shuffle.py '[1,2]' '[3]' '[2,1,3]'
+ test False == False
++ ./shuffle.py '[1,2]' '[3]' '[2,3,1]'
+ test False == False
++ ./shuffle.py '[1,2]' '[3]' '[3,2,1]'
+ test False == False
+ echo 'All tests passed.'
All tests passed.
#!/usr/bin/env python
import sys
import json
def commonCount(list1, list2):
if len(list1) == 0 or len(list2) == 0:
return 0
elif list1[:1] == list2[:1]:
return 1 + commonCount(list1[1:], list2[1:])
else:
return 0
def isPossibleSingleRifleShuffle(half1, half2, shuffledDeck):
if len(shuffledDeck) == 0:
return True
common1 = commonCount(half1, shuffledDeck)
common2 = commonCount(half2, shuffledDeck)
if common1:
return True and isPossibleSingleRifleShuffle(half1[common1:], half2, shuffledDeck[common1:])
elif common2:
return True and isPossibleSingleRifleShuffle(half1, half2[common2:], shuffledDeck[common2:])
else:
return False
if len(sys.argv) < 4:
sys.stderr.write("Error: bad arguments\n")
sys.stderr.write("Usage: ./shuffle.py <half1 JSON> <half2 JSON> <shuffledDeck JSON>\n")
sys.exit(1)
half1 = json.loads(sys.argv[1])
half2 = json.loads(sys.argv[2])
shuffledDeck = json.loads(sys.argv[3])
print isPossibleSingleRifleShuffle(half1, half2, shuffledDeck)
#!/bin/bash
set -e -o pipefail
set -x
test "True" == `./shuffle.py [1] [2] [1,2]`
test "True" == `./shuffle.py [1] [2] [2,1]`
test "True" == `./shuffle.py [1,2] [3] [1,2,3]`
test "True" == `./shuffle.py [1,2] [3] [1,3,2]`
test "True" == `./shuffle.py [1,2] [3] [3,1,2]`
test "False" == `./shuffle.py [1,2] [3] [2,1,3]`
test "False" == `./shuffle.py [1,2] [3] [2,3,1]`
test "False" == `./shuffle.py [1,2] [3] [3,2,1]`
echo "All tests passed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment