# Want to see a Magic Card Trick?

The first magic card trick I ever learned as a child was the following:

• Have 1 deck of cards where the pattern on the back is not vertically symmetric.
• Organize all cards to be facing one direction.
• Ask an individual to, "pick a card, any card, memorize it and give it back to you".
• Proceed to put it into the deck (in the wrong direction).
• Shuffle vigorously, giving the illusion that you won't know where their card is.
• Produce their card to their amazement.

This trick is obviously a little bit lack-luster in nature now-a-days, however it makes for a good challenge. Write a program, that when given no input, outputs a randomly shuffled deck of cards with one of the cards, chosen at random, reversed. However, when the input is a deck of cards with one card reversed, you must output the reversed card (in the correct order).

The Deck of Cards

A deck of cards is defined to be:

[2S,3S,4S,5S,6S,7S,8S,9S,TS,JS,QS,KS,AS,
2H,3H,4H,5H,6H,7H,8H,9H,TH,JH,QH,KH,AH,
2C,3C,4C,5C,6C,7C,8C,9C,TC,JC,QC,KC,AC]

A card is defined as it's number, then the first letter of its suit. The reverse of a card is the exact opposite, the first letter of its suit followed by a number.

The Drawn Card

Example, if the card we randomly chose to reverse was the 4 of Clubs (4C), we'd end up with (without shuffling, obviously):

[2S,3S,4S,5S,6S,7S,8S,9S,TS,JS,QS,KS,AS,
2H,3H,4H,5H,6H,7H,8H,9H,TH,JH,QH,KH,AH,
2C,3C,C4,5C,6C,7C,8C,9C,TC,JC,QC,KC,AC]

The Shuffling

Then, after shuffling:

This is a valid output given empty input.

The Deck Input

However, conversely, when our program receives the above output as input, it should output 4C. That is to say, for an input of:

You iterate through until you find the reversed card, and return it, reversed back to the normal state. So here we'd find C4, know that C isn't a number, and return it as 4C, which is correct.

# Rules

• You may not load the deck from any external sources.
• An empty input should result in a randomly shuffled deck with 1 random card reversed.
• A deck of cards with 1 card reversed as input should result in the reversed card.
• Any other inputs can result in explosive llamas riding segways through a futuristic tube.
• Or anything else, for that matter.
• Both the chosen card and the shuffling order must be uniformly random.
• I.E. all cards have equal chance of being selected to be reversed.
• I.E. all combinations of cards have an equal chance of appearing.
• You may use SHCD or shcd for the suits, but be consistent:
• If you choose uppercase suits (SHCD) you must also use TJQKA.
• If you choose lowercase suits (shcd) you must also use tjqka.
• This is , winner is lowest bytes.
• @labela--gotoa there's FAR too many variations of this haha. I remember my dad blowing my mind using vertically symmetric cards and doing a different trick, but making me think it was this one. – Magic Octopus Urn Feb 20 '18 at 21:35
• "Explosive llamas riding segways through a futuristic tube" - I'm looking forward to your next ascii-art challenge... – Level River St Feb 20 '18 at 22:05
• Rotating the entire deck by a random offset from 0 to 51 inclusive satisfies the condition that "all cards have an equal chance of appearing anywhere in the shuffled deck", but should probably not be considered a random shuffling. Do you mean that all (52!) orders are approximately equally likely? – aschepler Feb 21 '18 at 1:02
• Just to extend on what @aschepler said: with the period length of the default PRNG in many languages, most of the 52! possible shuffles have a probability of appearing exactly equal to zero (although it might be better or worse depending on the shuffling algorithm). – Arnauld Feb 21 '18 at 11:47
• Is a dalai lama riding a lama on a dolly also acceptable? I'm out of segways and explosives, but I have got candy worms... i.imgur.com/gEkVR5P.gif – Tschallacka Feb 21 '18 at 12:01

# Retina, 6160 59 bytes

G[HCDS].
^$23456789TJQK /^2/&L$.
$&H¶$&D¶$&C¶$&S
@V
O?

Try it online! Edit: Saved 1 2 bytes thanks to @MartinEnder. Explanation:

G[HCDS].

Delete all unreversed cards. This should leave one reversed card or no cards.

^$23456789TJQK /^2/&L$.
$&H¶$&D¶$&C¶$&S

If the input is (now) empty, create a pack of cards.

@V

Randomly select one card and reverse it (unreverses the single reversed card).

O?

Shuffle the card(s).

# 05AB1E, 29 bytes

Y9ŸJ.•§®т•«.•öB•âsKDgiëDΩÂ:.r

Try it online!

