Mind boggling card trick: Difference between revisions

(Added AppleScript.)
(17 intermediate revisions by 12 users not shown)
Line 36:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">//import random
V n = 52
V Black = ‘Black’
Line 73:
print(‘Yeha! The mathematicians assertion is correct.’)
E
print(‘Whoops - The mathematicians (or my card manipulations) are flakey’)</langsyntaxhighlight>
 
{{out}}
Line 84:
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">use AppleScript version "2.5" -- OS X 10.11 (El Capitan) or later
<lang applescript>on cardTrick()
use framework "Foundation"
use framework "GameplayKit" -- For randomising functions.
 
on cardTrick()
(* Create a pack of "cards" and shuffle it. *)
set suits to {"♥️", "♣️", "♦️", "♠️"}
set cards to {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}
Line 94 ⟶ 99:
end repeat
end repeat
set deck to (current application's class "GKRandomSource"'s new()'s arrayByShufflingObjectsInArray:(deck)) as list
shuffle(deck)
(* Perform the black pile/red pile/discard stuff. *)
set {blackPile, redPile, discardPile} to {{}, {}, {}}
repeat with c from 1 to (count deck) by 2
Line 106 ⟶ 112:
set end of discardPile to topCard
end repeat
-- When equal numbers of two possibilities are randomly paired, the number of pairs whose members are
-- both one of the possibilities is the same as the number whose members are both the other. The cards
-- in the red and black piles have effectively been paired with cards of the eponymous colours, so
-- the number of reds in the red pile is already the same as the number of blacks in the black.
(* Take a random number of random cards from one pile and swap them with an equal number from the other,
religiously following the "red bunch"/"black bunch" ritual instead of simply swapping pairs of cards. *)
-- Where swapped cards are the same colour, this will make no difference at all. Where the colours
-- are different, both piles will either gain or lose a card of their relevant colour, maintaining
-- the defining balance either way.
set {redBunch, blackBunch} to {{}, {}}
set maxRand{redPileCount, blackPileCount} to {(count redPile), (count blackPile)}
set maxX to blackPileCount
tell (count redPile) to if (it < maxRand) then set maxRand to it
setif X(redPileCount to< (randommaxX) numberthen fromset 1maxX to maxRand)redPileCount
set X to (current application's class "GKRandomDistribution"'s distributionForDieWithSideCount:(maxX))'s nextInt()
set RNG to current application's class "GKShuffledDistribution"'s distributionForDieWithSideCount:(redPileCount)
repeat X times
set cr to RNG's nextInt(random number from 1 to maxRand)
set end of redBunch to textitem cr of redPile
set textitem cr of redPile to missing value
end repeat
set RNG to current application's class "GKShuffledDistribution"'s distributionForDieWithSideCount:(blackPileCount)
set c to (random number from 1 to maxRand)
repeat X times
set end of blackBunch to text c of blackPile
set text c of blackPileb to missingRNG's valuenextInt()
set end of blackBunch to item b of blackPile
set maxRanditem tob maxRandof blackPile to -missing 1value
end repeat
set blackPile to (blackPile's text) & redBunch
set redPile to (redPile's text) & blackBunch
(* Count and compare the number of blacks in the black pile and the number of reds in the red. *)
set blacksInBlackPile to 0
repeat with card in blackPile
Line 137 ⟶ 154:
return {truth:(blacksInBlackPile = redsInRedPile), reds:redPile, blacks:blackPile, discards:discardPile}
end cardTrick
 
on shuffle(array)
repeat with i from (count array) to 2 by -1
set j to (random number from 1 to i)
if (j < i) then
tell array's item i
set array's item i to array's item j
set array's item j to it
end tell
end if
end repeat
return array
end shuffle
 
on join(lst, delim)
Line 162 ⟶ 165:
on task()
set output to {}
repeat with i from 1 to 105
set {truth:truth, reds:reds, blacks:blacks, discards:discards} to cardTrick()
set end of output to "Test " & i & ": Assertion is " & truth
Line 172 ⟶ 175:
return text 1 thru -2 of join(output, linefeed)
end task
return task()</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">"Test 1: Assertion is true
Red pile: 8♥️3♦️, 5♠️2♦️, 9♥️9♣️, K♣️6♣️, J♣️3♥️, 10♣️9♥️, A♠️, Q♥️, Q♠️3♠️, 2♥️, 5♣️Q♠️, 3♣️7♥️, 2♠️, 2♦️K♥️
Black pile: K♥️Q♥️, 9♠️J♣️, 8♠️7♦️, 10♦️4♦️, 7♣️8♦️, 2♣️5♥️, A♣️K♣️, 3♦️10♠️, 7♦️10♣️, 7♣️, 2♣️, 10♥️9♦️, J♥️5♣️, K♦️6♦️
Discards: A♦️9♠️, 4♣️Q♦️, 4♥️3♣️, 3♠️6♠️, Q♦️8♠️, 6♣️8♥️, 6♥️Q♣️, J♠️4♠️, 6♠️J♠️, 5♥️K♦️, 4♠️7♠️, K♠️A♦️, 6♦️5♦️
9♦️, 7♥️10♥️, J♦️, A♥️, 8♣️4♥️, 7♠️6♥️, Q♣️J♥️, 10♠️K♠️, 3♥️5♠️, 4♦️10♦️, 5♦️4♣️, 8♦️2♠️, 8♣️, 9♣️A♣️
 
Test 2: Assertion is true
Red pile: A♣️7♣️, K♠️Q♠️, J♠️2♦️, 2♦️K♣️, 7♦️J♠️, K♣️A♠️, 5♦️J♣️, 4♣️5♣️, 7♠️6♥️, 4♥️7♦️, 5♥️, 7♣️9♥️, 8♠️, 3♠️, 6♣️, 8♣️4♠️
Black pile: 3♦️K♠️, 9♥️J♦️, 6♣️, K♥️, Q♥️4♣️, 10♠️, 10♣️4♥️, 2♥️3♥️, 6♠️, 8♥️4♦️, 2♠️, 6♥️10♣️, 6♦️9♦️
Discards: K♦️8♦️, 10♥️J♥️, J♣️A♣️, A♦️10♥️, 5♣️8♣️, 9♠️, 8♦️A♦️, Q♦️2♣️, 9♣️K♥️, 7♥️Q♣️, A♥️, 5♠️5♦️, Q♠️9♣️
8♠️K♦️, A♠️3♣️, 9♦️2♠️, 4♠️7♠️, Q♣️5♠️, 2♣️2♥️, 10♦️6♦️, 3♥️10♦️, 4♦️3♦️, J♦️Q♦️, 3♠️8♥️, 3♣️7♥️, J♥️Q♥️
 
Test 3: Assertion is true
Red pile: Q♦️4♥️, K♦️2♠️, J♥️Q♦️, 5♥️9♣️, 3♠️4♣️, 2♦️7♥️, 2♣️A♣️, 9♠️6♠️, 7♦️3♥️, 3♥️8♣️, 7♠️A♦️, 2♣️, 3♣️6♥️, 10♠️5♦️
Black pile: 6♥️K♦️, 9♦️2♦️, 6♠️5♠️, 10♣️10♠️, 4♥️J♠️, 7♥️9♦️, A♠️4♦️, J♠️4♠️, 4♠️Q♣️, A♥️6♣️, K♣️3♣️, 10♦️, 7♣️
Discards: 6♣️J♦️, 4♦️9♥️, Q♠️K♠️, 5♦️10♥️, J♣️5♥️, K♠️10♣️, Q♥️K♣️, A♣️8♠️, J♦️8♥️, 8♠️A♠️, 4♣️7♣️, 8♣️7♦️, 10♥️8♦️
5♣️Q♠️, 2♥️9♠️, 6♦️, 8♥️3♠️, 9♣️2♥️, 9♥️J♣️, Q♣️A♥️, 3♦️K♥️, 2♠️Q♥️, A♦️5♣️, K♥️7♠️, 5♠️3♦️, 8♦️J♥️
 
Test 4: Assertion is true
Red pile: 10♥️6♠️, J♣️A♣️, 5♣️8♥️, 9♦️4♣️, 9♣️5♥️, A♠️J♠️, K♥️9♠️, 3♠️7♥️, 3♣️7♣️, 5♦️4♦️, A♠️, A♥️, 6♠️8♠️, 7♥️6♦️, 5♣️, Q♣️, 6♥️, Q♦️K♠️
Black pile: 8♣️5♦️, 4♦️4♠️, A♦️2♣️, A♣️6♣️, 6♦️10♣️, K♠️8♣️, 7♣️Q♠️, K♣️, 10♦️, K♦️, J♠️, Q♠️10♠️
Discards: 5♠️J♥️, 9♥️A♦️, 7♦️7♠️, Q♥️9♥️, 5♥️K♦️, 7♠️10♥️, 4♥️Q♦️, 8♠️10♦️, J♦️8♦️, 2♥️3♥️, 9♠️3♠️, 10♣️2♦️, 6♣️J♣️
2♦️9♦️, 10♠️J♦️, 8♥️9♣️, 3♦️2♠️, 2♣️3♦️, 6♥️2♥️, 4♠️7♦️, J♥️Q♥️, 4♣️3♣️, 3♥️K♥️, 2♠️K♣️, 8♦️5♠️, Q♣️4♥️
 
Test 5: Assertion is true
Red pile: Q♥️2♣️, Q♠️9♠️, K♥️5♦️, 9♠️4♥️, 3♠️K♥️, 4♦️5♥️, A♦️8♦️, 8♣️2♠️, 4♥️3♦️, A♥️10♥️, 7♦️10♦️
Black pile: 8♥️2♦️, 2♥️, 7♥️8♣️, 4♣️9♣️, 8♦️7♥️, Q♣️3♣️, 2♦️Q♠️, 3♣️10♠️, 5♣️8♥️, 8♠️10♣️, 9♦️K♣️, 3♦️5♠️, 4♠️4♦️, 7♣️3♥️, K♦️6♥️
Discards: 5♠️7♦️, 5♦️J♥️, 6♠️7♣️, 10♣️4♠️, Q♦️6♦️, 3♥️4♣️, K♣️7♠️, 2♠️Q♥️, J♦️J♠️, 6♣️Q♦️, J♣️6♠️, 6♦️J♣️, A♠️A♥️
K♠️9♦️, 6♥️K♦️, 10♠️J♦️, 9♣️3♠️, J♥️5♣️, 9♥️Q♣️, 7♠️A♣️, J♠️K♠️, 10♥️8♠️, 5♥️9♥️, 10♦️A♠️, 2♣️6♣️, A♣️A♦️"</syntaxhighlight>
 
Test 6: Assertion is true
Red pile: 5♥️, 4♥️, 6♥️, 3♦️, 9♣️, J♦️, 6♦️, 3♣️, 3♥️, 10♥️, J♣️, K♠️
Black pile: 4♣️, 5♦️, A♠️, Q♦️, A♦️, 8♥️, A♥️, K♣️, 2♣️, A♣️, 9♦️, 7♠️, J♠️, 10♠️
Discards: 8♠️, 3♠️, J♥️, 2♦️, 8♦️, Q♥️, 8♣️, 4♦️, 7♦️, 7♥️, Q♣️, K♥️, 10♦️
10♣️, 9♠️, 7♣️, 5♠️, Q♠️, 6♠️, 4♠️, 5♣️, 2♥️, 2♠️, 6♣️, K♦️, 9♥️
 
Test 7: Assertion is true
Red pile: 3♦️, K♠️, K♥️, 5♣️, 9♣️, 8♥️, K♦️, 2♥️, 9♥️, 3♥️, 8♣️, 6♥️, 4♠️
Black pile: J♣️, 8♠️, 7♠️, J♦️, Q♣️, 2♦️, A♦️, 10♦️, 6♣️, 5♠️, J♠️, 7♣️, 7♥️
Discards: 10♠️, 6♦️, 5♥️, Q♦️, 5♦️, 3♠️, 9♦️, 10♥️, J♥️, 9♠️, 8♦️, Q♥️, 3♣️
6♠️, 4♥️, 4♦️, A♥️, 2♣️, Q♠️, 4♣️, A♠️, K♣️, 7♦️, A♣️, 2♠️, 10♣️
 
Test 8: Assertion is true
Red pile: 4♥️, 2♣️, Q♦️, 10♣️, 3♥️, 2♦️, K♠️, 9♣️, A♣️, Q♠️, 10♠️, 6♥️
Black pile: 5♦️, 10♦️, K♥️, J♣️, J♥️, 6♣️, 7♠️, 3♦️, 7♥️, 8♦️, 9♠️, A♥️, 3♠️, K♦️
Discards: 8♣️, 7♣️, J♦️, 2♥️, 8♥️, 5♠️, 10♥️, 4♣️, 5♥️, J♠️, A♠️, Q♣️, 9♦️
4♦️, 2♠️, 8♠️, 6♦️, 9♥️, K♣️, A♦️, 5♣️, 3♣️, 4♠️, 7♦️, Q♥️, 6♠️
 
Test 9: Assertion is true
Red pile: 8♦️, 7♣️, 4♠️, 7♠️, 3♠️, 7♥️, A♥️, 9♥️, 9♦️, 8♥️, 5♦️, K♠️, 5♠️, Q♣️, J♦️
Black pile: 8♠️, 10♦️, 9♠️, Q♠️, 7♦️, 10♠️, 3♥️, A♠️, A♣️, 2♣️, 2♠️
Discards: J♥️, 5♣️, 8♣️, 9♣️, 6♦️, Q♥️, 6♠️, 2♥️, 4♥️, 3♣️, 2♦️, 6♥️, J♣️
K♣️, Q♦️, 6♣️, 10♣️, K♥️, 4♦️, 4♣️, K♦️, 3♦️, J♠️, A♦️, 5♥️, 10♥️
 
Test 10: Assertion is true
Red pile: 5♥️, 3♠️, 2♣️, A♥️, 9♥️, 6♠️, 8♥️, 2♦️, 3♣️
Black pile: 8♦️, 2♠️, 4♦️, 6♦️, 6♥️, J♠️, J♥️, A♠️, 7♦️, 10♦️, 9♦️, 2♥️, K♦️, Q♠️, J♦️, A♦️, A♣️
Discards: 9♣️, J♣️, 5♠️, 7♣️, 10♣️, 8♣️, 10♠️, 3♥️, K♣️, 4♠️, Q♥️, 6♣️, 8♠️
7♠️, Q♦️, 9♠️, 3♦️, 5♣️, Q♣️, 7♥️, 5♦️, K♥️, 4♣️, 4♥️, K♠️, 10♥️"</lang>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">;==========================================================
; create cards
cards := [], suits := ["♠","♥","♦","♣"], num := 0
Line 361 ⟶ 334:
SB_SetText(countB " Face Down Black Cards", 2)
return
;==========================================================</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
Line 494 ⟶ 467:
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 519 ⟶ 492:
 
Result: 5 successes out of 5 simulations</pre>
 
 
=={{header|C#}}==
{{trans|Java}}
<syntaxhighlight lang="C#">
using System;
using System.Collections.Generic;
using System.Linq;
 
public class MindBogglingCardTrick
{
public static void Main(string[] args)
{
List<char> cards = new List<char>();
cards.AddRange(Enumerable.Repeat('R', 26));
cards.AddRange(Enumerable.Repeat('B', 26));
Shuffle(cards);
 
List<char> redPile = new List<char>();
List<char> blackPile = new List<char>();
List<char> discardPile = new List<char>();
 
for (int i = 0; i < 52; i += 2)
{
if (cards[i] == 'R')
{
redPile.Add(cards[i + 1]);
}
else
{
blackPile.Add(cards[i + 1]);
}
discardPile.Add(cards[i]);
}
 
Console.WriteLine("A sample run.\n");
Console.WriteLine("After dealing the cards the state of the piles is:");
Console.WriteLine($" Red : {redPile.Count} cards -> {string.Join(",", redPile)}");
Console.WriteLine($" Black : {blackPile.Count} cards -> {string.Join(",", blackPile)}");
Console.WriteLine($" Discard: {discardPile.Count} cards -> {string.Join(",", discardPile)}");
 
Random random = new Random();
int minimumSize = Math.Min(redPile.Count, blackPile.Count);
int choice = random.Next(1, minimumSize + 1);
 
List<int> redIndexes = Enumerable.Range(0, redPile.Count).ToList();
List<int> blackIndexes = Enumerable.Range(0, blackPile.Count).ToList();
Shuffle(redIndexes);
Shuffle(blackIndexes);
List<int> redChosenIndexes = redIndexes.Take(choice).ToList();
List<int> blackChosenIndexes = blackIndexes.Take(choice).ToList();
 
Console.WriteLine($"\nNumber of cards are to be swapped: {choice}");
Console.WriteLine("The respective zero-based indices of the cards to be swapped are:");
Console.WriteLine($" Red : {string.Join(", ", redChosenIndexes)}");
Console.WriteLine($" Black: {string.Join(", ", blackChosenIndexes)}");
 
for (int i = 0; i < choice; i++)
{
char temp = redPile[redChosenIndexes[i]];
redPile[redChosenIndexes[i]] = blackPile[blackChosenIndexes[i]];
blackPile[blackChosenIndexes[i]] = temp;
}
 
Console.WriteLine($"\nAfter swapping cards the state of the red and black piles is:");
Console.WriteLine($" Red : {string.Join(", ", redPile)}");
Console.WriteLine($" Black: {string.Join(", ", blackPile)}");
 
int redCount = redPile.Count(ch => ch == 'R');
int blackCount = blackPile.Count(ch => ch == 'B');
 
Console.WriteLine($"\nThe number of red cards in the red pile: {redCount}");
Console.WriteLine($"The number of black cards in the black pile: {blackCount}");
if (redCount == blackCount)
{
Console.WriteLine("So the assertion is correct.");
}
else
{
Console.WriteLine("So the assertion is incorrect.");
}
}
 
private static void Shuffle<T>(List<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
</syntaxhighlight>
{{out}}
<pre>
A sample run.
 
After dealing the cards the state of the piles is:
Red : 13 cards -> B,R,R,R,R,B,R,R,R,B,R,R,B
Black : 13 cards -> R,R,B,B,R,B,R,B,B,B,B,B,B
Discard: 26 cards -> R,R,B,R,B,R,R,B,R,B,R,R,B,B,R,B,R,B,B,B,B,B,R,B,R,R
 
Number of cards are to be swapped: 3
The respective zero-based indices of the cards to be swapped are:
Red : 9, 8, 1
Black: 1, 11, 5
 
After swapping cards the state of the red and black piles is:
Red : B, B, R, R, R, B, R, R, B, R, R, R, B
Black: R, B, B, B, R, R, R, B, B, B, B, R, B
 
The number of red cards in the red pile: 8
The number of black cards in the black pile: 8
So the assertion is correct.
 
</pre>
 
 
=={{header|C++}}==
<syntaxhighlight lang="c++">
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
 
template <typename T>
void print_vector(const std::vector<T>& list) {
std::cout << "[";
for ( uint64_t i = 0; i < list.size() - 1; ++i ) {
std::cout << list[i] << " ";
}
std::cout << list.back() << "]" << std::endl;
}
 
int main() {
std::vector<char> cards;
for ( int32_t i = 0; i < 26; ++i ) {
cards.emplace_back('R');
cards.emplace_back('B');
}
 
std::random_device rand;
std::mt19937 mersenne_twister(rand());
std::shuffle(cards.begin(), cards.end(), mersenne_twister);
 
std::vector<char> red_pile;
std::vector<char> black_pile;
std::vector<char> discard_pile;
 
for ( int32_t i = 0; i < 52; i += 2 ) {
if ( cards[i] == 'R' ) {
red_pile.emplace_back(cards[i + 1]);
} else {
black_pile.emplace_back(cards[i + 1]);
}
discard_pile.emplace_back(cards[i]);
}
 
std::cout << "A sample run." << "\n" << std::endl;
std::cout << "After dealing the cards the state of the piles is:" << std::endl;
std::cout << " Red : " << std::setw(2) << red_pile.size() << " cards -> "; print_vector<char>(red_pile);
std::cout << " Black : " << std::setw(2) << black_pile.size() << " cards -> "; print_vector<char>(black_pile);
std::cout << " Discard: " << std::setw(2) << discard_pile.size()
<< " cards -> "; print_vector<char>(discard_pile);
 
const int32_t minimum_size = std::min(red_pile.size(), black_pile.size());
std::uniform_int_distribution<int> uniform_random{ 1, minimum_size };
const int32_t choice = uniform_random(mersenne_twister);
 
std::vector<int32_t> red_indexes(red_pile.size());
std::iota(red_indexes.begin(), red_indexes.end(), 0);
std::vector<int32_t> black_indexes(black_pile.size());
std::iota(black_indexes.begin(), black_indexes.end(), 0);
 
std::shuffle(red_indexes.begin(), red_indexes.end(), mersenne_twister);
std::shuffle(black_indexes.begin(), black_indexes.end(), mersenne_twister);
 
std::vector<int32_t> red_chosen_indexes(red_indexes.begin(), red_indexes.begin() + choice);
std::vector<int32_t> black_chosen_indexes(black_indexes.begin(), black_indexes.begin() + choice);
 
std::cout << "\n" << "Number of cards are to be swapped: " << choice << std::endl;
std::cout << "The respective zero-based indices of the cards to be swapped are:" << std::endl;
std::cout << " Red : "; print_vector<int32_t>(red_chosen_indexes);
std::cout << " Black: "; print_vector<int32_t>(black_chosen_indexes);
 
for ( int32_t i = 0; i < choice; ++i ) {
const char temp = red_pile[red_chosen_indexes[i]];
red_pile[red_chosen_indexes[i]] = black_pile[black_chosen_indexes[i]];
black_pile[black_chosen_indexes[i]] = temp;
}
 
std::cout << "\n" << "After swapping cards the state of the red and black piles is:" << std::endl;
std::cout << " Red : "; print_vector<char>(red_pile);
std::cout << " Black: "; print_vector<char>(black_pile);
 
int32_t red_count = 0;
for ( const char& ch : red_pile ) {
if ( ch == 'R' ) {
red_count++;
}
}
 
int32_t black_count = 0;
for ( const char& ch : black_pile ) {
if ( ch == 'B' ) {
black_count++;
}
}
 
std::cout << "\n" << "The number of red cards in the red pile: " << red_count << std::endl;
std::cout << "The number of black cards in the black pile: " << black_count << std::endl;
if ( red_count == black_count ) {
std::cout << "So the assertion is correct." << std::endl;
} else {
std::cout << "So the assertion is incorrect." << std::endl;
}
}
</syntaxhighlight>
{{ out }}
<pre>
A sample run.
 
After dealing the cards the state of the piles is:
Red : 11 cards -> [R R B R R B R B B B R]
Black : 15 cards -> [B R B B R B R R R B B R R R R]
Discard: 26 cards -> [B B R B B B B R R B R R R R B B B R B R B B R B R B]
 
Number of cards are to be swapped: 11
The respective zero-based indices of the cards to be swapped are:
Red : [6 7 10 2 8 4 1 3 0 5 9]
Black: [2 9 11 12 0 7 3 6 8 14 10]
 
After swapping cards the state of the red and black piles is:
Red : [R B R R R R B B B B R]
Black: [B R R R R B R R R B B R B R B]
 
The number of red cards in the red pile: 6
The number of black cards in the black pile: 6
So the assertion is correct.
</pre>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">deck = ([:black, :red] * 26 ).shuffle
black_pile, red_pile, discard = [] of Symbol, [] of Symbol, [] of Symbol
 
Line 540 ⟶ 761:
puts "The magician predicts there will be #{black_pile.count( :black )} red cards in the other pile.
Drumroll...
There were #{red_pile.count( :red )}!"</langsyntaxhighlight>
{{out}}
<pre>The magician predicts there will be 7 red cards in the other pile.
Drumroll...
There were 7!
</pre>
 
=={{header|EasyLang}}==
{{trans|Wren}}
<syntaxhighlight>
proc shuffle . a[] .
for i = len a[] downto 2
r = randint i
swap a[r] a[i]
.
.
func$ a2str a[] .
for v in a[]
r$ &= strchar v & " "
.
return r$
.
R = strcode "R"
B = strcode "B"
for i to 26
pack[] &= R
pack[] &= B
.
shuffle pack[]
#
for i = 1 step 2 to 51
if pack[i] = B
black[] &= pack[i + 1]
else
red[] &= pack[i + 1]
.
discard[] &= pack[i]
.
print "After dealing the cards the state of the stacks is:"
print " Red : " & a2str red[]
print " Black : " & a2str black[]
print " Discard: " & a2str discard[]
for i to len red[]
rp[] &= i
.
for i to len black[]
bp[] &= i
.
shuffle rp[]
shuffle bp[]
n = randint lower len red[] len black[]
len rp[] n
len bp[] n
#
for i to n
h = red[rp[i]]
red[rp[i]] = black[bp[i]]
black[bp[i]] = h
.
print ""
print "After swapping " & n & " cards the state of the stacks is:"
print " Red : " & a2str red[]
print " Black : " & a2str black[]
#
for c in red[]
red += if c = R
.
for c in black[]
black += if c = B
.
print ""
print "The number of red cards in the red stack = " & red
print "The number of black cards in the black stack = " & black
if red = black
print "So the asssertion is correct!"
.
</syntaxhighlight>
{{out}}
<pre>
After dealing the cards the state of the stacks is:
Red : B B B R B B B R R R R R R B
Black : B B B R R B R B B R R B
Discard: R B R B B R B R R B B R R R R R R R R B B B B B R B
 
After swapping 7 cards the state of the stacks is:
Red : R R B R R B B R B R B R R B
Black : B B R B R B B B R B R B
 
The number of red cards in the red stack = 8
The number of black cards in the black stack = 8
So the asssertion is correct!
</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
//Be boggled? Nigel Galloway: September 19th., 2018
let N=System.Random()
Line 555 ⟶ 862:
printf "A well shuffled deck -> "; List.iter (printf "%s ") fN; printfn ""
fN |> List.chunkBySize 2 |> List.groupBy List.head |> List.iter(fun(n,n')->printfn "The %s pile contains %s" n (fG n'))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 564 ⟶ 871:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: accessors combinators.extras formatting fry
generalizations io kernel math math.ranges random sequences
sequences.extras ;
Line 616 ⟶ 923:
test-assertion ; ! step 4
 
MAIN: main</langsyntaxhighlight>
A run:
{{out}}
Line 669 ⟶ 976:
B in black: 5
</pre>
 
=={{header|FreeBASIC}}==
{{trans|XPL0}}
<syntaxhighlight lang="vbnet">Randomize Timer
Dim Shared As String Deck(52), BlackPile(52), RedPile(52), DiscardPile(52)
Dim Shared As Integer BlP, ReP, DiP
 
Sub Show
Dim As Integer i
Print "Black pile: ";
For i = 0 To BlP-1
Print BlackPile(i);
Next i
Print !"\nRed pile: ";
For i = 0 To ReP-1
Print RedPile(i);
Next i
Print !"\nDiscard pile: ";
For i = 0 To DiP-1
Print DiscardPile(i);
Next i
Print
End Sub
 
Dim As String BlackBunch(52), RedBunch(52)
Dim As Integer i, j, m, x, y, BB, RB, BC, RC
Dim As Integer ub = Ubound(Deck)
 
For i = 0 To (ub/2)-1
Deck(i) = "r"
Deck(i+26) = "b"
Next i
For i = 0 To ub-1
y = Int(Rnd * 51) + 1
Swap Deck(y), Deck(i)
Next i
BlP = 0
ReP = 0
DiP = 0
For i = 0 To ub-1
If Deck(i) = "b" Then
BlackPile(BlP) = Deck(i+1)
BlP += 1
Else
RedPile(ReP) = Deck(i+1)
ReP += 1
End If
DiscardPile(DiP) = Deck(i)
DiP += 1
i += 1
Next i
 
Show
m = BlP
If ReP < m Then m = ReP
x = Int(Rnd * m) + 1
Print "Swap "; x; " cards between the red and black piles."
RB = 0
BB = 0
For i = 0 To x-1
Do
y = Int(Rnd * ReP)
Loop Until RedPile(y) <> "0"
RedBunch(RB) = RedPile(y)
RB += 1
RedPile(y) = "0"
Next i
For i = 0 To x-1
Do
y = Int(Rnd * BlP)
Loop Until BlackPile(y) <> "0"
BlackBunch(BB) = BlackPile(y)
BB += 1
BlackPile(y) = "0"
Next i
RB = 0
For i = 0 To x-1
j = 0
While BlackPile(j) <> "0"
j += 1
Wend
BlackPile(j) = RedBunch(RB)
RB += 1
Next i
BB = 0
For i = 0 To x-1
j = 0
While RedPile(j) <> "0"
j += 1
Wend
RedPile(j) = BlackBunch(BB)
BB += 1
Next i
 
Show
BC = 0
For i = 0 To BlP-1
If BlackPile(i) = "b" Then BC += 1
Next i
RC = 0
For i = 0 To ReP-1
If RedPile(i) = "r" Then RC += 1
Next i
Print "The number of black cards in the black pile is "; BC
Print "The number of red cards in the red pile is "; RC
Print Using "The mathematician's assertion is &correct."; Iif(BC <>RC, "not ", "")
 
Sleep</syntaxhighlight>
{{out}}
<pre>Black pile: rbrbrrrrbrrrrb
Red pile: bbbbrrbrbbbr
Discard pile: bbrrbrrbbrbrrrrbrbbrbbrbbb
Swap 11 cards between the red and black piles.
Black pile: rbbrbrbbbbrbrb
Red pile: rrrrrrbbrrbr
Discard pile: bbrrbrrbbrbrrrrbrbbrbbrbbb
The number of black cards in the black pile is 9
The number of red cards in the red pile is 9
The mathematician's assertion is correct.</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 748 ⟶ 1,174:
fmt.Println("So the asssertion is incorrect!")
}
}</langsyntaxhighlight>
 
{{out}}
Line 796 ⟶ 1,222:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.Random (randomRIO)
import Data.List (partition)
import Data.Monoid ((<>))
Line 863 ⟶ 1,289:
replaceAt i c l =
let (a, b) = splitAt i l
in a ++ c : drop 1 b</langsyntaxhighlight>
{{Out}}
<pre>Discarded: RRRRRBBBBBRBBBRBBRBRRBRRRB
Line 875 ⟶ 1,301:
=={{header|J}}==
The trick verb returns 0 if the magician's proposition fails, otherwise 1.
<syntaxhighlight lang="j">
<lang J>
NB. A failed assertion looks like this
assert 0
|assertion failure: assert
| assert 0
</langsyntaxhighlight>
We find that in three runs the trick works.
<syntaxhighlight lang="j">
<lang J>
shuffle =: {~ ?~@:#
f =: (,&.> {:)~
Line 930 ⟶ 1,356:
black pile BrrBrrrBBrr
red pile rBrBrBBrBBBBBBB
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
 
public final class MindBogglingCardTrick {
 
public static void main(String[] aArgs) {
List<Character> cards = new ArrayList<Character>(52);
cards.addAll(Collections.nCopies(26, 'R'));
cards.addAll(Collections.nCopies(26, 'B'));
Collections.shuffle(cards);
List<Character> redPile = new ArrayList<Character>();
List<Character> blackPile = new ArrayList<Character>();
List<Character> discardPile = new ArrayList<Character>();
for ( int i = 0; i < 52; i += 2 ) {
if ( cards.get(i) == 'R' ) {
redPile.add(cards.get(i + 1));
} else {
blackPile.add(cards.get(i + 1));
}
discardPile.add(cards.get(i));
}
System.out.println("A sample run." + System.lineSeparator());
System.out.println("After dealing the cards the state of the piles is:");
System.out.println(String.format(" Red : %2d cards -> %s", redPile.size(), redPile));
System.out.println(String.format(" Black : %2d cards -> %s", blackPile.size(), blackPile));
System.out.println(String.format(" Discard: %2d cards -> %s", discardPile.size(), discardPile));
ThreadLocalRandom random = ThreadLocalRandom.current();
final int minimumSize = Math.min(redPile.size(), blackPile.size());
final int choice = random.nextInt(1, minimumSize + 1);
List<Integer> redIndexes = IntStream.range(0, redPile.size()).boxed().collect(Collectors.toList());
List<Integer> blackIndexes = IntStream.range(0, blackPile.size()).boxed().collect(Collectors.toList());
Collections.shuffle(redIndexes);
Collections.shuffle(blackIndexes);
List<Integer> redChosenIndexes = redIndexes.subList(0, choice);
List<Integer> blackChosenIndexes = blackIndexes.subList(0, choice);
 
System.out.println(System.lineSeparator() + "Number of cards are to be swapped: " + choice);
System.out.println("The respective zero-based indices of the cards to be swapped are:");
System.out.println(" Red : " + redChosenIndexes);
System.out.println(" Black: " + blackChosenIndexes);
for ( int i = 0; i < choice; i++ ) {
final char temp = redPile.get(redChosenIndexes.get(i));
redPile.set(redChosenIndexes.get(i), blackPile.get(blackChosenIndexes.get(i)));
blackPile.set(blackChosenIndexes.get(i), temp);
}
System.out.println(System.lineSeparator() + "After swapping cards the state of the red and black piles is:");
System.out.println(" Red : " + redPile);
System.out.println(" Black: " + blackPile);
int redCount = 0;
for ( char ch : redPile ) {
if ( ch == 'R' ) {
redCount += 1;
}
}
int blackCount = 0;
for ( char ch : blackPile ) {
if ( ch == 'B' ) {
blackCount += 1;
}
}
System.out.println(System.lineSeparator() + "The number of red cards in the red pile: " + redCount);
System.out.println("The number of black cards in the black pile: " + blackCount);
if ( redCount == blackCount ) {
System.out.println("So the assertion is correct.");
} else {
System.out.println("So the assertion is incorrect.");
}
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
A sample run.
 
After dealing the cards the state of the piles is:
Red : 11 cards -> [B, R, R, R, B, B, R, R, B, R, B]
Black : 15 cards -> [R, R, R, R, R, R, B, R, R, B, B, R, B, B, B]
Discard: 26 cards -> [R, B, B, B, R, B, R, R, R, B, B, B, B, B, R, B, B, B, R, R, R, R, R, B, B, B]
 
Number of cards are to be swapped: 6
The respective zero-based indices of the cards to be swapped are:
Red : [4, 5, 6, 9, 0, 2]
Black: [1, 4, 10, 7, 3, 0]
 
After swapping cards the state of the red and black piles is:
Red : [R, R, R, R, R, R, B, R, B, R, B]
Black: [R, B, R, B, B, R, B, R, R, B, R, R, B, B, B]
 
The number of red cards in the red pile: 8
The number of black cards in the black pile: 8
So the assertion is correct.
</pre>
 
=={{header|Javascript}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,095 ⟶ 1,631:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Discarded: BRBRBRRRRBBBRBBBRBBBBBRRBR
Line 1,104 ⟶ 1,640:
BBBBBBBB = Black cards in the black pile
true</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
 
'''Works with jq, the C implementation of jq'''
 
'''Works with gojq, the Go implementation of jq'''
 
Since jq does not include a PRN generator, an external source of entropy such as /dev/urandom is assumed.
A suitable invocation of jq would be along the lines of:
<pre>
< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -nr trick.jq
</pre>
<syntaxhighlight lang="jq">
### Generic utilities
def count(s): reduce s as $x (0; . + 1);
 
def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .;
 
 
### Pseuo-random numbers
 
# Output: a prn in range(0;$n) where $n is `.`
def prn:
if . == 1 then 0
else . as $n
| ([1, (($n-1)|tostring|length)]|max) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
 
def sample:
if length == 0 # e.g. null or []
then null
else .[length|prn]
end;
 
def knuthShuffle:
length as $n
| if $n <= 1 then .
else {i: $n, a: .}
| until(.i == 0;
.i += -1
| (.i + 1 | prn) as $j
| .a[.i] as $t
| .a[.i] = .a[$j]
| .a[$j] = $t)
| .a
end;
 
 
### Cards
 
def R: "R"; # 82 ASCII
def B: "B"; # 66 ASCII
 
# Create deck, half red, half black and shuffle it.
def deck:
([range(0;26)|R] + [range(0;26)|B]) | knuthShuffle;
 
# Deal from `deck` into three stacks: {black, red, discard}
def deal:
deck as $deck
| reduce range(0; 51; 2) as $i (.;
if $deck[$i] == B
then .black += [$deck[$i+1]]
else .red += [$deck[$i+1]]
end
| .discard += [$deck[$i]] );
 
def proceed:
def p: join(" ");
(.red|length) as $lr
| (.black|length) as $lb
| (.discard|length) as $ld
 
| def displayStacks($discard):
" Red : \($lr|lpad(2)) cards -> \(.red|p)",
" Black : \($lb|lpad(2)) cards -> \(.black|p)",
(select($discard)
| " Discard: \($ld) cards -> \(.discard|p)") ;
 
# Input: {red, black}
def swap($n):
. + { rp: ([range(0; $lr)] | knuthShuffle[0:$n] ),
bp: ([range(0; $lb)] | knuthShuffle[0:$n]) }
| reduce range(0;$n) as $i (.;
.red[.rp[$i]] as $t
| .red[.rp[$i]] = .black[.bp[$i]]
| .black[.bp[$i]] = $t);
 
def epilog:
# Check that the number of black cards in the black stack equals
# the number of red cards in the red stack:
count(select(.red[] == R)) as $rcount
| count(select(.black[] == B)) as $bcount
| "\nThe number of red cards in the red stack = \($rcount)",
"The number of black cards in the black stack = \($bcount)",
if $rcount == $bcount
then "So the assertion is correct!"
else "So the assertion is incorrect!"
end;
 
"After dealing the cards, the stacks are as follows:",
displayStacks(true),
# Swap the same, random, number of cards between the red and black stacks.
( (if $lr < $lb then $lr else $lb end) as $min
| (($min - 1|prn) + 1) as $n
| swap($n)
| "\n\($n) card(s) are to be swapped.",
"The respective zero-based indices of the cards to be swapped are:",
" Red : \(.rp|map(lpad(3))|p)",
" Black : \(.bp|map(lpad(3))|p)",
"\nAfter swapping, the red and black stacks are as follows:",
displayStacks(false),
epilog ) ;
 
deal | proceed
</syntaxhighlight>
{{output}}
<pre>
After dealing the cards, the stacks are as follows:
Red : 12 cards -> R B R R B B B R R B R B
Black : 14 cards -> R B B R B R R R B R B R B R
Discard: 26 cards -> R R B B B R B R B R R B B B R B R B R B B B R B R R
 
1 card(s) are to be swapped.
The respective zero-based indices of the cards to be swapped are:
Red : 6
Black : 5
 
After swapping, the red and black stacks are as follows:
Red : 12 cards -> R B R R B B R R R B R B
Black : 14 cards -> R B B R B B R R B R B R B R
 
The number of red cards in the red stack = 7
The number of black cards in the black stack = 7
So the assertion is correct!
</pre>
 
=={{header|Julia}}==
{{trans|Raku}}
<syntaxhighlight lang="julia">using Random
<lang julia>const rbdeck = split(repeat('R', 26) * repeat('B', 26), "")
 
const rbdeck = split(repeat('R', 26) * repeat('B', 26), "")
shuffledeck() = shuffle(rbdeck)
 
Line 1,158 ⟶ 1,836:
mindbogglingcardtrick(false)
end
</langsyntaxhighlight>{{output}}<pre>
Shuffled deck is: SubString{String}["B", "B", "R", "B", "B", "R", "B", "R", "B", "R", "B", "B", "B", "R", "B", "R", "R", "B", "R", "R",
"R", "R", "R", "R", "B", "R", "B", "B", "B", "R", "R", "B", "B", "R", "B", "B", "R", "R", "B", "R", "R", "R", "R", "B", "B", "R", "B",
Line 1,197 ⟶ 1,875:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">// Version 1.2.61
 
import java.util.Random
Line 1,258 ⟶ 1,936:
println("So the asssertion is incorrect!")
}
}</langsyntaxhighlight>
 
{{output}}
Line 1,304 ⟶ 1,982:
So the asssertion is correct!
</pre>
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">-- support:
function T(t) return setmetatable(t, {__index=table}) end
table.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end
table.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end
table.filter = function(t,f) local s=T{} for i=1,#t do if f(t[i]) then s[#s+1]=t[i] end end return s end
table.clone = function(t) local s=T{} for k,v in ipairs(t) do s[k]=v end return s end
table.head = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end
table.tail = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[#t-n+i] end return s end
table.append = function(t,v) local s=t:clone() for i=1,#v do s[#s+1]=v[i] end return s end
table.shuffle = function(t) for i=#t,2,-1 do local j=math.random(i) t[i],t[j]=t[j],t[i] end return t end -- inplace!
 
-- task:
function cardtrick()
-- 1.
local deck = T{}:range(52):map(function(v) return v%2==0 and "B" or "R" end):shuffle()
print("1. DECK : " .. deck:concat())
-- 2. (which guarantees the outcome)
local bpile, rpile, discs = T{}, T{}, T{}
local xpile = {B=bpile, R=rpile}
while #deck>0 do
local card, next = deck:remove(), deck:remove()
xpile[card]:insert(next)
discs:insert(card)
end
print("2. BLACK PILE: " .. bpile:concat())
print("2. RED PILE : " .. rpile:concat())
print("2. DISCARDS : " .. discs:concat())
-- 3. (which cannot change the outcome)
local x = math.random(0, math.min(#bpile, #rpile))
local btake, rtake = T{}, T{}
for i = 1, x do
btake:insert((bpile:remove(math.random(#bpile))))
rtake:insert((rpile:remove(math.random(#rpile))))
end
print("3. SWAPPING X: " .. x)
print("3. BLACK SWAP: keep:" .. bpile:concat() .. " take:" .. btake:concat())
print("3. RED SWAP : keep:" .. rpile:concat() .. " take:" .. rtake:concat())
bpile, rpile = bpile:append(rtake), rpile:append(btake)
print("3. BLACK PILE: " .. bpile:concat())
print("3. RED PILE : " .. rpile:concat())
-- 4. ("proving" that which was guaranteed earlier)
local binb, rinr = bpile:filter(function(v) return v=="B" end), rpile:filter(function(v) return v=="R" end)
print("4. BLACK PILE: contains " .. #binb .. " B's")
print("4. RED PILE : contains " .. #rinr .. " R's")
print(#binb==#rinr and "VERIFIED" or "NOT VERIFIED")
print()
end
 
-- demo:
math.randomseed(os.time())
for i = 1,3 do cardtrick() end</syntaxhighlight>
{{out}}
<pre>1. DECK : RBBBRBRBRBBBBRRRRBRBBBRRBRRBRRBRBBRRBBRRBBRRRBBRBRBR
2. BLACK PILE: RBBBRBRRBRRRBR
2. RED PILE : BBBRRRBRBRRB
2. DISCARDS : RRRBRBRBRBRRBRRBBBRRBBBBBB
3. SWAPPING X: 3
3. BLACK SWAP: keep:RBBRBRRRRBR take:BBR
3. RED SWAP : keep:BBRRBRBRR take:RBB
3. BLACK PILE: RBBRBRRRRBRRBB
3. RED PILE : BBRRBRBRRBBR
4. BLACK PILE: contains 6 B's
4. RED PILE : contains 6 R's
VERIFIED
 
1. DECK : BRBBRRRRRBRBBRRBRRRRRBRBRBBBBBBRRRRBBRBBRBBRRBBBRBBR
2. BLACK PILE: RBRRBRBBRRRRRRB
2. RED PILE : BBBRBRRBRRB
2. DISCARDS : RBBBRBBRBRRBBBBBRRBRBBRRBR
3. SWAPPING X: 1
3. BLACK SWAP: keep:RRRBRBBRRRRRRB take:B
3. RED SWAP : keep:BBBRBRBRRB take:R
3. BLACK PILE: RRRBRBBRRRRRRBR
3. RED PILE : BBBRBRBRRBB
4. BLACK PILE: contains 4 B's
4. RED PILE : contains 4 R's
VERIFIED
 
1. DECK : BBRRRBBBBRBBRBBBRBRRRRRRBBRRRBRRBRRRRBRBBBRBBBBRBRBR
2. BLACK PILE: BRBRRRBRBRBBRB
2. RED PILE : BBBRBRRRRRBR
2. DISCARDS : RRRBBBBBRRRBRBRRRBBBBRBBRB
3. SWAPPING X: 5
3. BLACK SWAP: keep:BBRBRBBRB take:RBRRR
3. RED SWAP : keep:BRBRRBR take:BRRBR
3. BLACK PILE: BBRBRBBRBBRRBR
3. RED PILE : BRBRRBRRBRRR
4. BLACK PILE: contains 8 B's
4. RED PILE : contains 8 R's
VERIFIED</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">s = RandomSample@Flatten[{Table[0, 26], Table[1, 26]}]
g = Take[s, {1, -1, 2}]
d = Take[s, {2, -1, 2}]
Line 1,321 ⟶ 2,091:
finala = Join[a[[1]], b[[2]]]
finalb = Join[b[[1]], a[[2]]]
Count[finala, 1] == Count[finalb, 0]</langsyntaxhighlight>
 
{{output}}
Line 1,343 ⟶ 2,113:
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight Nimlang="nim">import random, sequtils, strformat, strutils
 
type Color {.pure.} = enum Red = "R", Black = "B"
Line 1,395 ⟶ 2,165:
echo "So the asssertion is correct."
else:
echo "So the asssertion is incorrect."</langsyntaxhighlight>
 
{{out}}
Line 1,420 ⟶ 2,190:
Trying several non-random deck orderings, in addition to a shuffled one. Predictably, the trick always works.
{{trans|Raku}}
<langsyntaxhighlight lang="perl">sub trick {
my(@deck) = @_;
my $result .= sprintf "%-28s @deck\n", 'Starting deck:';
Line 1,463 ⟶ 2,233:
print trick(@deck);
@deck = sort { -1 + 2*int(rand 2) } @deck; # poor man's shuffle
print trick(@deck);</langsyntaxhighlight>
{{out}}
<pre>Starting deck: R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B R B
Line 1,494 ⟶ 2,264:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant n = 52,
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
pack = shuffle(repeat('r',n/2)&repeat('b',n/2))
<span style="color: #008080;">constant</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">52</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">pack</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'r'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'b'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">))</span>
string {black, red, discard} @= ""
for i=1 to length(pack) by 2 do
<span style="color: #004080;">string</span> <span style="color: #000000;">black</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">red</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">discard</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
integer {top,next} = pack[i..i+1]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pack</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
if top=='b' then
<span style="color: #004080;">integer</span> <span style="color: #000000;">top</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pack</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span>
black &= next
<span style="color: #000000;">next</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pack</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
else
<span style="color: #008080;">if</span> <span style="color: #000000;">top</span><span style="color: #0000FF;">==</span><span style="color: #008000;">'b'</span> <span style="color: #008080;">then</span>
red &= next
<span style="color: #000000;">black</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">next</span>
end if
<span style="color: #008080;">else</span>
discard &= top
<span style="color: #000000;">red</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">next</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
black = shuffle(black); red = shuffle(red) -- (optional)
<span style="color: #000000;">discard</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">top</span>
--printf(1,"Discards : %s\n",{discard})
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #000000;">black</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">black</span><span style="color: #0000FF;">);</span> <span style="color: #000000;">red</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">red</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (optional)
printf(1,"Reds : %s\nBlacks : %s\n\n",{red,black})
--printf(1,"Discards : %s\n",{discard})</span>
 
integer lb = length(black), lr = length(red),
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Reds : %s\nBlacks : %s\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">red</span><span style="color: #0000FF;">,</span><span style="color: #000000;">black</span><span style="color: #0000FF;">})</span>
ns = rand(min(lb,lr))
printf(1,"Swap %d cards:\n\n", ns)
<span style="color: #004080;">integer</span> <span style="color: #000000;">lb</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">black</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">lr</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">red</span><span style="color: #0000FF;">),</span>
{black[1..ns],red[1..ns]} = {red[1..ns],black[1..ns]}
<span style="color: #000000;">ns</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">lb</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lr</span><span style="color: #0000FF;">))</span>
 
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Swap %d cards:\n\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ns</span><span style="color: #0000FF;">)</span>
printf(1,"Reds : %s\nBlacks : %s\n\n",{red,black})
<span style="color: #004080;">string</span> <span style="color: #000000;">b1ns</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">black</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">ns</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">r1ns</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">red</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">ns</span><span style="color: #0000FF;">]</span>
integer nb = sum(sq_eq(black,'b')),
<span style="color: #000000;">black</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">ns</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r1ns</span>
nr = sum(sq_eq(red,'r'))
<span style="color: #000000;">red</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">ns</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">b1ns</span>
string correct = iff(nr==nb?"correct":"**INCORRECT**")
printf(1,"%d r in red, %d b in black - assertion %s\n",{nr,nb,correct})</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Reds : %s\nBlacks : %s\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">red</span><span style="color: #0000FF;">,</span><span style="color: #000000;">black</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">nb</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">black</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'b'</span><span style="color: #0000FF;">)),</span>
<span style="color: #000000;">nr</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_eq</span><span style="color: #0000FF;">(</span><span style="color: #000000;">red</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'r'</span><span style="color: #0000FF;">))</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">correct</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">nr</span><span style="color: #0000FF;">==</span><span style="color: #000000;">nb</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"correct"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"**INCORRECT**"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d r in red, %d b in black - assertion %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">nr</span><span style="color: #0000FF;">,</span><span style="color: #000000;">nb</span><span style="color: #0000FF;">,</span><span style="color: #000000;">correct</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,538 ⟶ 2,315:
=={{header|Python}}==
The code is layed out to follow the task decription, leading to some deviations from the PEP8 ''guidelines''
<langsyntaxhighlight lang="python">import random
 
## 1. Cards
Line 1,586 ⟶ 2,363:
print('Yeha! The mathematicians assertion is correct.')
else:
print('Whoops - The mathematicians (or my card manipulations) are flakey')</langsyntaxhighlight>
 
A run.
Line 1,601 ⟶ 2,378:
Swapping 2
Yeha! The mathematicians assertion is correct.</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ stack ] is discards ( --> s )
[ stack ] is red-card ( --> s )
[ stack ] is black-card ( --> s )
 
[ dup take rot join swap put ] is to-pile ( n s --> )
 
[ $ "" discards put
$ "" red-card put
$ "" black-card put
char R 26 of
char B 26 of join shuffle
26 times
[ behead tuck discards to-pile
behead rot char R =
iff red-card else black-card
to-pile ]
drop
discards take witheach
[ emit sp ] cr
red-card take shuffle
black-card take shuffle
over size over size min random
say "Swapping " dup echo
say " cards." cr
dup dip [ split rot ] split
dip join rot join
0 swap witheach
[ char R = + ]
0 rot witheach
[ char B = + ]
say "The assertion is "
= iff [ say "true." ]
else [ say "false." ] cr cr ] is task ( --> )
 
5 times task</syntaxhighlight>
 
{{out}}
 
<pre>B R R R B B R B B B R R B R R B B B R B B R B R R B
Swapping 2 cards.
The assertion is true.
 
B R B R B B B B R B B B R R R R B B R R B R B B B B
Swapping 4 cards.
The assertion is true.
 
B B R R R B R B B R B R R B R B R B B B R B R R B R
Swapping 3 cards.
The assertion is true.
 
B B B R R R R R B R B B R B R B B R R R R R R R B B
Swapping 8 cards.
The assertion is true.
 
B R B B B R R R R R B R B B R R B B B R R R R R B R
Swapping 5 cards.
The assertion is true.</pre>
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
magictrick<-function(){
deck=c(rep("B",26),rep("R",26))
Line 1,643 ⟶ 2,480:
}
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,666 ⟶ 2,503:
{{works with|Rakudo|2018.08}}
 
<syntaxhighlight lang="raku" perl6line># Generate a shuffled deck
my @deck = shuffle;
put 'Shuffled deck: ', @deck;
Line 1,712 ⟶ 2,549:
@r[@ri] = @bs;
@b[@bi] = @rs;
}</langsyntaxhighlight>
{{out|Sample output}}
<pre>Shuffled deck: B B B R B R R R B B R R R B R B R B R R R B R B B R R B B R R B R B R R R R B R R B B B B B B R R B B B
Line 1,745 ⟶ 2,582:
Extra coding was added to keep ''singularities'' &nbsp; (opposite of a plural) &nbsp; to keep the English gooder (''sic''), &nbsp; as well as
<br>adding commas to larger numbers.
<langsyntaxhighlight lang="rexx">/*REXX pgm mimics a boggling card trick; separates cards into 3 piles based on color ···*/
parse arg trials # shuffs seed . /*obtain optional arguments from the CL*/
if trials=='' | trials=="," then trials= 1000 /*Not specified? Then use the default.*/
Line 1,794 ⟶ 2,631:
/*"blacks" " " " */ Bc= Bc word(B, B?); B= delword(B, B?, 1) /* " " */
end /*?($)*/
R=R Bc; B=B Rc; return /*add swapped cards to piles.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 1,801 ⟶ 2,638:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">deck = ([:black, :red] * 26 ).shuffle
black_pile, red_pile, discard = [], [], []
 
Line 1,820 ⟶ 2,657:
Drumroll...
There were #{red_pile.count( :red )}!"
</syntaxhighlight>
</lang>
{{out}}
<pre>The magician predicts there will be 5 red cards in the other pile.
Line 1,829 ⟶ 2,666:
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">extern crate rand; // 0.5.5
use rand::Rng;
use std::iter::repeat;
Line 1,888 ⟶ 2,725:
println!("Number of black cards in black stack: {}", num_black);
println!("Number of red cards in red stack: {}", num_red);
}</langsyntaxhighlight>
 
{{out}}
Line 1,899 ⟶ 2,736:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "./fmt" for Fmt
 
var R = 82 // ASCII 'R'
Line 1,970 ⟶ 2,807:
} else {
System.print("So the asssertion is incorrect!")
}</langsyntaxhighlight>
 
{{out}}
Line 1,992 ⟶ 2,829:
The number of black cards in the black stack = 4
So the asssertion is correct!
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">include xpllib; \for Print
 
char Deck(52), BlackPile(52), RedPile(52), DiscardPile(52),
BlackBunch(52), RedBunch(52);
int I, J, T, M, X, Y, BP, RP, DP, BB, RB, BC, RC;
 
proc Show;
[Print("Black pile: ");
for I:= 0 to BP-1 do ChOut(0, BlackPile(I));
Print("\nRed pile: ");
for I:= 0 to RP-1 do ChOut(0, RedPile(I));
Print("\nDiscard pile: ");
for I:= 0 to DP-1 do ChOut(0, DiscardPile(I));
Print("\n");
];
 
[for I:= 0 to 26-1 do
[Deck(I):= ^r; Deck(I+26):= ^b];
for I:= 0 to 52-1 do
[Y:= Ran(52); \0..51
T:= Deck(I); Deck(I):= Deck(Y); Deck(Y):= T;
];
BP:= 0; RP:= 0; DP:= 0;
for I:= 0 to 52-1 do
[if Deck(I) = ^b then
[BlackPile(BP):= Deck(I+1); BP:= BP+1]
else
[RedPile (RP):= Deck(I+1); RP:= RP+1];
DiscardPile(DP):= Deck(I); DP:= DP+1;
I:= I+1;
];
Show;
M:= BP;
if RP < M then M:= RP;
X:= Ran(M) + 1;
Print("Swap %d cards between the red and black piles.\n", X);
RB:= 0; BB:= 0;
for I:= 0 to X-1 do
[repeat Y:= Ran(RP); until RedPile(Y) # 0;
RedBunch(RB):= RedPile(Y); RB:= RB+1; RedPile(Y):= 0;
];
for I:= 0 to X-1 do
[repeat Y:= Ran(BP); until BlackPile(Y) # 0;
BlackBunch(BB):= BlackPile(Y); BB:= BB+1; BlackPile(Y):= 0;
];
RB:= 0;
for I:= 0 to X-1 do
[J:= 0;
while BlackPile(J) # 0 do J:= J+1;
BlackPile(J):= RedBunch(RB); RB:= RB+1;
];
BB:= 0;
for I:= 0 to X-1 do
[J:= 0;
while RedPile(J) # 0 do J:= J+1;
RedPile(J):= BlackBunch(BB); BB:= BB+1;
];
Show;
BC:= 0;
for I:= 0 to BP-1 do
if BlackPile(I) = ^b then BC:= BC+1;
RC:= 0;
for I:= 0 to RP-1 do
if RedPile(I) = ^r then RC:= RC+1;
Print("The number of black cards in the black pile is %d.\n", BC);
Print("The number of red cards in the red pile is %d.\n", RC);
Print("The mathematician's assertion is%s correct.\n",
if BC#RC then " not" else "");
]</syntaxhighlight>
{{out}}
<pre>
Black pile: rrrrrbbbrbbbr
Red pile: brrrbbbrrrbbb
Discard pile: brrrrrbbbbrbrrbrbbrbbrbrbr
Swap 11 cards between the red and black piles.
Black pile: bbrrbbbbrbrbr
Red pile: brbrrrrrbrbbr
Discard pile: brrrrrbbbbrbrrbrbbrbbrbrbr
The number of black cards in the black pile is 8.
The number of red cards in the red pile is 8.
The mathematician's assertion is correct.
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">cards:=[1..52].pump(List,"isEven","toInt").shuffle(); // red==1
stacks:=T(List(),List()); // black stack [0], red stack [1]
blkStk,redStk := stacks;
Line 2,012 ⟶ 2,933:
else println("Boo, different stack lenghts");
 
fcn redBlack(cards){ cards.pump(String,fcn(c){ c and "R " or "B " }) }</langsyntaxhighlight>
{{out}}
<pre>
2,489

edits