How to resolve the algorithm Mind boggling card trick step by step in the Perl programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Mind boggling card trick step by step in the Perl programming language

Table of Contents

Problem Statement

Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics the steps shown in the video.

(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.) Show output on this page.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Mind boggling card trick step by step in the Perl programming language

Source code in the perl programming language

sub trick {
    my(@deck) = @_;
    my $result .= sprintf "%-28s @deck\n", 'Starting deck:';

    my(@discard, @red, @black);
    deal(\@deck, \@discard, \@red, \@black);

    $result .= sprintf "%-28s @red\n", 'Red     pile:';
    $result .= sprintf "%-28s @black\n", 'Black   pile:';

    my $n = int rand(+@red < +@black ? +@red : +@black);
    swap(\@red, \@black, $n);

    $result .= sprintf "Red pile   after %2d swapped: @red\n", $n;
    $result .= sprintf "Black pile after %2d swapped: @black\n", $n;

    $result .= sprintf "Red in Red, Black in Black:  %d = %d\n", (scalar grep {/R/} @red), scalar grep {/B/} @black;
    return "$result\n";
}

sub deal {
    my($c, $d, $r, $b) = @_;
    while (@$c) {
        my $top = shift @$c;
        if ($top eq 'R') { push @$r, shift @$c }
        else             { push @$b, shift @$c }
        push @$d, $top;
    }
}

sub swap {
    my($r, $b, $n) = @_;
    push @$r, splice @$b, 0, $n;
    push @$b, splice @$r, 0, $n;
}

@deck = split '', 'RB' x 26;               # alternating red and black
print trick(@deck);
@deck = split '', 'RRBB' x 13;             # alternating pairs of reds and blacks
print trick(@deck);
@deck = sort @deck;                        # all blacks precede reds
print trick(@deck);
@deck = sort { -1 + 2*int(rand 2) } @deck; # poor man's shuffle
print trick(@deck);


  

You may also check:How to resolve the algorithm 99 bottles of beer step by step in the Intercal programming language
You may also check:How to resolve the algorithm Sort an array of composite structures step by step in the Ruby programming language
You may also check:How to resolve the algorithm Variable size/Set step by step in the 8086 Assembly programming language
You may also check:How to resolve the algorithm Read a configuration file step by step in the Python programming language
You may also check:How to resolve the algorithm Interactive programming (repl) step by step in the MATLAB / Octave programming language