• .•Āk{?Öw•9LJì#â would save a few bytes to compress those two together. – Magic Octopus Urn Feb 21 '18 at 14:08
• @MagicOctopusUrn: After removing 1 and 2, that ends up at the same bytecount doesn't it? – Emigna Feb 21 '18 at 14:26
• Try it online! - 28, right? – Magic Octopus Urn Feb 21 '18 at 15:30
• @MagicOctopusUrn: Unfortunately not. You've got both 1 and a in there. – Emigna Feb 21 '18 at 20:28
• Leave it to me to misinterpret Y9ŸJ as 9LJ – Magic Octopus Urn Feb 21 '18 at 21:30

# PowerShell v2 or later, 175 bytes

%{$s=[char[]]'SDHC';if($_){$_|?{$s-contains$_[0]}|%{$_[1]+$_[0]}}else{$d=$s|%{$e=$_;[char[]]'23456789TJQKA'|%{$_+$e}}|random -c 52;$r=random 52;$d[$r]=$d[$r][1]+$d[$r][0];$d}} Long version: ForEach-Object {$s = [char[]]'SDHC'                         # Create a character array with the suits
if ($_) { # If there's pipeline input ...$_ |                                    # ... write it to the output pipeline ...
Where-Object {$s -contains$_[0]} | # ... but let only those input elements pass where the first letter appears in the suits ...
ForEach-Object {$_[1] +$_[0]}      # ... and swap the two elements
} else {
$d =$s | ForEach-Object {              # Assign $d to the output of the suits, processing each element first.$e = $_ # Store the current suit element for use in the inner loop [char[]]'23456789TJQKA' | ForEach-Object {$_ + $e} # Process each of the numbers, joining it with the current suit, ... } | Get-Random -Count 52 # ... and the resulting 2-char-strings goes back into the output to be shuffled$r = Get-Random -Maximum 52
$d[$r] = $d[$r][1] + $d[$r][0]          # Swap the two chars of a random array element in $d$d                                      # Write $d to the output pipeline } } ## Usage: Create a shuffled deck and store it in a variable:$Deck = %{$s=[char[]]'SDHC';if($_){$_|?{$s-contains$_[0]}|%{$_[1]+$_[0]}}else{$d=$s|%{$e=$_;[char[]]'23456789TJQKA'|%{$_+$e}}|random -c 52;$r=random 52;$d[$r]=$d[$r][1]+$d[$r][0];$d}} Inspect the variable at will, for example$Deck -join ','

Pipe the deck back into the script:

$Deck | %{$s=[char[]]'SDHC';if($_){$_|?{$s-contains$_[0]}|%{$_[1]+$_[0]}}else{$d=$s|%{$e=$_;[char[]]'23456789TJQKA'|%{$_+$e}}|random -c 52;$r=random 52;$d[$r]=$d[$r][1]+$d[$r][0];$d}}

# Python 2, 175 bytes

from random import*
s='SHCD';c='23456789TJQKA'
d=input()
if d:print[b+a for a,b in d if a in s];q
k=sample
r=k(c,1)+k(s,1)
print k([(a+b,b+a)[r==a+b]for a in c for b in s],52)

Try it online! empty input is denoted as []

# ><>, 215 193 bytes

i:0)?\~"CHSD":"2"$:"3"$:"4"$:"5"$:"6"$:"7"$:"8"$:"9"$:"T"$:"J"$:"Q"$:"K"$:"A"$&105&"S"=?.~~~{c0. =+i$?\i$:::"B")$"I"(*$"S" _oo$~/;
x0
x0
x0
x0
x0
x0
x0
x0
x0
x0
\l&>?!<

# Pyth, 45 bytes

J"CDHS"KO52=NsM.S*+c"AKQJT"1S9J|f}hTJQXNK_@NK

Takes the empty list for empty input.
Try it online

### Explanation

J"CDHS"KO52=NsM.S*+c"AKQJT"1S9J|f}hTJQXNK_@NK
J"CDHS"                                        Save the suits as J.
KO52                                    Save a random index as K.
=NsM.S*+c"AKQJT"1S9J                Save a shuffled deck as N.
f}hTJQ         Find all cards with suit first.
|      XNK_@NK  If there aren't any, flip a card.

# R, 177 171 bytes

function(l=1,F="(.)(.)",R="\\2\\1",S=sample)if(l>1)sub(F,R,grep("^[SDHC]",l,v=T))else{m=S(outer(c(2:9,"T","J","Q","K"),c("S","D","H","C"),paste0))
m[1]=sub(F,R,m[1])
S(m)}

Try it online!

Given empty input, (call f with no input), we default to l=1 and thus create a random permutation m of the deck. Assuming sample is truly random, there is an equal probability of any card being the first in this list. So we modify the first one, and then shuffle again, returning the list.

Reversing it, we look for a card starting with one of SDHC and reverse it.

# Python 2, 135 bytes

from random import*
s=shuffle
d=zip('A23456789TJQK'*4,'SCDH'*13)
s(d)
D=input()
if D:d=list(set(D)-set(d))
d[0]=d[0][::-1]
s(d)
print d

Try it online!

Cards are tuples of (value,suit)

Empty input is []