    Dim deckCards(52)
    Dim holdCards(1, 1)
Print "The Sorted Deck"
    Call sortDeck
    Call dealDeck
Print: Print
Print "The Shuffled Deck"
    Call shuffleDeck
    Call dealDeck
Print: Print
    nPlayers = 4
    nCards = 5
    ct = 0
    Redim holdCards(nPlayers, nCards)
Print "Dealing ";nCards;" cards to ";nPlayers;" players"
    For i = 1 to nPlayers
        Print "Player #";i,,
    Next i
    Print
    For i = 1 to nCards
        For j = 1 to nPlayers
            ct = ct + 1
            holdCards(j, i) = deckCards(ct)
            card = deckCards(ct)
            value = value(card)
            suit$ = suit$(card)
            pip$ = pip$(value)
            Print card;": ";pip$;" of ";suit$,
        Next j
        Print
    Next i
Print: Print
    Print "The cards in memory / array"
    For i = 1 to nPlayers
        Print "Player #";i;" is holding"
        For j = 1 to nCards
            card = holdCards(i, j)
            value = value(card)
            suit$ = suit$(card)
            pip$ = pip$(value)
            Print card;": ";pip$;" of ";suit$
        Next j
        Print
    Next i

End

Sub dealDeck
    For i = 1 to 52
        card = deckCards(i)
        value = value(card)
        suit$ = suit$(card)
        pip$ = pip$(value)
        Print i, card, value, pip$;" of ";suit$
    Next i
End Sub

Sub sortDeck
    For i = 1 to 52
        deckCards(i) = i
    Next i
End Sub

Sub shuffleDeck
    For i = 52 to 1 Step -1
        x = Int(Rnd(1) * i) + 1
        temp = deckCards(x)
        deckCards(x) = deckCards(i)
        deckCards(i) = temp
    Next i
End Sub

Function suit$(deckValue)
    cardSuit$ = "Spades Hearts Clubs Diamonds"
    suit = Int(deckValue / 13)
    If deckValue Mod 13 = 0 Then
        suit = suit - 1
    End If
    suit$ = Word$(cardSuit$, suit + 1)
End Function

Function value(deckValue)
    value = deckValue Mod 13
    If value = 0 Then
        value = 13
    End If
End Function

Function pip$(faceValue)
    pipLabel$ = "Ace Deuce Three Four Five Six Seven Eight Nine Ten Jack Queen King"
    pip$ = Word$(pipLabel$, faceValue)
End Function


make "suits {Diamonds Hearts Clubs Spades}
make "pips {Ace Two Three Four Five Six Seven Eight Nine Ten Jack Queen King}

to card :n
  output (sentence item 1 + modulo :n 13 :pips  "of  item 1 + int quotient :n 13 :suits)
end

to new.deck
  make "deck listtoarray iseq 0 51
  make "top 1
end

to swap :i :j :a
  localmake "t item :i :a
  setitem :i :a item :j :a
  setitem :j :a :t
end
to shuffle.deck
  for [i [count :deck] 2] [swap 1 + random :i :i :deck]
end

to show.deck
  for [i :top [count :deck]] [show card item :i :deck]
end

to deal.card
  show card item :top :deck
  make "top :top + 1
end

new.deck
shuffle.deck
repeat 5 [deal.card]


suits = {"Clubs", "Diamonds", "Hearts", "Spades"}
faces = {2,3,4,5,6,7,8,9,10,"Jack","Queen","King","Ace"}
--a stack is a set of cards. a stack of length 1 acts as a card; the stack constructor only creates decks.

stack = setmetatable({
--shuffles a stack
__unm = function(z)
  local ret = {}
  for i = #z, 1, -1 do
    ret[#ret + 1] = table.remove(z,math.random(i))
  end
  return setmetatable(ret, stack)
end,
--puts two stacks together
__add = function(z, z2)
  for i = 1, #z2 do
    z[#z+1] = table.remove(z2)
  end
  return z
end,
--removes n cards from a stack and returns a stack of those cards
__sub = function(z, n)
  local ret = {}
  for i = 1, n do
    ret[i] = table.remove(z)
  end
  return setmetatable(ret, stack)
end,
--breaks a stack into n equally sized stacks and returns them all
deal = function(z, n)
  local ret = {}
  for i = 1, #z/n do
    ret[i] = table.remove(z)
  end
  if n > 1 then return setmetatable(ret, stack), stack.deal(z,n-1)
  else return setmetatable(ret, stack)
  end
end,
--returns a and b as strings, concatenated together. Simple enough, right?
__concat = function(a, b)
  if getmetatable(a) == stack then
    return stack.stackstring(a) .. b
  else
    return a .. stack.stackstring(b)
  end
end,
stackstring = function(st, ind)
    ind = ind or 1
	if not st[ind] then return "" end
	return st[ind] and (faces[math.ceil(st[ind]/4)] .. " of " .. suits[st[ind]%4+1] .. "\n" .. stack.stackstring(st, ind+1)) or ""
end}, {
--creates a deck
__call = function(z)
  local ret = {}
  for i = 1, 52 do ret[i] = i end
  return -setmetatable(ret,z)
end})

print(stack() .. "\n")
a, b, c, d = stack.deal(stack(), 4)
print(a .. "\n\n\n")
print(b + c .. "\n\n\n")
print(d - 4 .. "")
print(-b .. "")


Module PlayCards {
      Font "Arial"  ' Ensure characters exist for Suits
      Cls 15,0
      Pen 0
      Inventory Suits = "♠":=0, "♥":=4, "♦":=4, "♣":=0 'suit -> color
      Inventory Cards = "two":=2, "three":=3, "four":=4, "five":=5
      Append Cards, "six":=6, "seven":=7, "eight":=8, "nine":=9
      Append Cards, "ten":=10, "jack":=10, "queen":=10, "king":=10, "ace":=1
      DealerMoney=0
      PrintCardOnly = Lambda Suits, Cards (k, nl=True)-> {
                For k {
                      Pen Suits(.suit!) {
                              If nl then {
                                    Print Part @(10), Eval$(Suits, .suit)+Eval$(Cards, .card)
                                    Print
                              } Else Print Eval$(Suits, .suit)+Eval$(Cards, .card),
                         }
              }
      }
      ' Using a stack object
      StackPack = Stack
      Module AppendArray (N, A) {
            Stack N {Data !A}
      }
      Class OneCard {
            suit=-1, Card
      Class:
           Module OneCard {
                 \\ ? for optional reading
                 read ? .suit, .card
           }
      }
      Decks=1
      Dim Pack(Len(Cards)*Len(Suits)*Decks)
      k=0
      \\ fill cards to Pack()
      For times=1 To Decks {
            N=each(Suits)
            While N {
                  M=each(Cards)
                  While M {
                        Pack(k)=OneCard(N^, M^)
                        k++
                  }
            }
      }
      DisplayAll() ' in order
      Suffle()
      DisplayAll() ' at random positions
      Print
      Card=OneCard()
      Print "Cards in Deck:";Len(StackPack)
      For i=1 to 60 {
            NextCard()
            Print "Get Card:";
            Call PrintCardOnly(Card)
            Print
            Print "Cards in Deck:";Len(StackPack)
            DisplayDeck()
            Print
      }

      Sub Suffle()
            Print
            Local N=Len(Pack())-1, N2, i, j, total=N*4+4, cur=1
            For j=1 To 4 {
                  For i=0 To N {
                        If cur Mod 4=3 Then Print Over format$("Suffle {0:0}%",cur/total*100)
                        N2=random(0, N)
                        While N2=i {N2=random(0, N)}
                        Swap Pack(i), Pack(N2)
                        cur++
                  }
            }
            AppendArray StackPack, Pack()
            Print
      End Sub
      Sub DisplayDeck()
            local m=each(StackPack)
            While m  {
                      Call PrintCardOnly(StackItem(m), False)
            }
      End Sub
      Sub DisplayAll()
            For k=0 To Len(Pack())-1 {
                  PrintCard(k)
            }
      End Sub
      Sub PrintCard(k)
            For Pack(k) {
                  Pen Suits(.suit!) {
                        Print Eval$(Suits, .suit)+Eval$(Cards, .card),
                  }
             }
      End Sub
      Sub NextCard()
                  If Len(StackPack)=0 Then {
                        Suffle()
                        Stack StackPack {
                              Drop Random(0, 51)
                        }
                  }
                  Stack StackPack {
                        Read Card
                  }
      End Sub
}
PlayCards


define(`randSeed',141592653)dnl
define(`setRand',
   `define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')dnl
define(`rand_t',`eval(randSeed^(randSeed>>13))')dnl
define(`random',
   `define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed')dnl
define(`for',
   `ifelse($#,0,``$0'',
   `ifelse(eval($2<=$3),1,
   `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')dnl
define(`foreach', `pushdef(`$1')_foreach([email protected])popdef(`$1')')dnl
define(`_arg1', `$1')dnl
define(`_foreach', `ifelse(`$2', `()', `',
   `define(`$1', _arg1$2)$3`'$0(`$1', (shift$2), `$3')')')dnl
define(`new',`define(`$1[size]',0)')dnl
define(`append',
   `define(`$1[size]',incr(defn(`$1[size]')))`'define($1[defn($1[size])],$2)')
define(`deck',
   `new($1)foreach(`x',(Ace,2,3,4,5,6,7,8,9,10,Jack,Queen,King),
      `foreach(`y',(Clubs,Diamonds,Hearts,Spades),
         `append(`$1',`x of y')')')')dnl
define(`show',
   `for(`x',1,defn($1[size]),`defn($1[x])ifelse(x,defn($1[size]),`',`, ')')')dnl
define(`swap',`define($1[$2],defn($1[$4]))define($1[$4],$3)')dnl
define(`shuffle',
   `for(`x',1,defn($1[size]),
      `swap($1,x,defn($1[x]),eval(1+random%defn($1[size])))')')dnl
define(`deal',
   `ifelse($#,0,``$0'',
   `ifelse(defn($1[size]),0,
      `NULL',
      defn($1[defn($1[size])])define($1[size],decr(defn($1[size]))))')')dnl
dnl
deck(`b')
show(`b')
shuffling shuffle(`b')
show(`b')
deal deal(`b')
deal deal(`b')
show(`b')


MakeDeck[] :=  Tuples[{{"Ace ", 2, 3 , 4 , 5, 6 , 7 , 8 , 9 , 10, "Jack" , "Queen", "King"}, {♦ , ♣, ♥ , ♠}}]
DeckShuffle[deck_] := RandomSample[deck, [email protected]]
DealFromDeck[] := ([email protected]@deck; deck = deck[[2 ;; All]];)


suits = ["Spades", "Clubs", "Hearts", "Diamonds"]
pips = ["Ace","Two","Three","Four","Five","Six","Seven",
    "Eight","Nine","Ten","Jack","Queen","King"]

Card = {}
Card.str = function()
    return self.pip + " of " + self.suit + " (value: " + self.value + ")"
end function

//Build Deck
deck = []
for s in suits.indexes
    for p in pips.indexes
        card = new Card
        card.suit = suits[s]
        card.pip = pips[p]
        card.value = s * 100 + p
        deck.push card
    end for
end for

draw = function(count=7)
    hand = []
    for i in range(1, count)
        hand.push deck.pop
    end for
    return hand
end function

display = function(stack)
    for card in stack
        print card.str
    end for
end function

print "Deck created. Cards in Deck: " + deck.len

deck.shuffle
print "Deck Shuffled"

hand = draw
print "First hand: "
display hand

print
print deck.len + " cards left in deck:"
display deck


import random, strutils

type
  Suit* = enum ♥, ♦, ♣, ♠

  Rank* {.pure.} = enum
    Ace = (1, "A")
    Two = (2, "2")
    Three = (3, "3")
    Four = (4, "4")
    Five = (5, "5")
    Six = (6, "6")
    Seven = (7, "7")
    Eight = (8, "8")
    Nine = (9, "9")
    Ten = (10, "10")
    Jack = (11, "J")
    Queen = (12, "Q")
    King = (13, "K")

  Card* = tuple[rank: Rank; suit: Suit]

  # Sequences of cards: synonyms for seq[Card].
  Deck* = seq[Card]
  Hand* = seq[Card]

var initRandom = false   # True if "randomize" has been called.

proc `$`*(c: Card): string =
  ## Return the representation of a card.
  $c.rank & $c.suit

proc initDeck*(): Deck =
  ## Initialize a deck.
  for suit in Suit:
    for rank in Rank:
      result.add (rank, suit)

proc shuffle*(cards: var seq[Card]) =
  ## Shuffle a list of cards (deck or hand).
  if not initRandom:
    randomize()
    initRandom = true
  random.shuffle(cards)

func `$`*(cards: seq[Card]): string =
  ## Return the representation of a list o cards.
  cards.join(" ")

func dealOne*(cards: var seq[Card]): Card =
  ## Deal one card from a list of cards.
  assert cards.len > 0
  cards.pop()

## Draw one card from a list of cards.
let draw* = dealOne

func deal*(deck: var Deck; nPlayers: Positive; nCards: Positive): seq[Hand] =
  ## Deal "nCards" cards to "nPlayers" players.
  assert deck.len >= nCards * nPlayers
  result.setLen(nPlayers)
  for n in 1..nCards:
    for p in 0..<nPlayers:
      result[p].add deck.pop()

when isMainModule:
  import strformat

  var deck = initDeck()
  deck.shuffle()
  echo "Initial deck after shuffling: "
  for i in 0..2: echo deck[(i * 13)..(i * 13 + 12)], " ..."
  echo deck[^13..^1]

  echo "\nDeal eight cards for five players from the deck:"
  var hands = deck.deal(5, 8)
  for i, hand in hands: echo &"Player {i + 1} hand: ", hand
  echo "Remaining cards: ", deck

  echo "\nAfter player 1 drew a card from the deck: "
  hands[0].add deck.draw()
  echo "Player 1 hand: ", hands[0]
  echo "Remaining cards: ", deck


type pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten |
           Jack | Queen | King | Ace
let pips = [Two; Three; Four; Five; Six; Seven; Eight; Nine; Ten;
            Jack; Queen; King; Ace]
type suit = Diamonds | Spades | Hearts | Clubs
let suits = [Diamonds; Spades; Hearts; Clubs]
type card = pip * suit
let full_deck = Array.of_list (List.concat (List.map (fun pip -> List.map (fun suit -> (pip, suit)) suits) pips))
let shuffle deck =
  for i = Array.length deck - 1 downto 1 do
    let j = Random.int (i+1) in
    let temp = deck.(i) in
    deck.(i) <- deck.(j);
    deck.(j) <- temp
  done


package Playing_Card_Deck;

use strict;

@Playing_Card_Deck::suits = qw
   [Diamonds Clubs Hearts Spades];
@Playing_Card_Deck::pips = qw
   [Two Three Four Five Six Seven Eight Nine Ten
    Jack King Queen Ace];
# I choose to fully qualify these names rather than declare them
# with "our" to keep them from escaping into the scope of other
# packages in the same file. Another possible solution is to use
# "our" or "my", but to enclose this entire package in a bare block.

sub new
# Creates a new deck-object. The cards are initially neatly ordered.
 {my $invocant = shift;
  my $class = ref($invocant) || $invocant;
  my @cards = ();
  foreach my $suit (@Playing_Card_Deck::suits)
     {foreach my $pip (@Playing_Card_Deck::pips)
         {push(@cards, {suit => $suit, pip => $pip});}}
  return bless([@cards], $class);}

sub deal
# Removes the top card of the given deck and returns it as a hash
# with the keys "suit" and "pip".
 {return %{ shift( @{shift(@_)} ) };}

sub shuffle
# Randomly permutes the cards in the deck. It uses the algorithm
# described at:
# http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm
 {our @deck; local *deck = shift;
    # @deck is now an alias of the invocant's referent.
  for (my $n = $#deck ; $n ; --$n)
     {my $k = int rand($n + 1);
      @deck[$k, $n] = @deck[$n, $k] if $k != $n;}}

sub print_cards
# Prints out a description of every card in the deck, in order.
 {print "$_->{pip} of $_->{suit}\n" foreach @{shift(@_)};}


-- demo\rosetta\Playing_cards.exw
function deal(sequence deck, integer nhands, integer ncards)
sequence hands = repeat({},nhands)
    for n=1 to ncards do
        for h=1 to nhands do
            hands[h] &= deck[1]
            deck = deck[2..$]
        end for
    end for
    return {deck,hands}
end function

--console:
procedure show_cards(sequence s)
    for i=1 to length(s) do
        integer c = s[i]-1
        string sep = iff(mod(i,13)=0 or i=length(s)?"\n":" ")
        puts(1,"23456789TJQKA"[mod(c,13)+1]&"SHDC"[floor(c/13)+1]&sep)
    end for
end procedure

sequence deck, hands

procedure console_show()
    for i=1 to length(hands) do
        printf(1,"hand%d:\n",{i})
        show_cards(sort(hands[i]))
    end for
    printf(1,"remaining cards(%d):\n",{length(deck)})
    show_cards(deck)
end procedure

--GUI:
function cards_to_utf8(sequence s)
sequence utf32 = {}
    for i=1 to length(s) do
        integer c = s[i]
        integer pip = mod(c,13)
        utf32 &= 0x1F0A1 + pip+(pip>10) + floor((c-1)/13)*#10
        if mod(i,12)=0 and i<length(s) then
            utf32 &= '\n'
        end if
    end for
    return utf32_to_utf8(utf32)
end function

include pGUI.e

constant FONT = sprintf(`FONT="Arial, %d"`,{92})

procedure gui_show()
    IupOpen()
    IupSetGlobal("UTF8MODE","YES")

    Ihandles lh = {}
    for i=1 to length(hands) do
        Ihandle l = IupLabel(sprintf("hand%d:",{i}))
        Ihandle h = IupLabel(cards_to_utf8(sort(hands[i])),FONT)
        lh &= l&h
    end for
    lh &= IupLabel("remaining cards:")
    lh &= IupLabel(cards_to_utf8(deck),FONT)

    Ihandle dlg = IupDialog(IupVbox(lh))
    IupShow(dlg)
    if platform()!=JS then
        IupMainLoop()
        IupClose()
    end if
end procedure

constant DECKSIZE=52
deck = shuffle(tagset(DECKSIZE))
show_cards(deck)
{deck,hands} = deal(deck,2,9)
console_show()
gui_show()


class Card
{
    // if unable to save as UTF-8, use other, non-UTF-8, symbols here
    protected static $suits = array( '♠', '♥', '♦', '♣' );

    protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );

    protected $suit;

    protected $suitOrder;

    protected $pip;

    protected $pipOrder;

    protected $order;

    public function __construct( $suit, $pip )
    {
        if( !in_array( $suit, self::$suits ) )
        {
            throw new InvalidArgumentException( 'Invalid suit' );
        }
        if( !in_array( $pip, self::$pips ) )
        {
            throw new InvalidArgumentException( 'Invalid pip' );
        }

        $this->suit = $suit;
        $this->pip = $pip;
    }

    public function getSuit()
    {
        return $this->suit;
    }

    public function getPip()
    {
        return $this->pip;
    }

    public function getSuitOrder()
    {
        // lazy evaluate suit order
        if( !isset( $this->suitOrder ) )
        {
            // cache suit order
            $this->suitOrder = array_search( $this->suit, self::$suits );
        }

        return $this->suitOrder;
    }

    public function getPipOrder()
    {
        // lazy evaluate pip order
        if( !isset( $this->pipOrder ) )
        {
            // cache pip order
            $this->pipOrder = array_search( $this->pip, self::$pips );
        }

        return $this->pipOrder;
    }

    public function getOrder()
    {
        // lazy evaluate order
        if( !isset( $this->order ) )
        {
            $suitOrder = $this->getSuitOrder();
            $pipOrder = $this->getPipOrder();
            // cache order
            $this->order = $pipOrder * count( self::$suits ) + $suitOrder;
        }

        return $this->order;
    }

    public function compareSuit( Card $other )
    {
        return $this->getSuitOrder() - $other->getSuitOrder();
    }

    public function comparePip( Card $other )
    {
        return $this->getPipOrder() - $other->getPipOrder();
    }

    public function compare( Card $other )
    {
        return $this->getOrder() - $other->getOrder();
    }

    public function __toString()
    {
        return $this->suit . $this->pip;
    }

    public static function getSuits()
    {
        return self::$suits;
    }

    public static function getPips()
    {
        return self::$pips;
    }
}

class CardCollection
    implements Countable, Iterator
{
    protected $cards = array();

    protected function __construct( array $cards = array() )
    {
        foreach( $cards as $card )
        {
            $this->addCard( $card );
        }
    }

    /**
      * Countable::count() implementation
      */
    public function count()
    {
        return count( $this->cards );
    }

    /**
      * Iterator::key() implementation
      */
    public function key()
    {
        return key( $this->cards );
    }

    /**
      * Iterator::valid() implementation
      */
    public function valid()
    {
        return null !== $this->key();
    }

    /**
      * Iterator::next() implementation
      */
    public function next()
    {
        next( $this->cards );
    }

    /**
      * Iterator::current() implementation
      */
    public function current()
    {
        return current( $this->cards );
    }

    /**
      * Iterator::rewind() implementation
      */
    public function rewind()
    {
        reset( $this->cards );
    }

    public function sort( $comparer = null )
    {
        $comparer = $comparer ?: function( $a, $b ) {
            return $a->compare( $b );
        };

        if( !is_callable( $comparer ) )
        {
            throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' );
        }

        usort( $this->cards, $comparer );
        return $this;
    }

    public function toString()
    {
        return implode( ' ', $this->cards );
    }

    public function __toString()
    {
        return $this->toString();
    }

    protected function addCard( Card $card )
    {
        if( in_array( $card, $this->cards ) )
        {
            throw new DomainException( 'Card is already present in this collection' );
        }

        $this->cards[] = $card;
    }
}

class Deck
    extends CardCollection
{
    public function __construct( $shuffled = false )
    {
        foreach( Card::getSuits() as $suit )
        {
            foreach( Card::getPips() as $pip )
            {
                $this->addCard( new Card( $suit, $pip ) );
            }
        }

        if( $shuffled )
        {
            $this->shuffle();
        }
    }

    public function deal( $amount = 1, CardCollection $cardCollection = null )
    {
        if( !is_int( $amount ) || $amount < 1 )
        {
            throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' );
        }

        if( $amount > count( $this->cards ) )
        {
            throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' );
        }

        $cards = array_splice( $this->cards, 0, $amount );

        $cardCollection = $cardCollection ?: new CardCollection;

        foreach( $cards as $card )
        {
            $cardCollection->addCard( $card );
        }

        return $cardCollection;
    }

    public function shuffle()
    {
        shuffle( $this->cards );
    }
}

class Hand
    extends CardCollection
{
    // override CardCollection __constructor
    // to allow public instantiation
    // but disallow instantiation with cards
    public function __construct() {}

    public function play( $position )
    {
        if( !isset( $this->cards[ $position ] ) )
        {
            throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' );
        }

        $result = array_splice( $this->cards, $position, 1 );
        return $result[ 0 ];
    }
}


go =>
  % Create and print the deck
  deck(Deck),
  print_deck(Deck),
  nl,

  % Shuffle the deck
  print_deck(shuffle(Deck)),
  nl,

  % Deal 3 cards
  Deck := deal(Deck,Card1),
  Deck := deal(Deck,Card2),
  Deck := deal(Deck,Card3),

  println(deal1=Card1),
  println(deal2=Card2),
  println(deal3=Card3),
  % The remaining deck
  print_deck(Deck),
  nl,

  % Deal 5 cards
  Deck := deal(Deck,Card4),
  Deck := deal(Deck,Card5),
  Deck := deal(Deck,Card6),
  Deck := deal(Deck,Card7),
  Deck := deal(Deck,Card8),

  println(cards4_to_8=[Card4,Card5,Card6,Card7,Card8]),
  nl,

  % Deal 5 cards
  Deck := deal_n(Deck,5,FiveCards),
  println(fiveCards=FiveCards),
  print_deck(Deck),
  nl,

  % And deal some more cards
  % This chaining works since deal/1 returns the remaining deck
  Deck := Deck.deal(Card9).deal(Card10).deal(Card11).deal(Card12),
  println("4_more_cards"=[Card9,Card10,Card11,Card12]),
  print_deck(Deck),

  nl.

% suits(Suits) => Suits = ["♠","♥","♦","♣"].
suits(Suits) => Suits = ["C","H","S","D"].
values(Values) => Values = ["A","2","3","4","5","6","7","8","9","T","J","Q","K"].

% Create a (sorted) deck.
deck(Deck) =>
  suits(Suits),
  values(Values),
  Deck =[S++V :V in Values, S in Suits].sort().

% Shuffle a deck
shuffle(Deck) = Deck2 =>
  Deck2 = Deck,
  Len = Deck2.length,
  foreach(I in 1..Len)
    R2 = random(1,Len),
    Deck2 := swap(Deck2,I,R2)
  end.

% Swap position I <=> J in list L
swap(L,I,J) = L2, list(L) =>
  L2 = L,
  T = L2[I],
  L2[I] := L2[J],
  L2[J] := T.

% The first card is returned as the out parameter Card.
% The deck is returned as the function value.
deal(Deck, Card) = Deck.tail() => Card = Deck.first().

% Deal N cards
deal_n(Deck, N, Cards) = [Deck[I] : I in Len+1..Deck.length]  =>
   Len = min(N,Deck.length),
   Cards = [Deck[I] : I in 1..Len].

% Print deck
print_deck(Deck) =>
  println("Deck:"),
  foreach({Card,I} in zip(Deck,1..Deck.len))
     printf("%w ", Card),
     if I mod 10 == 0 then
       nl
     end
  end,
  nl.


(de *Suits
   Club Diamond Heart Spade )

(de *Pips
   Ace 2 3 4 5 6 7 8 9 10 Jack Queen King )

(de mkDeck ()
   (mapcan
      '((Pip) (mapcar cons *Suits (circ Pip)))
      *Pips ) )

(de shuffle (Lst)
   (by '(NIL (rand)) sort Lst) )


<#
.Synopsis
   Creates a new "Deck" which is a hashtable converted to a dictionary
   This is only used for creating the deck, to view/list the deck contents use Get-Deck.
.DESCRIPTION
   Casts the string value that the user inputs to the name of the variable that holds the "deck"
   Creates a global variable, allowing you to use the name you choose in other functions and allows you to create
   multiple decks under different names.
.EXAMPLE
    PS C:\WINDOWS\system32> New-Deck
    cmdlet New-Deck at command pipeline position 1
    Supply values for the following parameters:
    YourDeckName: Deck1

    PS C:\WINDOWS\system32>

.EXAMPLE
   PS C:\WINDOWS\system32> New-Deck -YourDeckName Deck2

    PS C:\WINDOWS\system32>

.EXAMPLE
     PS C:\WINDOWS\system32> New-Deck -YourDeckName Deck2

    PS C:\WINDOWS\system32> New-Deck -YourDeckName Deck3

    PS C:\WINDOWS\system32>
#>
function New-Deck
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Name your Deck, this will be the name of the variable that holds your deck
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$False,
                   Position=0)]$YourDeckName
    )

    Begin
    {
        $Suit = @(' of Hearts', ' of Spades', ' of Diamonds', ' of Clubs')
        $Pip = @('Ace', 'King', 'Queen',  'Jack', '10', '9', '8', '7', '6', '5', '4', '3', '2')

        #Creates the hash table that will hold the suit and pip variables
        $Deck = @{}

        #creates counters for the loop below to make 52 total cards with 13 cards per suit
        [int]$SuitCounter = 0
        [int]$PipCounter = 0
        [int]$CardValue = 0

    }
    Process
    {
        #Creates the initial deck
        do
        {
            #card2add is the rows in the hashtable
            $Card2Add = ($Pip[$PipCounter]+$Suit[$SuitCounter])

            #Addes the row to the hashtable
            $Deck.Add($CardValue, $Card2Add)

            #Used to create the Keys
            $CardValue++

            #Counts the amount of cards per suit
            $PipCounter ++
                if ($PipCounter -eq 13)
                {
                    #once reached the suit is changed
                    $SuitCounter++
                    #and the per-suit counter is reset
                    $PipCounter = 0
                }
                else
                {
                    continue
                }
        }
        #52 cards in a deck
        until ($Deck.count -eq 52)

    }
    End
    {
        #sets the name of a variable that is unknown
        #Then converts the hash table to a dictionary and pipes it to the Get-Random cmdlet with the arguments to randomize the contents
        Set-Variable -Name "$YourDeckName" -Value ($Deck.GetEnumerator() | Get-Random -Count ([int]::MaxValue)) -Scope Global
}
}

<#
.Synopsis
   Lists the cards in your selected deck
.DESCRIPTION
   Contains a Try-Catch-Finally block in case the deck requested has not been created
.EXAMPLE
    PS C:\WINDOWS\system32> Get-Deck -YourDeckName deck1

    8 of Clubs
    5 of Hearts
    --Shortened--
    King of Clubs
    Jack of Diamonds

    PS C:\WINDOWS\system32>

.EXAMPLE
    PS C:\WINDOWS\system32> Get-Deck -YourDeckName deck2

    deck2 does not exist...
    Creating Deck deck2...

    Ace of Spades
    10 of Hearts
    --Shortened--
    5 of Clubs
    4 of Clubs

    PS C:\WINDOWS\system32>

.EXAMPLE
    PS C:\WINDOWS\system32> deck deck2

    Ace of Spades
    10 of Hearts
    --Shortened--
    4 of Spades
    6 of Spades
    Queen of Spades

    PS C:\WINDOWS\system32>
#>
function Get-Deck
{
    [CmdletBinding()]
    [Alias('Deck')]
    [OutputType([int])]
    Param
    (
        #Brings the Vairiable in from Get-Deck
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]$YourDeckName
    )

    Begin
    {

    }
    Process
    {
        # Will return a terminal error if the deck has not been created
        try
        {
            $temp = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction stop
        }
        catch
        {
            Write-Host
            Write-Host "$YourDeckName does not exist..."
            Write-Host "Creating Deck $YourDeckName..."
            New-Deck -YourDeckName $YourDeckName
            $temp = Get-Variable -name "$YourDeckName" -ValueOnly
        }

        finally
        {
            $temp | select Value | ft -HideTableHeaders
        }

    }
    End
    {
        Write-Verbose "End of show-deck function"
    }
}

<#
.Synopsis
   Shuffles a deck of your selection with Get-Random
.DESCRIPTION
   This function can be used to Shuffle any deck that has been created.
   This can be used on a deck that has less than 52 cards
   Contains a Try-Catch-Finally block in case the deck requested has not been created
   Does NOT output the value of the deck being shuffled (You wouldn't look at the cards you shuffled, would you?)

.EXAMPLE
    PS C:\WINDOWS\system32> Shuffle-Deck -YourDeckName Deck1
    Your Deck was shuffled

    PS C:\WINDOWS\system32>

.EXAMPLE
    PS C:\WINDOWS\system32> Shuffle NotMadeYet

    NotMadeYet does not exist...
    Creating and shuffling NotMadeYet...
    Your Deck was shuffled

    PS C:\WINDOWS\system32>
#>
function Shuffle-Deck
{
    [CmdletBinding()]
    [Alias('Shuffle')]
    [OutputType([int])]
    Param
    (
        #The Deck you want to shuffle
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]$YourDeckName)

    Begin
    {
        Write-Verbose 'Shuffles your deck with Get-Random'
    }
    Process
    {
        # Will return a missing variable error if the deck has net been created
        try
        {
            #These two commands could be on one line using the pipeline, but look cleaner on two
            $temp1 = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction stop
            $temp1 = $temp1 | Get-Random -Count ([int]::MaxValue)
        }
        catch
        {
            Write-Host
            Write-Host "$YourDeckName does not exist..."
            Write-Host "Creating and shuffling $YourDeckName..."
            New-Deck -YourDeckName $YourDeckName
            $temp1 = Get-Variable -name "$YourDeckName" -ValueOnly
            $temp1 = $temp1 | Get-Random -Count ([int]::MaxValue)

        }

        finally
        {
            #Gets the actual value of variable $YourDeckName from the New-Deck function and uses that string value
            #to set the variables name
            Set-Variable -Name "$YourDeckName" -value ($temp1) -Scope Global
        }
    }
    End
    {
        Write-Host "Your Deck was shuffled"
    }
}

<#
.Synopsis
   Creates a new "Hand" which is a hashtable converted to a dictionary
   This is only used for creating the hand, to view/list the deck contents use Get-Hand.
.DESCRIPTION
   Casts the string value that the user inputs to the name of the variable that holds the "hand"
   Creates a global variable, allowing you to use the name you choose in other functions and allows you to create
   multiple hands under different names.
.EXAMPLE
    PS C:\WINDOWS\system32> New-Hand -YourHandName JohnDoe

    PS C:\WINDOWS\system32>
.EXAMPLE
    PS C:\WINDOWS\system32> New-Hand JaneDoe

    PS C:\WINDOWS\system32>
>
#>
function New-Hand
{
    [CmdletBinding()]
    [OutputType([int])]
    Param
    (
        # Name your Deck, this will be the name of the variable that holds your deck
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$False,
                   Position=0)]$YourHandName
    )

    Begin
    {
        $Hand = @{}
    }
    Process
    {
    }

    End
    {
        Set-Variable -Name "$YourHandName" -Value ($Hand.GetEnumerator()) -Scope Global
}
}

<#
.Synopsis
   Lists the cards in the selected Hand
.DESCRIPTION
   Contains a Try-Catch-Finally block in case the hand requested has not been created
.EXAMPLE
    #create a new hand
    PS C:\WINDOWS\system32> New-Hand -YourHandName Hand1

    PS C:\WINDOWS\system32> Get-Hand -YourHandName Hand1
    Hand1's hand contains  cards, they are...

    PS C:\WINDOWS\system32>
    #This hand is empty
.EXAMPLE
    PS C:\WINDOWS\system32> Get-Hand -YourHandName Hand2

    Hand2 does not exist...
    Creating Hand Hand2...
    Hand2's hand contains  cards, they are...

    PS C:\WINDOWS\system32>

.EXAMPLE
    PS C:\WINDOWS\system32> hand hand3
    hand3's hand contains 4 cards, they are...

    5 of Spades
    4 of Spades
    6 of Spades
    Queen of Diamonds
#>
function Get-Hand
{
    [CmdletBinding()]
    [Alias('Hand')]
    [OutputType([int])]
    Param
    (
        #Brings the Vairiable in from Get-Deck
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]$YourHandName
    )
    Begin
    {
    }
    Process
    {
        # Will return a missing variable error if the deck has net been created
        try
        {
            $temp = Get-Variable -name "$YourHandName" -ValueOnly -ErrorAction stop
        }
        catch
        {
            Write-Host
            Write-Host "$YourHandName does not exist..."
            Write-Host "Creating Hand $YourHandName..."
            New-Hand -YourHandName $YourHandName
            $temp = Get-Variable -name "$YourHandName" -ValueOnly
        }

        finally
        {
            $count = $temp.count
            Write-Host "$YourHandName's hand contains $count cards, they are..."
            $temp | select Value | ft -HideTableHeaders
        }

    }
    End
    {
        Write-Verbose "End of show-deck function"
    }
}

<#
.Synopsis
   Draws/returns cards
.DESCRIPTION
   Draws/returns cards from your chosen deck , to your chosen hand
   Can be used without creating a deck or hand first
.EXAMPLE
    PS C:\WINDOWS\system32> DrawFrom-Deck -YourDeckName Deck1 -YourHandName test1 -HowManyCardsToDraw 10

PS C:\WINDOWS\system32>
.EXAMPLE
DrawFrom-Deck -YourDeckName Deck2 -YourHandName test2 -HowManyCardsToDraw 10
Deck2 does not exist...
Creating Deck Deck2...

test2 does not exist...
Creating Hand test2...
test2's hand contains  cards, they are...

.EXAMPLE
    PS C:\WINDOWS\system32> draw -YourDeckName deck1 -YourHandName test1 -HowManyCardsToDraw 5

#>
function Draw-Deck
{
    [CmdletBinding()]
    [Alias('Draw')]
    [OutputType([int])]
    Param
    (
        # The Deck in which you want to draw cards out of
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]$YourDeckName,

        #The hand in which you want to draw cards to
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]$YourHandName,

        #Quanity of cards being drawn
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]$HowManyCardsToDraw

                   )
    Begin
    {
        Write-Verbose "Draws a chosen amount of cards from the chosen deck"

       #try-catch-finally blocks so the user does not have to use New-Deck and New-Hand beforehand.
       try
        {
            $temp = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction Stop
        }
        catch
        {
            Get-Deck -YourDeckName $YourDeckName
            $temp = Get-Variable -name "$YourDeckName" -ValueOnly -ErrorAction Stop
        }
        finally
        {
            Write-Host
        }

        try
        {
            $temp2 = Get-Variable -name "$YourHandName" -ValueOnly -ErrorAction Stop
        }
        catch
        {
            Get-Hand -YourHandName $YourHandName
            $temp2 = Get-Variable -name "$YourHandName" -ValueOnly -ErrorAction Stop
        }
        finally
        {
            Write-Host
        }
    }

    Process
    {
        Write-Host "you drew $HowManyCardsToDraw cards, they are..."

        $handValues = Get-Variable -name "$YourDeckName" -ValueOnly
        $handValues = $handValues[0..(($HowManyCardsToDraw -1))] | select value | ft -HideTableHeaders
        $handValues

    }
    End
    {
        #sets the new values for the deck and the hand selected
        Set-Variable -Name "$YourDeckName" -value ($temp[$HowManyCardsToDraw..($temp.count)]) -Scope Global
        Set-Variable -Name "$YourHandName" -value ($temp2 + $handValues) -Scope Global
    }
}


/** <module> Cards

  A card is represented by the term "card(Pip, Suit)".
  A deck is represented internally as a list of cards.

  Usage:
  new_deck(D0), deck_shuffle(D0, D1), deck_deal(D1, C, D2).
*/
:- module(cards, [ new_deck/1,     % -Deck
                   deck_shuffle/2, % +Deck, -NewDeck
                   deck_deal/3,    % +Deck, -Card, -NewDeck
                   print_deck/1    % +Deck
                  ]).

%% new_deck(-Deck)
new_deck(Deck) :-
        Suits = [clubs, hearts, spades, diamonds],
        Pips = [2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king, ace],
        setof(card(Pip, Suit), (member(Suit, Suits), member(Pip, Pips)), Deck).

%% deck_shuffle(+Deck, -NewDeck)
deck_shuffle(Deck, NewDeck) :-
        length(Deck, NumCards),
        findall(X, (between(1, NumCards, _I), X is random(1000)), Ord),
        pairs_keys_values(Pairs, Ord, Deck),
        keysort(Pairs, OrdPairs),
        pairs_values(OrdPairs, NewDeck).

%% deck_deal(+Deck, -Card, -NewDeck)
deck_deal([Card|Cards], Card, Cards).

%% print_deck(+Deck)
print_deck(Deck) :-
        maplist(print_card, Deck).

% print_card(+Card)
print_card(card(Pip, Suit)) :-
        format('~a of ~a~n', [Pip, Suit]).


#MaxCards = 52 ;Max Cards in a deck
Structure card
  pip.s
  suit.s
EndStructure

Structure _membersDeckClass
  *vtable.i
  size.i ;zero based count of cards present
  cards.card[#MaxCards] ;deck content
EndStructure

Interface deckObject
  Init()
  shuffle()
  deal.s(isAbbr = #True)
  show(isAbbr = #True)
EndInterface

Procedure.s _formatCardInfo(*card.card, isAbbr = #True)
  ;isAbbr determines if the card information is abbrieviated to 2 characters
  Static pips.s = "2 3 4 5 6 7 8 9 10 Jack Queen King Ace"
  Static suits.s = "Diamonds Clubs Hearts Spades"
  Protected c.s

  If isAbbr
    c = *card\pip + *card\suit
  Else
    c = StringField(pips,FindString("23456789TJQKA", *card\pip, 1), " ") + " of "
    c + StringField(suits,FindString("DCHS", *card\suit, 1)," ")
  EndIf
  ProcedureReturn c
EndProcedure

Procedure setInitialValues(*this._membersDeckClass)
  Protected i, c.s

  Restore cardDat
  For i = 0 To #MaxCards - 1
    Read.s c
    *this\cards[i]\pip = Left(c, 1)
    *this\cards[i]\suit = Right(c, 1)
  Next
EndProcedure

Procedure.s dealCard(*this._membersDeckClass, isAbbr)
  ;isAbbr is #True if the card dealt is abbrieviated to 2 characters
  Protected c.card
  If *this\size < 0
    ;deck is empty
    ProcedureReturn ""
  Else
    c = *this\cards[*this\size]
    *this\size - 1
    ProcedureReturn _formatCardInfo(@c, isAbbr)
  EndIf
EndProcedure

Procedure showDeck(*this._membersDeckClass, isAbbr)
  ;isAbbr determines if cards are shown with 2 character abbrieviations
  Protected i

  For i = 0 To *this\size
    Print(_formatCardInfo(@*this\cards[i], isAbbr))
    If i <> *this\size: Print(", "): EndIf
  Next
  PrintN("")
EndProcedure

Procedure shuffle(*this._membersDeckClass)
  ;works with decks of any size
  Protected w, i
  Dim shuffled.card(*this\size)

  For i = *this\size To 0 Step -1
    w = Random(i)
    shuffled(i) = *this\cards[w]
    If w <> i
      *this\cards[w] = *this\cards[i]
    EndIf

  Next

  For i = 0 To *this\size
    *this\cards[i] = shuffled(i)
  Next
EndProcedure

Procedure newDeck()
  Protected *newDeck._membersDeckClass = AllocateMemory(SizeOf(_membersDeckClass))
  If *newDeck
    *newDeck\vtable = ?vTable_deckClass
    *newDeck\size = #MaxCards - 1
    setInitialValues(*newDeck)
  EndIf
  ProcedureReturn *newDeck
EndProcedure

DataSection
  vTable_deckClass:
  Data.i @setInitialValues()
  Data.i @shuffle()
  Data.i @dealCard()
  Data.i @showDeck()

  cardDat:
  Data.s "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "TD", "JD", "QD", "KD", "AD"
  Data.s "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "TC", "JC", "QC", "KC", "AC"
  Data.s "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "TH", "JH", "QH", "KH", "AH"
  Data.s "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "TS", "JS", "QS", "KS", "AS"
EndDataSection

If OpenConsole()

  Define deck.deckObject = newDeck()
  Define deck2.deckObject = newDeck()

  If deck = 0 Or deck2 = 0
    PrintN("Unable to create decks")
    End
  EndIf

  deck\shuffle()
  PrintN("Dealt: " + deck\deal(#False))
  PrintN("Dealt: " + deck\deal(#False))
  PrintN("Dealt: " + deck\deal(#False))
  PrintN("Dealt: " + deck\deal(#False))
  deck\show()
  deck2\show()

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


import random

class Card(object):
    suits = ("Clubs","Hearts","Spades","Diamonds")
    pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")

    def __init__(self, pip,suit):
        self.pip=pip
        self.suit=suit

    def __str__(self):
        return "%s %s"%(self.pip,self.suit)

class Deck(object):
    def __init__(self):
        self.deck = [Card(pip,suit) for suit in Card.suits for pip in Card.pips]

    def __str__(self):
        return "[%s]"%", ".join( (str(card) for card in self.deck))

    def shuffle(self):
        random.shuffle(self.deck)

    def deal(self):
        self.shuffle()  # Can't tell what is next from self.deck
        return self.deck.pop(0)


/O> newpack +jokers 3 riffles 4 players 7 deal
... say "The player's hands..." cr cr
... witheach [ echohand cr ]
... say "Cards left in the pack (the talon)..." cr cr
... echohand
...
The player's hands...

eight of hearts
seven of clubs
nine of hearts
two of diamonds
three of diamonds
three of hearts
seven of spades

low joker
ace of hearts
ace of clubs
queen of diamonds
nine of clubs
six of spades
six of diamonds

ten of diamonds
five of spades
jack of diamonds
two of hearts
two of clubs
five of diamonds
ten of clubs

ace of diamonds
ace of spades
eight of clubs
king of diamonds
four of diamonds
ten of hearts
three of clubs

Cards left in the pack (the talon)...

eight of spades
four of hearts
jack of hearts
four of clubs
nine of spades
ten of spades
two of spades
five of hearts
seven of diamonds
five of clubs
jack of clubs
eight of diamonds
six of hearts
queen of hearts
three of spades
nine of diamonds
six of clubs
queen of clubs
four of spades
seven of hearts
jack of spades
queen of spades
king of hearts
king of spades
king of clubs
high joker


pips <- c("2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace")
suit <- c("Clubs", "Diamonds", "Hearts", "Spades")
# Create a deck
deck <- data.frame(pips=rep(pips, 4), suit=rep(suit, each=13))

shuffle <- function(deck)
{
   n <- nrow(deck)
   ord <- sample(seq_len(n), size=n)
   deck[ord,]
}

deal <- function(deck, fromtop=TRUE)
{
   index <- ifelse(fromtop, 1, nrow(deck))
   print(paste("Dealt the", deck[index, "pips"], "of", deck[index, "suit"]))
   deck[-index,]
}

# Usage
deck <- shuffle(deck)
deck
deck <- deal(deck)
# While no-one is looking, sneakily deal a card from the bottom of the pack
deck <- deal(deck, FALSE)


#lang racket

;; suits:
(define suits '(club heart diamond spade))

;; ranks
(define ranks '(1 2 3 4 5 6 7 8 9 10 jack queen king))

;; cards
(define cards
  (for*/list ([suit suits] [rank ranks])
    (list suit rank)))

;; a deck is a box containing a list of cards.
(define (new-deck)
  (box cards))

;; shuffle the cards in a deck
(define (deck-shuffle deck)
  (set-box! deck (shuffle (unbox deck))))

;; deal a card from tA 2 3 4 5 6 7 8 9 10 J Q K>;
enum Suit he deck:
(define (deck-deal deck)
  (begin0 (first (unbox deck))
          (set-box! deck (rest (unbox deck)))))

;; TRY IT OUT:
(define my-deck (new-deck))
(deck-shuffle my-deck)
(deck-deal my-deck)
(deck-deal my-deck)
(length (unbox my-deck))


enum Pip <A 2 3 4 5 6 7 8 9 10 J Q K>;
enum Suit <♦ ♣ ♥ ♠>;

class Card {
    has Pip $.pip;
    has Suit $.suit;

    method Str { $!pip ~ $!suit }
}

class Deck {
    has Card @.cards = pick *,
            map { Card.new(:$^pip, :$^suit) }, flat (Pip.pick(*) X Suit.pick(*));

    method shuffle { @!cards .= pick: * }

    method deal { shift @!cards }

    method Str  { ~@!cards }
    method gist { ~@!cards }
}

my Deck $d = Deck.new;
say "Deck: $d";

my $top = $d.deal;
say "Top card: $top";

$d.shuffle;
say "Deck, re-shuffled: ", $d;


Red [Title: "Playing Cards"]

pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"]
suit: ["♣" "♦" "♥" "♠"]

make-deck: function [] [
	new-deck: make block! 52
	foreach s suit [foreach p pip [append/only new-deck reduce [p s]]]
	return new-deck
]

shuffle: function [deck [block!]] [deck: random deck]

deal: function [other-deck [block!] deck [block!]] [unless empty? deck [append/only other-deck take deck]]

contents: function [deck [block!]] [
	line: 0
	repeat i length? deck [
		prin [trim/all form deck/:i " "]
		if (to-integer i / 13) > line [line: line + 1 print ""]
]]

deck: shuffle make-deck
print "40 cards from a deck:"
loop 5 [ print "" loop 8 [prin [trim/all form take deck " "]]]
prin "^/^/remaining: "
contents deck


/* REXX ***************************************************************
* 1) Build ordered Card deck
* 2) Create shuffled stack
* 3) Deal 5 cards to 4 players each
* 4) show what cards have been dealt and what's left on the stack
* 05.07.2012 Walter Pachl
**********************************************************************/
colors='S H C D'
ranks ='A 2 3 4 5 6 7 8 9 T J Q K'
i=0
cards=''
ss=''
Do c=1 To 4
  Do r=1 To 13
    i=i+1
    card.i=word(colors,c)word(ranks,r)
    cards=cards card.i
    End
  End
n=52                                   /* number of cards on deck    */
Do si=1 To 51                          /* pick 51 cards              */
  x=random(0,n-1)+1                    /* take card x (in 1...n)     */
  s.si=card.x                          /* card on shuffled stack     */
  ss=ss s.si                           /* string of shuffled stack   */
  card.x=card.n                        /* replace card taken         */
  n=n-1                                /* decrement nr of cards      */
  End
s.52=card.1                            /* pick the last card left    */
ss=ss s.52                             /* add it to the string       */
Say 'Ordered deck:'
Say '  'subword(cards,1,26)
Say '  'subword(cards,27,52)
Say 'Shuffled stack:'
Say '  'subword(ss,1,26)
Say '  'subword(ss,27,52)
si=52
deck.=''
Do ci=1 To 5                           /* 5 cards each               */
  Do pli=1 To 4                        /* 4 players                  */
    deck.pli.ci=s.si                   /* take top of shuffled deck  */
    si=si-1                            /* decrement number           */
    deck.pli=deck.pli deck.pli.ci      /* pli's cards as string      */
    End
  End
Do pli=1 To 4                          /* show the 4 dealt ...       */
  Say pli':' deck.pli
  End
Say 'Left on shuffled stack:'
Say '  'subword(ss,1,26)               /* and what's left on stack   */
Say '  'subword(ss,27,6)


Load "guilib.ring"

nScale = 1

app1 = new qApp

mypic = new QPixmap("cards.jpg")

mypic2 = mypic.copy(0,(124*4)+1,79,124)
Player1EatPic = mypic.copy(80,(124*4)+1,79,124)
Player2EatPic= mypic.copy(160,(124*4)+1,79,124)

aMyCards = []
aMyValues = []
for x1 = 0 to 3
        for y1 = 0 to 12
          temppic = mypic.copy((79*y1)+1,(124*x1)+1,79,124)
                  aMyCards + temppic
                  aMyValues + (y1+1)
        next
next

nPlayer1Score = 0   nPlayer2Score=0

do
        Page1 = new Game
        Page1.Start()
again Page1.lnewgame

mypic.delete()
mypic2.delete()
Player1EatPic.delete()
Player2EatPic.delete()

for t in aMyCards
          t.delete()
next

func gui_setbtnpixmap pBtn,pPixmap
        pBtn {
                setIcon(new qicon(pPixmap.scaled(width(),height(),0,0)))
                setIconSize(new QSize(width(),height()))
        }

Class Game

        nCardsCount = 10
        win1 layout1 label1 label2 layout2 layout3 aBtns aBtns2
        aCards nRole=1 aStatus = list(nCardsCount) aStatus2 = aStatus
        aValues        aStatusValues = aStatus  aStatusValues2 = aStatus
        Player1EatPic   Player2EatPic
        lnewgame = false
        nDelayEat = 0.5
        nDelayNewGame = 1

        func start

                win1 = new qWidget() {
                        setwindowtitle("Five")
                        setstylesheet("background-color: White")
                        showfullscreen()
                }

                layout1 = new qvboxlayout()

                label1 = new qlabel(win1) {
                        settext("Player (1) - Score : " + nPlayer1Score)
                        setalignment(Qt_AlignHCenter | Qt_AlignVCenter)
                        setstylesheet("color: White; background-color: Purple;
                                         font-size:20pt")
                        setfixedheight(200)
                }

                closebtn = new qpushbutton(win1)  {
                        settext("Close Application")
                        setstylesheet("font-size: 18px ; color : white ;
                                         background-color: black ;")
                        setclickevent("Page1.win1.close()")
                }

                aCards = aMyCards
                aValues = aMyValues

                layout2 = new qhboxlayout()

                aBtns = []

                for x = 1 to nCardsCount
                        aBtns + new qpushbutton(win1)
                        aBtns[x].setfixedwidth(79*nScale)
                        aBtns[x].setfixedheight(124*nScale)
                        gui_setbtnpixmap(aBtns[x],mypic2)
                        layout2.addwidget(aBtns[x])
                        aBtns[x].setclickevent("Page1.Player1click("+x+")")
                next

                layout1.addwidget(label1)
                layout1.addlayout(layout2)

                label2 = new qlabel(win1) {
                        settext("Player (2) - Score : " + nPlayer2Score)
                        setalignment(Qt_AlignHCenter | Qt_AlignVCenter)
                        setstylesheet("color: white; background-color: red;
                                         font-size:20pt")
                        setfixedheight(200)
                }

                layout3 = new qhboxlayout()

                aBtns2 = []
                for x = 1 to nCardsCount
                        aBtns2 + new qpushbutton(win1)
                        aBtns2[x].setfixedwidth(79*nScale)
                        aBtns2[x].setfixedheight(124*nScale)
                        gui_setbtnpixmap(aBtns2[x],mypic2)
                        layout3.addwidget(aBtns2[x])
                        aBtns2[x].setclickevent("Page1.Player2click("+x+")")
                next

                layout1.addwidget(label2)
                layout1.addlayout(layout3)
                layout1.addwidget(closebtn)

                win1.setlayout(layout1)

                app1.exec()

        Func Player1Click x
                if nRole = 1 and aStatus[x] = 0
                        nPos = ((random(100)+clock())%(len(aCards)-1)) + 1
                        gui_setbtnpixmap(aBtns[x],aCards[nPos])
                        del(aCards,nPos)
                        nRole = 2
                        aStatus[x] = 1
                        aStatusValues[x] = aValues[nPos]
                        del(aValues,nPos)
                        Player1Eat(x,aStatusValues[x])
                        checknewgame()
                ok

        Func Player2Click x
                if nRole = 2 and aStatus2[x] = 0
                        nPos = ((random(100)+clock())%(len(aCards)-1)) + 1
                        gui_setbtnpixmap(aBtns2[x],aCards[nPos])
                        del(aCards,nPos)
                        nRole = 1
                        aStatus2[x] = 1
                        aStatusValues2[x] = aValues[nPos]
                        del(aValues,nPos)
                        Player2Eat(x,aStatusValues2[x])
                        checknewgame()
                ok

        Func Player1Eat nPos,nValue

                 app1.processEvents()

                 delay(nDelayEat)
                 lEat = false
                 for x = 1 to nCardsCount
                         if aStatus2[x] = 1 and (aStatusValues2[x] = nValue or nValue=5)
                                aStatus2[x] = 2
                                gui_setbtnpixmap(aBtns2[x],Player1EatPic)
                                lEat = True
                                nPlayer1Score++
                         ok
                         if (x != nPos) and (aStatus[x] = 1) and
                                (aStatusValues[x] = nValue or nValue=5)
                                aStatus[x] = 2
                                gui_setbtnpixmap(aBtns[x],Player1EatPic)
                                lEat = True
                                nPlayer1Score++
                         ok
                 next
                 if lEat
                                nPlayer1Score++
                                gui_setbtnpixmap(aBtns[nPos],Player1EatPic)
                                aStatus[nPos] = 2
                                label1.settext("Player (1) - Score : " + nPlayer1Score)
                 ok

        Func Player2Eat nPos,nValue

                 app1.processEvents()

                 delay(nDelayEat)
                 lEat = false
                 for x = 1 to  nCardsCount
                         if aStatus[x] = 1 and (aStatusValues[x] = nValue or nValue = 5)
                                aStatus[x] = 2
                                gui_setbtnpixmap(aBtns[x],Player2EatPic)
                                lEat = True
                                nPlayer2Score++
                         ok

                         if (x != nPos) and (aStatus2[x] = 1) and
                                (aStatusValues2[x] = nValue or nValue=5 )
                                aStatus2[x] = 2
                                gui_setbtnpixmap(aBtns2[x],Player2EatPic)
                                lEat = True
                                nPlayer2Score++
                         ok
                 next
                 if lEat
                                nPlayer2Score++
                                gui_setbtnpixmap(aBtns2[nPos],Player2EatPic)
                                aStatus2[nPos] = 2
                                label2.settext("Player (2) - Score : " + nPlayer2Score)
                 ok

        Func checknewgame
                if isnewgame()
                                  lnewgame = true

                                  if nPlayer1Score > nPlayer2Score
                                         label1.settext("Player (1) Wins!!!")
                                  ok
                                  if nPlayer2Score > nPlayer1Score
                                         label2.settext("Player (2) Wins!!!")
                                  ok

                                  app1.processEvents()
                                  delay(nDelayNewGame)

                                  win1.delete()
                                  app1.quit()
                ok

        Func isnewgame
                for t in aStatus
                        if t = 0
                                return false
                        ok
                next
                for t in aStatus2
                        if t = 0
                                return false
                        ok
                next
                return true

        Func delay x
        nTime = x * 1000
        oTest = new qTest
        oTest.qsleep(nTime)


class Card
  # class constants
  SUITS = %i[ Clubs Hearts Spades Diamonds ]
  PIPS  = %i[ 2 3 4 5 6 7 8 9 10 Jack Queen King Ace ]

  # class variables (private)
  @@suit_value = Hash[ SUITS.each_with_index.to_a ]
  @@pip_value  = Hash[ PIPS.each_with_index.to_a ]

  attr_reader :pip, :suit

  def initialize(pip,suit)
    @pip = pip
    @suit = suit
  end

  def to_s
    "#{@pip} #{@suit}"
  end

  # allow sorting an array of Cards: first by suit, then by value
  def <=>(other)
    (@@suit_value[@suit] <=> @@suit_value[other.suit]).nonzero? or
    @@pip_value[@pip] <=> @@pip_value[other.pip]
  end
end

class Deck
  def initialize
    @deck = Card::SUITS.product(Card::PIPS).map{|suit,pip| Card.new(pip,suit)}
  end

  def to_s
    @deck.inspect
  end

  def shuffle!
    @deck.shuffle!
    self
  end

  def deal(*args)
    @deck.shift(*args)
  end
end

deck = Deck.new.shuffle!
puts card = deck.deal
hand = deck.deal(5)
puts hand.join(", ")
puts hand.sort.join(", ")


suite$ = "C,D,H,S"                      ' Club, Diamond, Heart, Spade
card$  = "A,2,3,4,5,6,7,8,9,T,J,Q,K"    ' Cards Ace to King

dim n(55)                               ' make ordered deck
for i = 1 to 52                         '  of 52 cards
 n(i) 	= i
next i

for i = 1 to 52 * 3                     ' shuffle deck 3 times
  i1    = int(rnd(1)*52) + 1
  i2    = int(rnd(1)*52) + 1
  h2    = n(i1)
  n(i1) = n(i2)
  n(i2) = h2
next i

for hand = 1 to 4                       ' 4 hands
for deal = 1 to 13			' deal each 13 cards
 card = card + 1                        ' next card in deck
    s    = (n(card) mod 4)  + 1         ' determine suite
    c    = (n(card) mod 13) + 1         ' determine card
    print word$(card$,c,",");word$(suite$,s,",");" ";  ' show the card
  next deal
print
next hand


extern crate rand;

use std::fmt;
use rand::Rng;
use Pip::*;
use Suit::*;

#[derive(Copy, Clone, Debug)]
enum Pip { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }

#[derive(Copy, Clone, Debug)]
enum Suit { Spades, Hearts, Diamonds, Clubs }

struct Card {
	pip: Pip,
	suit: Suit
}

impl fmt::Display for Card {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?} of {:?}", self.pip, self.suit)
    }
}

struct Deck(Vec<Card>);

impl Deck {
    fn new() -> Deck {
        let mut cards:Vec<Card> = Vec::with_capacity(52);
        for &suit in &[Spades, Hearts, Diamonds, Clubs] {
            for &pip in &[Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King] {
                cards.push( Card{pip: pip, suit: suit} );
            }
        }
        Deck(cards)
    }

    fn deal(&mut self) -> Option<Card> {
        self.0.pop()
    }

    fn shuffle(&mut self) {
        rand::thread_rng().shuffle(&mut self.0)
    }
}

impl fmt::Display for Deck {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for card in self.0.iter() {
            writeln!(f, "{}", card);
        }
        write!(f, "")
    }
}

fn main() {
    let mut deck = Deck::new();
    deck.shuffle();
    //println!("{}", deck);
    for _ in 0..5 {
        println!("{}", deck.deal().unwrap());
    }
}


import scala.annotation.tailrec
import scala.util.Random

object Pip extends Enumeration {
  type Pip = Value
  val Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace = Value
}

object Suit extends Enumeration {
  type Suit = Value
  val Diamonds, Spades, Hearts, Clubs = Value
}

import Suit._
import Pip._
case class Card(suit:Suit, value:Pip){
  override def toString():String=value + " of " + suit
}

class Deck private(val cards:List[Card]) {
  def this()=this(for {s <- Suit.values.toList; v <- Pip.values} yield Card(s,v))
  def shuffle:Deck=new Deck(Random.shuffle(cards))

  def deal(n:Int=1):(Seq[Card], Deck)={
    @tailrec def loop(count:Int, c:Seq[Card], d:Deck):(Seq[Card], Deck)={
      if(count==0 || d.cards==Nil) (c,d)
      else {
        val card :: deck = d.cards
        loop(count-1, c :+ card, new Deck(deck))
      }
    }
    loop(n, Seq(), this)
  }
  override def toString():String="Deck: " + (cards mkString ", ")
}


(define ranks
  (quote (ace 2 3 4 5 6 7 8 9 10 jack queen king)))

(define suits
  (quote (clubs diamonds hearts spades)))

(define new-deck
  (apply append
         (map (lambda (suit)
                (map (lambda (rank)
                       (cons rank suit))
                     ranks))
              suits)))

(define (shuffle deck)
  (define (remove-card deck index)
    (if (zero? index)
        (cdr deck)
        (cons (car deck) (remove-card (cdr deck) (- index 1)))))
  (if (null? deck)
      (list)
      (let ((index (random (length deck))))
        (cons (list-ref deck index) (shuffle (remove-card deck index))))))

(define-syntax deal!
  (syntax-rules ()
    ((deal! deck hand)
     (begin (set! hand (cons (car deck) hand)) (set! deck (cdr deck))))))


properties
	cards: []
end properties
to initialize
	set pips to (2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace")
	set suits to ("Clubs", "Spades", "Diamonds", "Hearts")
	repeat for each suit in suits
		repeat for each pip in pips
			set card to pip && "of" && suit
			insert card into my cards
		end repeat
	end repeat
	put "New deck created, number of cards in deck:" && the number of items in my cards
end initialize
to shuffle
	sort my cards by random of a million
	put "Deck shuffled"
end shuffle
to deal
	pull from my cards into card
	put "Card dealt:" && card
	put "Cards in deck remaining:" && the number of items in my cards
end deal
to handle asText
	return my cards joined by return
end asText


define Pip = <A 2 3 4 5 6 7 8 9 10 J Q K>;
define Suit = <♦ ♣ ♥ ♠>;

class Card(pip, suit) {
    method to_s { pip + suit }
}

class Deck(cards=[]) {

    method init {
        cards = gather {
            Pip.each { |p| Suit.each { |s| take(Card(p, s)) } }
        }
    }

    method shuffle {
        cards.shuffle!;
    }

    method deal { cards.shift };
    method to_s { cards.join(" ") };
}

var d = Deck();
say "Deck: #{d}";

var top = d.deal;
say "Top card: #{top}";

d.shuffle;
say "Deck, shuffled: #{d}";


Object subclass: #Card
  instanceVariableNames: 'thePip theSuit'
  classVariableNames: 'pips suits'
  poolDictionaries: ''
  category: nil !

!Card class methods!
initialize
  suits ifNil: [ suits := 'clubs,hearts,spades,diamonds' subStrings: $, ].
  pips ifNil: [ pips := '2,3,4,5,6,7,8,9,10,jack,queen,king,ace' subStrings: $, ]
!
new
  | o |
  o := super new.
  ^o
!
new: card
  | o |
  o := self new.
  o initWithPip: (card at: 1) andSuit: (card at: 2).
  ^o
!!

!Card class methods !
pips
  Card initialize.
  ^pips
!
suits
  Card initialize.
  ^suits
!!

!Card methods!
initWithPip: aPip andSuit: aSuit
  ( (pips includes: aPip asLowercase) &
    (suits includes: aSuit asLowercase) )
     ifTrue: [
          thePip := aPip copy.
          theSuit := aSuit copy
     ] ifFalse: [ 'Unknown pip or suit' displayOn: stderr .
                  Character nl displayOn: stderr ].
  ^self
!
asString
  ^('(%1,%2)' % { thePip . theSuit })
!
display
  self asString display
!
displayNl
  self display.
  Character nl display
!!

Object subclass: #Deck
  instanceVariableNames: 'deck'
  classVariableNames: ''
  poolDictionaries: ''
  category: nil !

!Deck class methods !
new
  |d|
  d := super new.
  d init.
  ^d
!!

!Deck methods !
init
   deck := OrderedCollection new.
   Card suits do: [ :suit |
     Card pips do: [ :pip |
         deck add: (Card new: { pip . suit })
     ]
   ]
!
deck
  ^deck
!
shuffle
  1 to: self deck size do: [ :i |
     |r2 o|
     r2 := Random between: 1 and: self deck size.
     o := self deck at: i.
     self deck at: i put: (self deck at: r2).
     self deck at: r2 put: o
  ].
  ^self
!
display
  self deck do: [ :card |
     card displayNl
  ]
!
deal
  ^self deck removeFirst
!!

"create a deck, shuffle it, remove the first card and display it"
Deck new shuffle deal displayNl.


import Foundation

// extend any Indexed collection to be able to shuffle (see http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift)
extension CollectionType where Index == Int {
    /// Return a copy of `self` with its elements shuffled
    func shuffle() -> [Generator.Element] {
        var list = Array(self)
        list.shuffleInPlace()
        return list
    }
}

extension MutableCollectionType where Index == Int {
    /// Shuffle the elements of `self` in-place.
    mutating func shuffleInPlace() {
        // empty and single-element collections don't shuffle
        if count < 2 { return }

        for i in 0..<count - 1 {
            let j = Int(arc4random_uniform(UInt32(count - i))) + i
            guard i != j else { continue }
            swap(&self[i], &self[j])
        }
    }
}

// now the model structs
enum CardColor : Int {
    case Red
    case Black
}
extension CardColor : CustomStringConvertible {
    var description : String {
        switch self {
        case .Red:
            return "Red"
        case .Black:
            return "Black"
        }
    }
}

enum Suit : Int {
    case Hearts = 1
    case Diamonds
    case Spades
    case Clubs

    var color : CardColor {
        switch self {
        case .Hearts, .Diamonds:
            return .Red
        case .Spades, .Clubs:
            return .Black
        }
    }
}

enum Pip : Int {
    case Ace = 1
    case Two = 2
    case Three = 3
    case Four = 4
    case Five = 5
    case Six = 6
    case Seven = 7
    case Eight = 8
    case Nine = 9
    case Ten = 10
    case Jack = 11
    case Queen = 12
    case King = 13
}

struct Card {
    let pip : Pip
    let suit : Suit

    var isFaceCard : Bool {
        return pip.rawValue > 10
    }

    var color : CardColor {
        return suit.color
    }
}
extension Card : Equatable {}
func == (l:Card, r:Card) -> Bool {
    return l.pip == r.pip &&
            l.suit == r.suit
}
extension Card : CustomStringConvertible {
    var description : String {
        return "\(pip) of \(suit)"
    }
}

struct Deck {
    var cards : [Card]

    var count : Int {
        return cards.count
    }

    init(shuffling:Bool=true) {
        var startcards = [Card]()
        for suit in (Suit.Hearts.rawValue...Suit.Clubs.rawValue) {
            for pip in (Pip.Ace.rawValue...Pip.King.rawValue) {
                startcards.append(Card(pip: Pip(rawValue: pip)!, suit: Suit(rawValue: suit)!))
            }
        }
        cards = startcards

        if shuffling {
            shuffle()
        }
    }

    mutating func shuffle() {
        cards.shuffleInPlace()
    }

    mutating func deal() -> Card {
        let out = cards.removeFirst()
        return out
    }

}
extension Deck : CustomStringConvertible {
    var description : String {
        return "\(count) cards: \(cards.description)"
    }
}

// test some cards
let kh = Card(pip: .King, suit: .Hearts)
let ad = Card(pip: .Ace, suit: .Diamonds)
let tc = Card(pip: .Two, suit: .Clubs)
let fc = Card(pip: Pip(rawValue:4)!, suit: .Spades)

// create an unshuffled deck
var efg =  Deck(shuffling: false)

// create a shuffled deck and print its contents
var d = Deck()
print(d)

// deal three cards
d.deal()
d.deal()
d.deal()
d

// deal a couple more cards and check their color
let c = d.deal()
c.color

let cc = d.deal()
cc.color

// deal out the rest of the deck, leaving just one card
while d.count > 1 {
    d.deal()
}
d

// test equality of a couple cards
if kh == Card(pip: Pip.King, suit: Suit.Clubs) {
    let a = true
}
else {
    let a = false
}

kh != Card(pip: Pip.King, suit: Suit.Clubs)
kh.isFaceCard
fc.isFaceCard


package require Tcl 8.5

namespace eval playing_cards {
    variable deck
    #variable suits {C D H S}
    variable suits {\u2663 \u2662 \u2661 \u2660}
    variable pips {2 3 4 5 6 7 8 9 10 J Q K A}

    proc new_deck {} {
        variable deck
        set deck [list]
        for {set i 0} {$i < 52} {incr i} {
            lappend deck $i
        }
    }

    proc shuffle {} {
        variable deck
        # shuffle in place
        for {set i 51} {$i > 0} {incr i -1} {
            set n [expr {int($i * rand())}]
            set card [lindex $deck $n]
            lset deck $n [lindex $deck $i]
            lset deck $i $card
        }
    }

    proc deal {{num 1}} {
        variable deck
        incr num -1
        set cards [lrange $deck 0 $num]
        set deck [lreplace $deck 0 $num]
        return $cards
    }

    proc card2string {card} {
        variable suits
        variable pips
        set suit [expr {$card / 13}]
        set pip [expr {$card % 13}]
        return [format "%2s %s" [lindex $pips $pip] [lindex $suits $suit]]
    }

    proc print {cards args} {
        array set opts [concat -sort false $args]
        if {$opts(-sort)} {
            set cards [lsort -integer $cards]
        }
        foreach card $cards {
            puts [card2string $card]
        }
    }

    proc print_deck {} {
        variable deck
        print $deck
    }
}

playing_cards::new_deck
playing_cards::shuffle
set hand [playing_cards::deal 5]
puts "my hand:"
playing_cards::print $hand -sort true
puts "\nthe deck:"
playing_cards::print_deck


class playingcard
	dim suit
	dim pips
end class

class carddeck
	private suitnames
	private pipnames
	private cardno
	private deck(52)
	private nTop

	sub class_initialize
		dim suit
		dim pips
		suitnames = split("H,D,C,S",",")
		pipnames = split("A,2,3,4,5,6,7,8,9,10,J,Q,K",",")
		cardno = 0

		for suit = 1 to 4
			for pips = 1 to 13
				set deck(cardno) = new playingcard
				deck(cardno).suit = suitnames(suit-1)
				deck(cardno).pips = pipnames(pips-1)
				cardno = cardno + 1
			next
		next
		nTop = 0
	end sub

	public sub showdeck
		dim a
		redim a(51-nTop)
		for i = nTop to 51
			a(i) = deck(i).pips & deck(i).suit
		next
		wscript.echo join( a, ", ")
	end sub

	public sub shuffle
		dim r
		randomize timer
		for i = nTop to 51
			r = int( rnd * ( 52 - nTop ) )
			if r <> i then
				objswap deck(i),deck(r)
			end if
		next
	end sub

	public function deal()
		set deal = deck( nTop )
		nTop = nTop + 1
	end function

	public property get cardsRemaining
		cardsRemaining = 52 - nTop
	end property

	private sub objswap(   a,   b )
		dim tmp
		set tmp = a
		set a = b
		set b = tmp
	end sub
end class


// Playing Cards, main program

Call("CREATE_DECK")
Call("SHUFFLE_DECK")
#21 = Buf_Switch(Buf_Free)        // #21 = players hand, 1st player
#1 = 5; Call("DEAL_CARDS")        // deal 5 cards to player 1
#22 = Buf_Switch(Buf_Free)        // #22 = players hand, 2nd player
#1 = 5; Call("DEAL_CARDS")        // deal 5 cards to player 2
Buf_Switch(#10) BOF               // display the deck
Return

///////////////////////////////////////////////////////////////////////////
//
//  Create a deck into a new edit buffer. One text line for each card.
//
:CREATE_DECK:
#10 = Buf_Switch(Buf_Free)        // Buffer @(#10) = the deck

RS(1, "Diamonds")
RS(2, "Spades")
RS(3, "Hearts")
RS(4, "Clubs")

RS(11, " Jack")
RS(12, "Queen")
RS(13, " King")
RS(14, "  Ace")

for (#1=1; #1<5; #1++) {
    for (#2=2; #2<15; #2++) {
        if (#2 < 11) {
            Num_Ins(#2, NOCR)     // pip (2 to 10) as numeric
        } else {
            IT(@(#2))             // pip (11 to 14) as a word
        }
        IT(" of ")
        IT(@(#1)) IN              // suit
    }
}
Return

///////////////////////////////////////////////////////////////////////////
//
//  Shuffle the deck using Fisher-Yates algorithm
//
:SHUFFLE_DECK:
Buf_Switch(#10)                   // the deck
#90 = Time_Tick                   // seed for random number generator
#91 = 51                          // random numbers in range 0 to 50
for (#1=1; #1<52; #1++) {
    Call("RANDOM")
    Goto_Line(Return_Value+1)
    Block_Copy(#1, #1, LINESET+DELETE)
    Reg_Copy(9, 1, DELETE)
    Goto_Line(#1)
    Reg_Ins(9)
}
Return

//--------------------------------------------------------------
// Generate random numbers in range 0 <= Return_Value < #91
//  #90 = Seed    (0 to 0x7fffffff)
//  #91 = Scaling (0 to 0x10000)

:RANDOM:
#92 = 0x7fffffff / 48271
#93 = 0x7fffffff % 48271
#90 = (48271 * (#90 % #92) - #93 * (#90 / #92)) & 0x7fffffff
Return ((#90 & 0xffff) * #91 / 0x10000)

///////////////////////////////////////////////////////////////////////////
//
//  Deal #1 cards: move the cards from deck to current edit buffer
//
:DEAL_CARDS:
#11 = Buf_Num                     // this buffer (players hand)
Buf_Switch(#10)                   // the deck
BOF
Reg_Copy(9, #1, DELETE)           // pull the first #1 cards from the deck
Buf_Switch(#11)                   // players hand
Reg_ins(9)                        // insert the cards here
Return


import "random" for Random

var FACES = "23456789TJQKA"
var SUITS = "shdc"

var createDeck = Fn.new {
    var cards = []
    SUITS.each { |suit| FACES.each { |face| cards.add("%(face)%(suit)") } }
    return cards
}

var dealTopDeck = Fn.new { |deck, n| deck.take(n).toList }

var dealBottomDeck = Fn.new { |deck, n| deck[-n..-1][-1..0] }

var printDeck = Fn.new { |deck|
    for (i in 0...deck.count) {
        System.write("%(deck[i])  ")
        if ((i + 1) % 13 == 0 || i == deck.count - 1) System.print()
    }
}

var deck = createDeck.call()
System.print("After creation, deck consists of:")
printDeck.call(deck)
Random.new().shuffle(deck)
System.print("\nAfter shuffling, deck consists of:")
printDeck.call(deck)
var dealtTop = dealTopDeck.call(deck, 10)
System.print("\nThe 10 cards dealt from the top of the deck are:")
printDeck.call(dealtTop)
var dealtBottom = dealBottomDeck.call(deck, 10)
System.print("\nThe 10 cards dealt from the bottom of the deck are:")
printDeck.call(dealtBottom)


char    Deck(52);               \card structure (low 2 bits = suit)
def     Players = 4;            \number of players to deal to
char    Hand(Players, 52);      \each player's hand
int     Card, N, I, J, T;
char    Suit, Royal;
[for Card:= 0 to 52-1 do        \make a new deck
        Deck(Card):= Card;
for N:= 0 to 10000 do           \shuffle the deck
        [I:= Ran(52);  J:= Ran(52);
        T:= Deck(I);  Deck(I):= Deck(J);  Deck(J):= T;
        ];
for N:= 0 to 52-1 do            \deal from the deck
        [Card:= Deck(N);
        I:= N/Players;
        J:= rem(0);
        Hand(J, I):= Card;
        ];
Suit:= "HDCS ";                 \print each player's hand
Royal:= "JQK ";                 \ (= contents of the deck)
for J:= 0 to Players-1 do       \e.g: 2D 3C 10C AS KD
    [for I:= 0 to 52/Players -1 do
        [Card:= Hand(J, I);
        N:= Card>>2 + 1;        \pip value
        if N = 1 then ChOut(0, ^A)
        else if N >= 11 then ChOut(0, Royal(N-11))
        else IntOut(0, N);
        ChOut(0, Suit(Card&3));
        ChOut(0, ^ );
        ];
    CrLf(0);
    ];
]


const Diamonds=1, Spades=3, Clubs=0, Hearts=2, Ace=1; // informational
var suits=T(0x1F0D1,0x1F0C1,0x1F0B1,0x1F0A1); //unicode 🃑,🃁,🂱,🂡

class Card{
   fcn init(pip,suit){  // or 0..51
      reg p,s;
      if(vm.numArgs==1){ s=pip/13; p=pip%13; } else { p=pip; s=suit }
      var [const] _pip=p, _suit=s;
   }
   fcn toString{
      p:=_pip + (_pip>=11);
      (suits[_suit]+p).toString(8); // int-->UTF-8
   }
}

class Deck{  //--> 52 shuffled Cards
   var [const] deck=L();
   fcn init{
      (0).pump(52,deck.clear().write,Card);
      shuffle();
   }
   fcn shuffle{ deck.shuffle() }
   fcn deal(cards=5){ deck.pop(0,cards); }
   fcn toString{ deck.pump(String,"toString"); }
}


10 GOSUB 5000
20 CLS
30 PRINT "Options:"
40 PRINT "1: Shuffle deck"
50 PRINT "2: Deal cards"
60 PRINT "3: Display deck"
70 INPUT o
80 IF o<1 OR o>3 OR o<>INT o THEN GOTO 70
90 GO SUB (o+1)*1000
100 GO TO 20

999 REM convert index to card
1000 LET s=INT ((x-1)/13)+1
1010 LET p=x-13*(s-1)
1020 LET n=s-2*INT (s/2)+1
1030 LET c$=p$(p)+CHR$ 16+CHR$ (n AND n>1)+s$(s): REM colour codes to force red or black
1040 RETURN

1999 REM shuffle - only a naive shuffle algorithm but it'll do; the modularity of the program means this is easy enough to modify
2000 CLS : PRINT FLASH 1;"Shuffling..."
2010 LET s=1: REM changing s allows shuffling the remainder of an undealt deck, say
2020 FOR x=1 TO 100
2030 LET a=INT (RND*53-s)+s
2040 LET b=INT (RND*53-s)+s
2050 LET n=d(a)
2060 LET d(a)=d(b)
2070 LET d(b)=n
2080 NEXT x
2090 RETURN

2999 REM deal
3000 INPUT "How many players? ";p
3010 INPUT "How many cards? ";c
3020 IF c<1 OR p<1 OR c<>INT c OR p<>INT p THEN PRINT "Don't be silly!": GO TO 3000
3030 IF c*p>52 THEN PRINT "Not enough cards for that!": GO TO 3000
3040 CLS : DIM h(p,c)
3050 LET k=1
3060 FOR f=1 TO c
3070 FOR e=1 TO p
3080 LET h(e,f)=d(k)
3090 LET k=k+1
3100 NEXT e
3110 NEXT f
3120 FOR e=1 TO p
3130 PRINT "Player ";e;"'s hand:"
3140 FOR f=1 TO c
3150 LET x=h(e,f)
3160 GO SUB 1000
3170 PRINT c$;" ";
3180 NEXT e
3190 PRINT
3200 NEXT f
3210 PRINT
3220 PRINT "Remaining deck:"
3230 IF c*p=52 THEN PRINT "none"
3240 GO SUB 4010
3250 RETURN

3999 REM display deck
4000 CLS : LET k=1
4010 FOR y=k TO 52: REM enter here with k>1 to show the rest of an undealt deck
4020 LET x=d(y)
4030 GO SUB 1000
4040 PRINT c$
4050 NEXT y
4060 FOR y=0 TO 1000
4070 NEXT y
4080 RETURN

4999 REM initialise
5000 DIM d(52)
5010 GO SUB 6000
5020 LET s$=CHR$ 144+CHR$ 145+CHR$ 146+CHR$ 147: REM or LET s$="HSDC" if you don't want symbols
5030 LET p$="A23456789TJQK"
5040 FOR x=1 TO 52
5050 LET d(x)=x
5060 NEXT x
5070 RETURN

5999 REM characters - the ZX Spectrum character set doesn't contain suit symbols
6000 RESTORE 7000
6010 FOR x=65368 TO 65399
6020 READ a
6030 POKE x,a
6040 NEXT x
6050 RETURN

7000 DATA BIN 01101100: REM 108
7010 DATA BIN 11111110: REM 254
7020 DATA BIN 11111110: REM 254
7030 DATA BIN 11111110: REM 254
7040 DATA BIN 01111100: REM 124
7050 DATA BIN 00111000: REM 56
7060 DATA BIN 00010000: REM 16
7070 DATA BIN 00000000: REM 0

7080 DATA BIN 00010000: REM 16
7090 DATA BIN 00111000: REM 56
7100 DATA BIN 01111100: REM 124
7110 DATA BIN 11111110: REM 254
7120 DATA BIN 01010100: REM 84
7130 DATA BIN 00010000: REM 16
7140 DATA BIN 01111100: REM 124
7150 DATA BIN 00000000: REM 0

7160 DATA BIN 00010000: REM 16
7170 DATA BIN 00111000: REM 56
7180 DATA BIN 01111100: REM 124
7190 DATA BIN 11111110: REM 254
7200 DATA BIN 01111100: REM 124
7210 DATA BIN 00111000: REM 56
7220 DATA BIN 00010000: REM 16
7230 DATA BIN 00000000: REM 0

7240 DATA BIN 00010000: REM 16
7250 DATA BIN 00111000: REM 56
7260 DATA BIN 01010100: REM 84
7270 DATA BIN 11111110: REM 254
7280 DATA BIN 01010100: REM 84
7290 DATA BIN 00010000: REM 16
7300 DATA BIN 01111100: REM 124
7310 DATA BIN 00000000: REM 0


BEGIN # find some pierpoint primes of the first kind (2^u3^v + 1)             #
      #                              and second kind (2^u3^v - 1)             #
    # construct a sieve of primes up to 10 000                                #
    PR read "primes.incl.a68" PR
    []BOOL prime = PRIMESIEVE 10 000;
    # returns the minimum of a and b                                          #
    PROC min = ( INT a, b )INT: IF a < b THEN a ELSE b FI;
    # returns TRUE if p is prime, FALSE otherwise                             #
    PROC is prime = ( INT p )BOOL:
         IF   NOT ODD p
         THEN p = 2
         ELIF p <= UPB prime
         THEN prime[ p ] # small enough to use the sieve                      #
         ELSE            # use trial division by the sieved primes            #
            BOOL probably prime := TRUE;
            FOR d FROM 3 BY 2 WHILE d * d <= p AND probably prime DO
                IF prime[ d ] THEN probably prime := p MOD d /= 0 FI
            OD;
            probably prime
         FI; # is prime #
    # sets the elements of pp1 to the first UPB pp1 Pierpoint primes of the   #
    #       first kind and pp2 to the first UPB pp2 Pierpoint primes of the   #
    #      second kind                                                        #
    PROC find pierpoint = ( REF[]INT pp1, pp2 )VOID:
         BEGIN
            # saved 3-smooth values                                           #
            # - only the currently active part of the seuence is kept         #
            INT three smooth limit = 33;
            [ 1 : three smooth limit * 3 ]INT s3s; FOR i TO UPB s3s DO s3s[ i ] := 0 OD;
            INT pp1 pos := LWB pp1 - 1, pp2 pos := LWB pp2 - 1;
            INT pp1 max  = UPB pp1;
            INT pp2 max  = UPB pp2;
            INT p2, p3, last2, last3;
            INT s pos := s3s[ 1 ] := last2 := last3 := p2 := p3 := 1;
            FOR n FROM 2 WHILE pp1 pos < pp1 max OR pp2 pos < pp2 max DO
                # the next 3-smooth number is the lowest of the next          #
                #     multiples of 2 and 3                                    #
                INT m = min( p2, p3 );
                IF pp1 pos < pp1 max THEN
                    IF  INT first = m + 1;
                        is prime( first )
                    THEN # have a Pierpoint prime of the first kind           #
                        pp1[ pp1 pos +:= 1 ] := first
                    FI
                FI;
                IF pp2 pos < pp2 max THEN
                    IF  INT second = m - 1;
                        is prime( second )
                    THEN # have a Pierpoint prime of the second kind          #
                        pp2[ pp2 pos +:= 1 ] := second
                    FI
                FI;
                s3s[ s pos +:= 1 ] := m;
                IF m = p2 THEN p2 := 2 * s3s[ last2 +:= 1 ] FI;
                IF m = p3 THEN p3 := 3 * s3s[ last3 +:= 1 ] FI;
                INT last min = IF last2 > last3 THEN last3 ELSE last2 FI;
                IF last min > three smooth limit THEN
                    # shuffle the sequence down, over the now unused bits     #
                    INT new pos := 0;
                    FOR pos FROM last min TO s pos DO
                        s3s[ new pos +:= 1 ] := s3s[ pos ]
                    OD;
                    INT diff := last min - 1;
                    last2   -:= diff;
                    last3   -:= diff;
                    s pos   -:= diff
                FI
            OD
         END; # find pierpoint #
    # prints a table of Pierpoint primes of the specified kind                #
    PROC print pierpoint = ( []INT primes, STRING kind )VOID:
         BEGIN
            print( ( "The first "
                   , whole( ( UPB primes + 1 ) - LWB primes, 0 )
                   , " Pierpoint primes of the "
                   , kind
                   , " kind:"
                   , newline
                   )
                 );
            INT p count := 0;
            FOR i FROM LWB primes TO UPB primes DO
                print( ( " ", whole( primes[ i ], -8 ) ) );
                IF ( p count +:= 1 ) MOD 10 = 0 THEN print( ( newline ) ) FI
            OD;
            print( ( newline ) )
         END; # print pierpoint #
    # find the first 50 Pierpoint primes of the first and second kinds        #
    INT max pierpoint    = 50;
    [ 1 : max pierpoint ]INT pfirst;
    [ 1 : max pierpoint ]INT psecond;
    find pierpoint( pfirst, psecond );
    # show the Pierpoint primes                                               #
    print pierpoint( pfirst,  "First"  );
    print pierpoint( psecond, "Second" )
END


#include <cassert>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>

using big_int = mpz_class;

bool is_prime(const big_int& n) {
    return mpz_probab_prime_p(n.get_mpz_t(), 25);
}

template <typename integer>
class n_smooth_generator {
public:
    explicit n_smooth_generator(size_t n);
    integer next();
    size_t size() const {
        return results_.size();
    }
private:
    std::vector<size_t> primes_;
    std::vector<size_t> index_;
    std::vector<integer> results_;
    std::vector<integer> queue_;
};

template <typename integer>
n_smooth_generator<integer>::n_smooth_generator(size_t n) {
    for (size_t p = 2; p <= n; ++p) {
        if (is_prime(p)) {
            primes_.push_back(p);
            queue_.push_back(p);
        }
    }
    index_.assign(primes_.size(), 0);
    results_.push_back(1);
}

template <typename integer>
integer n_smooth_generator<integer>::next() {
    integer last = results_.back();
    for (size_t i = 0, n = primes_.size(); i < n; ++i) {
        if (queue_[i] == last)
            queue_[i] = results_[++index_[i]] * primes_[i];
    }
    results_.push_back(*min_element(queue_.begin(), queue_.end()));
    return last;
}

void print_vector(const std::vector<big_int>& numbers) {
    for (size_t i = 0, n = numbers.size(); i < n; ++i) {
        std::cout << std::setw(9) << numbers[i];
        if ((i + 1) % 10 == 0)
            std::cout << '\n';
    }
    std::cout << '\n';
}

int main() {
    const int max = 250;
    std::vector<big_int> first, second;
    int count1 = 0;
    int count2 = 0;
    n_smooth_generator<big_int> smooth_gen(3);
    big_int p1, p2;

    while (count1 < max || count2 < max) {
        big_int n = smooth_gen.next();
        if (count1 < max && is_prime(n + 1)) {
            p1 = n + 1;
            if (first.size() < 50)
                first.push_back(p1);
            ++count1;
        }
        if (count2 < max && is_prime(n - 1)) {
            p2 = n - 1;
            if (second.size() < 50)
                second.push_back(p2);
            ++count2;
        }
    }

    std::cout << "First 50 Pierpont primes of the first kind:\n";
    print_vector(first);
    std::cout << "First 50 Pierpont primes of the second kind:\n";
    print_vector(second);

    std::cout << "250th Pierpont prime of the first kind: " << p1 << '\n';
    std::cout << "250th Pierpont prime of the second kind: " << p2 << '\n';
    return 0;
}


program Pierpont_primes;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.Math,
  System.StrUtils,
  System.Generics.Collections,
  System.Generics.Defaults,
  Velthuis.BigIntegers,
  Velthuis.BigIntegers.Primes;

function Pierpont(ulim, vlim: Integer; first: boolean): TArray<BigInteger>;
begin
  var p: BigInteger := 0;
  var p2: BigInteger := 1;
  var p3: BigInteger := 1;

  for var v := 0 to vlim - 1 do
  begin
    for var u := 0 to ulim - 1 do
    begin
      p := p2 * p3;
      if first then
        p := p + 1
      else
        p := p - 1;
      if IsProbablePrime(p, 10) then
      begin
        SetLength(result, Length(result) + 1);
        result[High(result)] := BigInteger(p);
      end;
      p2 := p2 * 2;
    end;
    p3 := p3 * 3;
    p2 := 1;
  end;

  TArray.sort<BigInteger>(Result, TComparer<BigInteger>.Construct(
    function(const Left, Right: BigInteger): Integer
    begin
      Result := BigInteger.Compare(Left, Right);
    end));
end;

begin

  writeln('First 50 Pierpont primes of the first kind:');
  var pp := Pierpont(120, 80, True);
  for var i := 0 to 49 do
  begin
    write(pp[i].ToString: 8, ' ');
    if ((i - 9) mod 10) = 0 then
      writeln;
  end;

  writeln('First 50 Pierpont primes of the second kind:');
  var pp2 := Pierpont(120, 80, False);
  for var i := 0 to 49 do
  begin
    write(pp2[i].ToString: 8, ' ');
    if ((i - 9) mod 10) = 0 then
      writeln;
  end;

  Writeln('250th Pierpont prime of the first kind:', pp[249].ToString);
  Writeln('250th Pierpont prime of the second  kind:', pp2[249].ToString);

  readln;
end.


// Pierpont primes . Nigel Galloway: March 19th., 2021
let fN g=let mutable g=g in ((fun()->g),fun()->g<-g+g;())
let fG y=let rec fG n g=seq{match g|>List.minBy(fun(n,_)->n()) with (f,s) when f()=n->yield f()+y; s(); yield! fG(n*3)(fN(n*3)::g)
                                                                   |(f,s)           ->yield f()+y; s(); yield! fG n g}
         seq{yield! fG 1 [fN 1]}|>Seq.filter isPrime
let pierpontT1,pierpontT2=fG 1,fG -1

pierpontT1|>Seq.take 50|>Seq.iter(printf "%d "); printfn ""
pierpontT2|>Seq.take 50|>Seq.iter(printf "%d "); printfn ""


USING: fry grouping io kernel locals make math math.functions
math.primes prettyprint sequences sorting ;

: pierpont ( ulim vlim quot -- seq )
    '[
        _ <iota> _ <iota> [
            [ 2 ] [ 3 ] bi* [ swap ^ ] [email protected] * 1 @
            dup prime? [ , ] [ drop ] if
        ] cartesian-each
    ] { } make natural-sort ; inline

: .fifty ( seq -- ) 50 head 10 group simple-table. nl ;

[let
    [ + ] [ - ] [ [ 120 80 ] dip pierpont ] [email protected]
    :> ( first second )

    "First 50 Pierpont primes of the first kind:" print
    first .fifty

    "First 50 Pierpont primes of the second kind:" print
    second .fifty

    "250th Pierpont prime of the first kind: " write
    249 first nth . nl

    "250th Pierpont prime of the second kind: " write
    249 second nth .
]


#define NPP 50

Function isPrime(Byval n As Ulongint) As Boolean
    If n < 2 Then Return false
    If n = 2 Then Return true
    If n Mod 2 = 0 Then Return false
    For i As Uinteger = 3 To Int(Sqr(n))+1 Step 2
        If n Mod i = 0 Then Return false
    Next i
    Return true
End Function

Function is_23(Byval n As Uinteger) As Boolean
    While n Mod 2 = 0
        n /= 2
    Wend
    While n Mod 3 = 0
        n /= 3
    Wend
    Return Iif(n=1, true, false)
End Function

Function isPierpont(n As Uinteger) As Uinteger
    If Not isPrime(n) Then Return 0  'not prime
    Dim As Uinteger p1 = is_23(n+1), p2 = is_23(n-1)
    If p1 And p2 Then Return 3       'pierpont prime of both kinds
    If p1 Then Return 1              'pierpont prime of the 1st kind
    If p2 Then Return 2              'pierpont prime of the 2nd kind
    Return 0                         'prime, but not pierpont
End Function

Dim As Uinteger pier(1 To 2, 1 To NPP), np(1 To 2) = {0, 0}
Dim As Uinteger x = 1, j
While np(1) <= NPP Or np(2) <= NPP
    x += 1
    j = isPierpont(x)
    If j > 0 Then
        If j Mod 2 = 1 Then
            np(1) += 1
            If np(1) <= NPP Then pier(1, np(1)) = x
        End If
        If j > 1 Then
            np(2) += 1
            If np(2) <= NPP Then pier(2, np(2)) = x
        End If
    End If
Wend

Print "First 50 Pierpoint primes of the first kind:"
For j = 1 To NPP
    Print Using " ########"; pier(2, j);
    If j Mod 10 = 0 Then Print
Next j
Print !"\nFirst 50 Pierpoint primes of the secod kind:"
For j = 1 To NPP
    Print Using " ########"; pier(1, j);
    If j Mod 10 = 0 Then Print
Next j


package main

import (
    "fmt"
    big "github.com/ncw/gmp"
    "sort"
)

var (
    one   = new(big.Int).SetUint64(1)
    two   = new(big.Int).SetUint64(2)
    three = new(big.Int).SetUint64(3)
)

func pierpont(ulim, vlim int, first bool) []*big.Int {
    p := new(big.Int)
    p2 := new(big.Int).Set(one)
    p3 := new(big.Int).Set(one)
    var pp []*big.Int
    for v := 0; v < vlim; v++ {
        for u := 0; u < ulim; u++ {
            p.Mul(p2, p3)
            if first {
                p.Add(p, one)
            } else {
                p.Sub(p, one)
            }
            if p.ProbablyPrime(10) {
                q := new(big.Int)
                q.Set(p)
                pp = append(pp, q)
            }
            p2.Mul(p2, two)
        }
        p3.Mul(p3, three)
        p2.Set(one)
    }
    sort.Slice(pp, func(i, j int) bool {
        return pp[i].Cmp(pp[j]) < 0
    })
    return pp
}
func main() {
    fmt.Println("First 50 Pierpont primes of the first kind:")
    pp := pierpont(120, 80, true)
    for i := 0; i < 50; i++ {
        fmt.Printf("%8d ", pp[i])
        if (i-9)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\nFirst 50 Pierpont primes of the second kind:")
    pp2 := pierpont(120, 80, false)
    for i := 0; i < 50; i++ {
        fmt.Printf("%8d ", pp2[i])
        if (i-9)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Println("\n250th Pierpont prime of the first kind:", pp[249])
    fmt.Println("\n250th Pierpont prime of the second kind:", pp2[249])
}


import Control.Monad (guard)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (Prime, unPrime, nextPrime)
import Math.NumberTheory.Primes.Testing (isPrime)
import Text.Printf (printf)

data PierPointKind = First | Second

merge :: Ord a => [a] -> [a] -> [a]
merge [] b = b
merge a@(x:xs) b@(y:ys) | x < y     = x : merge xs b
                        | otherwise = y : merge a ys

nSmooth :: Integer -> [Integer]
nSmooth p = 1 : foldr u [] factors
 where
  factors = takeWhile (<=p) primes
  primes = map unPrime [nextPrime 1..]
  u n s = r
   where
    r = merge s (map (n*) (1:r))

pierpoints :: PierPointKind -> [Integer]
pierpoints k = do
  n <- nSmooth 3
  let x = case k of First  -> succ n
                    Second -> pred n
  guard (isPrime x) >> [x]

main :: IO ()
main = do
  printf "\nFirst 50 Pierpont primes of the first kind:\n"
  mapM_ (\row -> mapM_ (printf "%12s" . commas) row >> printf "\n") (rows $ pierpoints First)
  printf "\nFirst 50 Pierpont primes of the second kind:\n"
  mapM_ (\row -> mapM_ (printf "%12s" . commas) row >> printf "\n") (rows $ pierpoints Second)
  printf "\n250th Pierpont prime of the first kind: %s\n" (commas $ pierpoints First !! 249)
  printf "\n250th Pierpont prime of the second kind: %s\n\n" (commas $ pierpoints Second !! 249)
 where
  rows = chunksOf 10 . take 50
  commas = reverse . intercalate "," . chunksOf 3 . reverse . show


import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

public class PierpontPrimes {

    public static void main(String[] args) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        display("First 50 Pierpont primes of the first kind:", pierpontPrimes(50, true));
        display("First 50 Pierpont primes of the second kind:", pierpontPrimes(50, false));
        System.out.printf("250th Pierpont prime of the first kind:     %s%n%n", nf.format(pierpontPrimes(250, true).get(249)));
        System.out.printf("250th Pierpont prime of the second kind: %s%n%n", nf.format(pierpontPrimes(250, false).get(249)));
    }

    private static void display(String message, List<BigInteger> primes) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        System.out.printf("%s%n", message);
        for ( int i = 1 ; i <= primes.size() ; i++ ) {
            System.out.printf("%10s  ", nf.format(primes.get(i-1)));
            if ( i % 10 == 0 ) {
                System.out.printf("%n");
            }
        }
        System.out.printf("%n");
    }

    public static List<BigInteger> pierpontPrimes(int n, boolean first) {
        List<BigInteger> primes = new ArrayList<BigInteger>();
        if ( first ) {
            primes.add(BigInteger.valueOf(2));
            n -= 1;
        }

        BigInteger two = BigInteger.valueOf(2);
        BigInteger twoTest = two;
        BigInteger three = BigInteger.valueOf(3);
        BigInteger threeTest = three;
        int twoIndex = 0, threeIndex = 0;
        List<BigInteger> twoSmooth = new ArrayList<BigInteger>();

        BigInteger one = BigInteger.ONE;
        BigInteger mOne = BigInteger.valueOf(-1);
        int count = 0;
        while ( count < n ) {
            BigInteger min = twoTest.min(threeTest);
            twoSmooth.add(min);
            if ( min.compareTo(twoTest) == 0 ) {
                twoTest = two.multiply(twoSmooth.get(twoIndex));
                twoIndex++;
            }
            if ( min.compareTo(threeTest) == 0 ) {
                threeTest = three.multiply(twoSmooth.get(threeIndex));
                threeIndex++;
            }
            BigInteger test = min.add(first ? one : mOne);
            if ( test.isProbablePrime(10) ) {
                primes.add(test);
                count++;
            }
        }
        return primes;
    }

}


def is_prime:
  . as $n
  | if ($n < 2)         then false
    elif ($n % 2 == 0)  then $n == 2
    elif ($n % 3 == 0)  then $n == 3
    elif ($n % 5 == 0)  then $n == 5
    elif ($n % 7 == 0)  then $n == 7
    elif ($n % 11 == 0) then $n == 11
    elif ($n % 13 == 0) then $n == 13
    elif ($n % 17 == 0) then $n == 17
    elif ($n % 19 == 0) then $n == 19
    else {i:23}
         | until( (.i * .i) > $n or ($n % .i == 0); .i += 2)
	 | .i * .i > $n
    end;

# pretty-printing
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;

def nwise($n):
  def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
  n;

def table($ncols; $colwidth):
  nwise($ncols) | map(lpad($colwidth)) | join(" ");


using Primes

function pierponts(N, firstkind = true)
    ret, incdec = BigInt[], firstkind ? 1 : -1
    for k2 in 0:10000, k3 in 0:k2, switch in false:true
        i, j = switch ? (k3, k2) : (k2, k3)
        n = BigInt(2)^i * BigInt(3)^j + incdec
        if isprime(n) && !(n in ret)
            push!(ret, n)
            if length(ret) == N * 2
                return sort(ret)[1:N]
            end
        end
    end
    throw("Failed to find $(N * 2) primes")
end

println("The first 50 Pierpont primes (first kind) are: ", pierponts(50))

println("\nThe first 50 Pierpont primes (second kind) are: ", pierponts(50, false))

println("\nThe 250th Pierpont prime (first kind) is: ", pierponts(250)[250])

println("\nThe 250th Pierpont prime (second kind) is: ", pierponts(250, false)[250])

println("\nThe 1000th Pierpont prime (first kind) is: ", pierponts(1000)[1000])

println("\nThe 1000th Pierpont prime (second kind) is: ", pierponts(1000, false)[1000])

println("\nThe 2000th Pierpont prime (first kind) is: ", pierponts(2000)[2000])

println("\nThe 2000th Pierpont prime (second kind) is: ", pierponts(2000, false)[2000])