Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write a version of this J function in C with identical behavior.
deck=: ,/ 'A23456789TJQK' ,"0/ 7 u: '♣♦♥♠' srnd=: 3 :'SEED=:{.y,11982' srnd '' seed=: do bind 'SEED' rnd=: (2^16) <.@%~ (2^31) srnd@| 2531011 + 214013 * seed pairs=: <@<@~.@(<: , (| rnd))@>:@i.@-@# swaps=: [: > C.&.>/@|.@; deal=: |.@(swaps pairs) bind deck show=: (,"2)@:(_8 ]\ ' '&,.)
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Convert the following code from J to C#, ensuring the logic remains intact.
deck=: ,/ 'A23456789TJQK' ,"0/ 7 u: '♣♦♥♠' srnd=: 3 :'SEED=:{.y,11982' srnd '' seed=: do bind 'SEED' rnd=: (2^16) <.@%~ (2^31) srnd@| 2531011 + 214013 * seed pairs=: <@<@~.@(<: , (| rnd))@>:@i.@-@# swaps=: [: > C.&.>/@|.@; deal=: |.@(swaps pairs) bind deck show=: (,"2)@:(_8 ]\ ' '&,.)
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Maintain the same structure and functionality when rewriting this code in C++.
deck=: ,/ 'A23456789TJQK' ,"0/ 7 u: '♣♦♥♠' srnd=: 3 :'SEED=:{.y,11982' srnd '' seed=: do bind 'SEED' rnd=: (2^16) <.@%~ (2^31) srnd@| 2531011 + 214013 * seed pairs=: <@<@~.@(<: , (| rnd))@>:@i.@-@# swaps=: [: > C.&.>/@|.@; deal=: |.@(swaps pairs) bind deck show=: (,"2)@:(_8 ]\ ' '&,.)
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Port the provided J code into Java while preserving the original functionality.
deck=: ,/ 'A23456789TJQK' ,"0/ 7 u: '♣♦♥♠' srnd=: 3 :'SEED=:{.y,11982' srnd '' seed=: do bind 'SEED' rnd=: (2^16) <.@%~ (2^31) srnd@| 2531011 + 214013 * seed pairs=: <@<@~.@(<: , (| rnd))@>:@i.@-@# swaps=: [: > C.&.>/@|.@; deal=: |.@(swaps pairs) bind deck show=: (,"2)@:(_8 ]\ ' '&,.)
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Generate a Python translation of this J snippet without changing its computational steps.
deck=: ,/ 'A23456789TJQK' ,"0/ 7 u: '♣♦♥♠' srnd=: 3 :'SEED=:{.y,11982' srnd '' seed=: do bind 'SEED' rnd=: (2^16) <.@%~ (2^31) srnd@| 2531011 + 214013 * seed pairs=: <@<@~.@(<: , (| rnd))@>:@i.@-@# swaps=: [: > C.&.>/@|.@; deal=: |.@(swaps pairs) bind deck show=: (,"2)@:(_8 ]\ ' '&,.)
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Translate this program into Go but keep the logic exactly as in J.
deck=: ,/ 'A23456789TJQK' ,"0/ 7 u: '♣♦♥♠' srnd=: 3 :'SEED=:{.y,11982' srnd '' seed=: do bind 'SEED' rnd=: (2^16) <.@%~ (2^31) srnd@| 2531011 + 214013 * seed pairs=: <@<@~.@(<: , (| rnd))@>:@i.@-@# swaps=: [: > C.&.>/@|.@; deal=: |.@(swaps pairs) bind deck show=: (,"2)@:(_8 ]\ ' '&,.)
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Transform the following Julia implementation into C, maintaining the same output and logic.
const rank = split("A23456789TJQK", "") const suit = split("♣♦♥♠", "") const deck = Vector{String}() const mslcg = [0] rng() = (mslcg[1] = ((mslcg[1] * 214013 + 2531011) & 0x7fffffff)) >> 16 initdeck() = for r in rank, s in suit push!(deck, "$r$s") end function deal(num = rand(UInt,1)[1] % 32000 + 1) initdeck() mslcg[1] = num println("\nGame while length(deck) > 0 choice = rng() % length(deck) + 1 deck[choice], deck[end] = deck[end], deck[choice] print(" ", pop!(deck), length(deck) % 8 == 4 ? "\n" : "") end end deal(1) deal(617) deal()
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Port the following code from Julia to C# with equivalent syntax and logic.
const rank = split("A23456789TJQK", "") const suit = split("♣♦♥♠", "") const deck = Vector{String}() const mslcg = [0] rng() = (mslcg[1] = ((mslcg[1] * 214013 + 2531011) & 0x7fffffff)) >> 16 initdeck() = for r in rank, s in suit push!(deck, "$r$s") end function deal(num = rand(UInt,1)[1] % 32000 + 1) initdeck() mslcg[1] = num println("\nGame while length(deck) > 0 choice = rng() % length(deck) + 1 deck[choice], deck[end] = deck[end], deck[choice] print(" ", pop!(deck), length(deck) % 8 == 4 ? "\n" : "") end end deal(1) deal(617) deal()
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Port the following code from Julia to C++ with equivalent syntax and logic.
const rank = split("A23456789TJQK", "") const suit = split("♣♦♥♠", "") const deck = Vector{String}() const mslcg = [0] rng() = (mslcg[1] = ((mslcg[1] * 214013 + 2531011) & 0x7fffffff)) >> 16 initdeck() = for r in rank, s in suit push!(deck, "$r$s") end function deal(num = rand(UInt,1)[1] % 32000 + 1) initdeck() mslcg[1] = num println("\nGame while length(deck) > 0 choice = rng() % length(deck) + 1 deck[choice], deck[end] = deck[end], deck[choice] print(" ", pop!(deck), length(deck) % 8 == 4 ? "\n" : "") end end deal(1) deal(617) deal()
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Produce a language-to-language conversion: from Julia to Java, same semantics.
const rank = split("A23456789TJQK", "") const suit = split("♣♦♥♠", "") const deck = Vector{String}() const mslcg = [0] rng() = (mslcg[1] = ((mslcg[1] * 214013 + 2531011) & 0x7fffffff)) >> 16 initdeck() = for r in rank, s in suit push!(deck, "$r$s") end function deal(num = rand(UInt,1)[1] % 32000 + 1) initdeck() mslcg[1] = num println("\nGame while length(deck) > 0 choice = rng() % length(deck) + 1 deck[choice], deck[end] = deck[end], deck[choice] print(" ", pop!(deck), length(deck) % 8 == 4 ? "\n" : "") end end deal(1) deal(617) deal()
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Write the same algorithm in Python as shown in this Julia implementation.
const rank = split("A23456789TJQK", "") const suit = split("♣♦♥♠", "") const deck = Vector{String}() const mslcg = [0] rng() = (mslcg[1] = ((mslcg[1] * 214013 + 2531011) & 0x7fffffff)) >> 16 initdeck() = for r in rank, s in suit push!(deck, "$r$s") end function deal(num = rand(UInt,1)[1] % 32000 + 1) initdeck() mslcg[1] = num println("\nGame while length(deck) > 0 choice = rng() % length(deck) + 1 deck[choice], deck[end] = deck[end], deck[choice] print(" ", pop!(deck), length(deck) % 8 == 4 ? "\n" : "") end end deal(1) deal(617) deal()
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Generate a Go translation of this Julia snippet without changing its computational steps.
const rank = split("A23456789TJQK", "") const suit = split("♣♦♥♠", "") const deck = Vector{String}() const mslcg = [0] rng() = (mslcg[1] = ((mslcg[1] * 214013 + 2531011) & 0x7fffffff)) >> 16 initdeck() = for r in rank, s in suit push!(deck, "$r$s") end function deal(num = rand(UInt,1)[1] % 32000 + 1) initdeck() mslcg[1] = num println("\nGame while length(deck) > 0 choice = rng() % length(deck) + 1 deck[choice], deck[end] = deck[end], deck[choice] print(" ", pop!(deck), length(deck) % 8 == 4 ? "\n" : "") end end deal(1) deal(617) deal()
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Produce a language-to-language conversion: from Lua to C, same semantics.
deck = {} rank = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"} suit = {"C", "D", "H", "S"} two31, state = bit32.lshift(1, 31), 0 function rng() state = (214013 * state + 2531011) % two31 return bit32.rshift(state, 16) end function initdeck() for i, r in ipairs(rank) do for j, s in ipairs(suit) do table.insert(deck, r .. s) end end end function deal(num) initdeck() state = num print("Game #" .. num) repeat choice = rng(num) % #deck + 1 deck[choice], deck[#deck] = deck[#deck], deck[choice] io.write(" " .. deck[#deck]) if (#deck % 8 == 5) then print() end deck[#deck] = nil until #deck == 0 print() end deal(1) deal(617)
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Rewrite the snippet below in C# so it works the same as the original Lua code.
deck = {} rank = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"} suit = {"C", "D", "H", "S"} two31, state = bit32.lshift(1, 31), 0 function rng() state = (214013 * state + 2531011) % two31 return bit32.rshift(state, 16) end function initdeck() for i, r in ipairs(rank) do for j, s in ipairs(suit) do table.insert(deck, r .. s) end end end function deal(num) initdeck() state = num print("Game #" .. num) repeat choice = rng(num) % #deck + 1 deck[choice], deck[#deck] = deck[#deck], deck[choice] io.write(" " .. deck[#deck]) if (#deck % 8 == 5) then print() end deck[#deck] = nil until #deck == 0 print() end deal(1) deal(617)
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Change the programming language of this snippet from Lua to C++ without modifying what it does.
deck = {} rank = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"} suit = {"C", "D", "H", "S"} two31, state = bit32.lshift(1, 31), 0 function rng() state = (214013 * state + 2531011) % two31 return bit32.rshift(state, 16) end function initdeck() for i, r in ipairs(rank) do for j, s in ipairs(suit) do table.insert(deck, r .. s) end end end function deal(num) initdeck() state = num print("Game #" .. num) repeat choice = rng(num) % #deck + 1 deck[choice], deck[#deck] = deck[#deck], deck[choice] io.write(" " .. deck[#deck]) if (#deck % 8 == 5) then print() end deck[#deck] = nil until #deck == 0 print() end deal(1) deal(617)
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Generate an equivalent Java version of this Lua code.
deck = {} rank = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"} suit = {"C", "D", "H", "S"} two31, state = bit32.lshift(1, 31), 0 function rng() state = (214013 * state + 2531011) % two31 return bit32.rshift(state, 16) end function initdeck() for i, r in ipairs(rank) do for j, s in ipairs(suit) do table.insert(deck, r .. s) end end end function deal(num) initdeck() state = num print("Game #" .. num) repeat choice = rng(num) % #deck + 1 deck[choice], deck[#deck] = deck[#deck], deck[choice] io.write(" " .. deck[#deck]) if (#deck % 8 == 5) then print() end deck[#deck] = nil until #deck == 0 print() end deal(1) deal(617)
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Port the provided Lua code into Python while preserving the original functionality.
deck = {} rank = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"} suit = {"C", "D", "H", "S"} two31, state = bit32.lshift(1, 31), 0 function rng() state = (214013 * state + 2531011) % two31 return bit32.rshift(state, 16) end function initdeck() for i, r in ipairs(rank) do for j, s in ipairs(suit) do table.insert(deck, r .. s) end end end function deal(num) initdeck() state = num print("Game #" .. num) repeat choice = rng(num) % #deck + 1 deck[choice], deck[#deck] = deck[#deck], deck[choice] io.write(" " .. deck[#deck]) if (#deck % 8 == 5) then print() end deck[#deck] = nil until #deck == 0 print() end deal(1) deal(617)
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Translate this program into Go but keep the logic exactly as in Lua.
deck = {} rank = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"} suit = {"C", "D", "H", "S"} two31, state = bit32.lshift(1, 31), 0 function rng() state = (214013 * state + 2531011) % two31 return bit32.rshift(state, 16) end function initdeck() for i, r in ipairs(rank) do for j, s in ipairs(suit) do table.insert(deck, r .. s) end end end function deal(num) initdeck() state = num print("Game #" .. num) repeat choice = rng(num) % #deck + 1 deck[choice], deck[#deck] = deck[#deck], deck[choice] io.write(" " .. deck[#deck]) if (#deck % 8 == 5) then print() end deck[#deck] = nil until #deck == 0 print() end deal(1) deal(617)
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Produce a language-to-language conversion: from Mathematica to C, same semantics.
next[last_] := Mod[214013 last + 2531011, 2^31]; deal[n_] := Module[{last = n, idx, deck = StringJoin /@ Tuples[{{"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"}, {"C", "D", "H", "S"}}], res = {}}, While[deck != {}, last = next[last]; idx = Mod[BitShiftRight[last, 16], Length[deck]] + 1; deck = ReplacePart[deck, {idx -> deck[[-1]], -1 -> deck[[idx]]}]; AppendTo[res, deck[[-1]]]; deck = deck[[;; -2]]]; res]; format[deal_] := Grid[Partition[deal, 8, 8, {1, 4}, Null]]; Print[format[deal[1]]]; Print[format[deal[617]]];
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Translate this program into C# but keep the logic exactly as in Mathematica.
next[last_] := Mod[214013 last + 2531011, 2^31]; deal[n_] := Module[{last = n, idx, deck = StringJoin /@ Tuples[{{"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"}, {"C", "D", "H", "S"}}], res = {}}, While[deck != {}, last = next[last]; idx = Mod[BitShiftRight[last, 16], Length[deck]] + 1; deck = ReplacePart[deck, {idx -> deck[[-1]], -1 -> deck[[idx]]}]; AppendTo[res, deck[[-1]]]; deck = deck[[;; -2]]]; res]; format[deal_] := Grid[Partition[deal, 8, 8, {1, 4}, Null]]; Print[format[deal[1]]]; Print[format[deal[617]]];
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Please provide an equivalent version of this Mathematica code in C++.
next[last_] := Mod[214013 last + 2531011, 2^31]; deal[n_] := Module[{last = n, idx, deck = StringJoin /@ Tuples[{{"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"}, {"C", "D", "H", "S"}}], res = {}}, While[deck != {}, last = next[last]; idx = Mod[BitShiftRight[last, 16], Length[deck]] + 1; deck = ReplacePart[deck, {idx -> deck[[-1]], -1 -> deck[[idx]]}]; AppendTo[res, deck[[-1]]]; deck = deck[[;; -2]]]; res]; format[deal_] := Grid[Partition[deal, 8, 8, {1, 4}, Null]]; Print[format[deal[1]]]; Print[format[deal[617]]];
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Preserve the algorithm and functionality while converting the code from Mathematica to Java.
next[last_] := Mod[214013 last + 2531011, 2^31]; deal[n_] := Module[{last = n, idx, deck = StringJoin /@ Tuples[{{"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"}, {"C", "D", "H", "S"}}], res = {}}, While[deck != {}, last = next[last]; idx = Mod[BitShiftRight[last, 16], Length[deck]] + 1; deck = ReplacePart[deck, {idx -> deck[[-1]], -1 -> deck[[idx]]}]; AppendTo[res, deck[[-1]]]; deck = deck[[;; -2]]]; res]; format[deal_] := Grid[Partition[deal, 8, 8, {1, 4}, Null]]; Print[format[deal[1]]]; Print[format[deal[617]]];
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Translate this program into Python but keep the logic exactly as in Mathematica.
next[last_] := Mod[214013 last + 2531011, 2^31]; deal[n_] := Module[{last = n, idx, deck = StringJoin /@ Tuples[{{"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"}, {"C", "D", "H", "S"}}], res = {}}, While[deck != {}, last = next[last]; idx = Mod[BitShiftRight[last, 16], Length[deck]] + 1; deck = ReplacePart[deck, {idx -> deck[[-1]], -1 -> deck[[idx]]}]; AppendTo[res, deck[[-1]]]; deck = deck[[;; -2]]]; res]; format[deal_] := Grid[Partition[deal, 8, 8, {1, 4}, Null]]; Print[format[deal[1]]]; Print[format[deal[617]]];
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Change the following Mathematica code into Go without altering its purpose.
next[last_] := Mod[214013 last + 2531011, 2^31]; deal[n_] := Module[{last = n, idx, deck = StringJoin /@ Tuples[{{"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"}, {"C", "D", "H", "S"}}], res = {}}, While[deck != {}, last = next[last]; idx = Mod[BitShiftRight[last, 16], Length[deck]] + 1; deck = ReplacePart[deck, {idx -> deck[[-1]], -1 -> deck[[idx]]}]; AppendTo[res, deck[[-1]]]; deck = deck[[;; -2]]]; res]; format[deal_] := Grid[Partition[deal, 8, 8, {1, 4}, Null]]; Print[format[deal[1]]]; Print[format[deal[617]]];
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Port the provided Nim code into C while preserving the original functionality.
import sequtils, strutils, os proc randomGenerator(seed: int): iterator: int = var state = seed return iterator: int = while true: state = (state * 214013 + 2531011) and int32.high yield state shr 16 proc deal(seed: int): seq[int] = const nc = 52 result = toSeq countdown(nc - 1, 0) var rnd = randomGenerator seed for i in 0 ..< nc: let r = rnd() let j = (nc - 1) - r mod (nc - i) swap result[i], result[j] proc show(cards: seq[int]) = var l = newSeq[string]() for c in cards: l.add "A23456789TJQK"[c div 4] & "CDHS"[c mod 4] for i in countup(0, cards.high, 8): echo " ", l[i..min(i+7, l.high)].join(" ") let seed = if paramCount() == 1: paramStr(1).parseInt else: 11982 echo "Hand ", seed let deck = deal seed show deck
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Preserve the algorithm and functionality while converting the code from Nim to C#.
import sequtils, strutils, os proc randomGenerator(seed: int): iterator: int = var state = seed return iterator: int = while true: state = (state * 214013 + 2531011) and int32.high yield state shr 16 proc deal(seed: int): seq[int] = const nc = 52 result = toSeq countdown(nc - 1, 0) var rnd = randomGenerator seed for i in 0 ..< nc: let r = rnd() let j = (nc - 1) - r mod (nc - i) swap result[i], result[j] proc show(cards: seq[int]) = var l = newSeq[string]() for c in cards: l.add "A23456789TJQK"[c div 4] & "CDHS"[c mod 4] for i in countup(0, cards.high, 8): echo " ", l[i..min(i+7, l.high)].join(" ") let seed = if paramCount() == 1: paramStr(1).parseInt else: 11982 echo "Hand ", seed let deck = deal seed show deck
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Translate the given Nim code snippet into C++ without altering its behavior.
import sequtils, strutils, os proc randomGenerator(seed: int): iterator: int = var state = seed return iterator: int = while true: state = (state * 214013 + 2531011) and int32.high yield state shr 16 proc deal(seed: int): seq[int] = const nc = 52 result = toSeq countdown(nc - 1, 0) var rnd = randomGenerator seed for i in 0 ..< nc: let r = rnd() let j = (nc - 1) - r mod (nc - i) swap result[i], result[j] proc show(cards: seq[int]) = var l = newSeq[string]() for c in cards: l.add "A23456789TJQK"[c div 4] & "CDHS"[c mod 4] for i in countup(0, cards.high, 8): echo " ", l[i..min(i+7, l.high)].join(" ") let seed = if paramCount() == 1: paramStr(1).parseInt else: 11982 echo "Hand ", seed let deck = deal seed show deck
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Write the same algorithm in Java as shown in this Nim implementation.
import sequtils, strutils, os proc randomGenerator(seed: int): iterator: int = var state = seed return iterator: int = while true: state = (state * 214013 + 2531011) and int32.high yield state shr 16 proc deal(seed: int): seq[int] = const nc = 52 result = toSeq countdown(nc - 1, 0) var rnd = randomGenerator seed for i in 0 ..< nc: let r = rnd() let j = (nc - 1) - r mod (nc - i) swap result[i], result[j] proc show(cards: seq[int]) = var l = newSeq[string]() for c in cards: l.add "A23456789TJQK"[c div 4] & "CDHS"[c mod 4] for i in countup(0, cards.high, 8): echo " ", l[i..min(i+7, l.high)].join(" ") let seed = if paramCount() == 1: paramStr(1).parseInt else: 11982 echo "Hand ", seed let deck = deal seed show deck
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Convert this Nim snippet to Python and keep its semantics consistent.
import sequtils, strutils, os proc randomGenerator(seed: int): iterator: int = var state = seed return iterator: int = while true: state = (state * 214013 + 2531011) and int32.high yield state shr 16 proc deal(seed: int): seq[int] = const nc = 52 result = toSeq countdown(nc - 1, 0) var rnd = randomGenerator seed for i in 0 ..< nc: let r = rnd() let j = (nc - 1) - r mod (nc - i) swap result[i], result[j] proc show(cards: seq[int]) = var l = newSeq[string]() for c in cards: l.add "A23456789TJQK"[c div 4] & "CDHS"[c mod 4] for i in countup(0, cards.high, 8): echo " ", l[i..min(i+7, l.high)].join(" ") let seed = if paramCount() == 1: paramStr(1).parseInt else: 11982 echo "Hand ", seed let deck = deal seed show deck
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Translate this program into Go but keep the logic exactly as in Nim.
import sequtils, strutils, os proc randomGenerator(seed: int): iterator: int = var state = seed return iterator: int = while true: state = (state * 214013 + 2531011) and int32.high yield state shr 16 proc deal(seed: int): seq[int] = const nc = 52 result = toSeq countdown(nc - 1, 0) var rnd = randomGenerator seed for i in 0 ..< nc: let r = rnd() let j = (nc - 1) - r mod (nc - i) swap result[i], result[j] proc show(cards: seq[int]) = var l = newSeq[string]() for c in cards: l.add "A23456789TJQK"[c div 4] & "CDHS"[c mod 4] for i in countup(0, cards.high, 8): echo " ", l[i..min(i+7, l.high)].join(" ") let seed = if paramCount() == 1: paramStr(1).parseInt else: 11982 echo "Hand ", seed let deck = deal seed show deck
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Transform the following OCaml implementation into C, maintaining the same output and logic.
let srnd x = let seed = ref x in fun () -> seed := (!seed * 214013 + 2531011) land 0x7fffffff; !seed lsr 16 let deal s = let rnd = srnd s in let t = Array.init 52 (fun i -> i) in let cards = Array.init 52 (fun j -> let n = 52 - j in let i = rnd() mod n in let this = t.(i) in t.(i) <- t.(pred n); this) in (cards) let show cards = let suits = "CDHS" and nums = "A23456789TJQK" in Array.iteri (fun i card -> Printf.printf "%c%c%c" nums.[card / 4] suits.[card mod 4] (if (i mod 8) = 7 then '\n' else ' ') ) cards; print_newline() let () = let s = try int_of_string Sys.argv.(1) with _ -> 11982 in Printf.printf "Deal %d:\n" s; let cards = deal s in show cards
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Write the same algorithm in C# as shown in this OCaml implementation.
let srnd x = let seed = ref x in fun () -> seed := (!seed * 214013 + 2531011) land 0x7fffffff; !seed lsr 16 let deal s = let rnd = srnd s in let t = Array.init 52 (fun i -> i) in let cards = Array.init 52 (fun j -> let n = 52 - j in let i = rnd() mod n in let this = t.(i) in t.(i) <- t.(pred n); this) in (cards) let show cards = let suits = "CDHS" and nums = "A23456789TJQK" in Array.iteri (fun i card -> Printf.printf "%c%c%c" nums.[card / 4] suits.[card mod 4] (if (i mod 8) = 7 then '\n' else ' ') ) cards; print_newline() let () = let s = try int_of_string Sys.argv.(1) with _ -> 11982 in Printf.printf "Deal %d:\n" s; let cards = deal s in show cards
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Keep all operations the same but rewrite the snippet in C++.
let srnd x = let seed = ref x in fun () -> seed := (!seed * 214013 + 2531011) land 0x7fffffff; !seed lsr 16 let deal s = let rnd = srnd s in let t = Array.init 52 (fun i -> i) in let cards = Array.init 52 (fun j -> let n = 52 - j in let i = rnd() mod n in let this = t.(i) in t.(i) <- t.(pred n); this) in (cards) let show cards = let suits = "CDHS" and nums = "A23456789TJQK" in Array.iteri (fun i card -> Printf.printf "%c%c%c" nums.[card / 4] suits.[card mod 4] (if (i mod 8) = 7 then '\n' else ' ') ) cards; print_newline() let () = let s = try int_of_string Sys.argv.(1) with _ -> 11982 in Printf.printf "Deal %d:\n" s; let cards = deal s in show cards
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Keep all operations the same but rewrite the snippet in Java.
let srnd x = let seed = ref x in fun () -> seed := (!seed * 214013 + 2531011) land 0x7fffffff; !seed lsr 16 let deal s = let rnd = srnd s in let t = Array.init 52 (fun i -> i) in let cards = Array.init 52 (fun j -> let n = 52 - j in let i = rnd() mod n in let this = t.(i) in t.(i) <- t.(pred n); this) in (cards) let show cards = let suits = "CDHS" and nums = "A23456789TJQK" in Array.iteri (fun i card -> Printf.printf "%c%c%c" nums.[card / 4] suits.[card mod 4] (if (i mod 8) = 7 then '\n' else ' ') ) cards; print_newline() let () = let s = try int_of_string Sys.argv.(1) with _ -> 11982 in Printf.printf "Deal %d:\n" s; let cards = deal s in show cards
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Change the programming language of this snippet from OCaml to Python without modifying what it does.
let srnd x = let seed = ref x in fun () -> seed := (!seed * 214013 + 2531011) land 0x7fffffff; !seed lsr 16 let deal s = let rnd = srnd s in let t = Array.init 52 (fun i -> i) in let cards = Array.init 52 (fun j -> let n = 52 - j in let i = rnd() mod n in let this = t.(i) in t.(i) <- t.(pred n); this) in (cards) let show cards = let suits = "CDHS" and nums = "A23456789TJQK" in Array.iteri (fun i card -> Printf.printf "%c%c%c" nums.[card / 4] suits.[card mod 4] (if (i mod 8) = 7 then '\n' else ' ') ) cards; print_newline() let () = let s = try int_of_string Sys.argv.(1) with _ -> 11982 in Printf.printf "Deal %d:\n" s; let cards = deal s in show cards
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Rewrite this program in Go while keeping its functionality equivalent to the OCaml version.
let srnd x = let seed = ref x in fun () -> seed := (!seed * 214013 + 2531011) land 0x7fffffff; !seed lsr 16 let deal s = let rnd = srnd s in let t = Array.init 52 (fun i -> i) in let cards = Array.init 52 (fun j -> let n = 52 - j in let i = rnd() mod n in let this = t.(i) in t.(i) <- t.(pred n); this) in (cards) let show cards = let suits = "CDHS" and nums = "A23456789TJQK" in Array.iteri (fun i card -> Printf.printf "%c%c%c" nums.[card / 4] suits.[card mod 4] (if (i mod 8) = 7 then '\n' else ' ') ) cards; print_newline() let () = let s = try int_of_string Sys.argv.(1) with _ -> 11982 in Printf.printf "Deal %d:\n" s; let cards = deal s in show cards
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Write a version of this Perl function in C with identical behavior.
use strict; use warnings; use utf8; sub deal { my $s = shift; my $rnd = sub { return (($s = ($s * 214013 + 2531011) & 0x7fffffff) >> 16 ); }; my @d; for my $b (split "", "A23456789TJQK") { push @d, map("$_$b", qw/♣ ♦ ♥ ♠/); } for my $idx (reverse 0 .. $ my $r = $rnd->() % ($idx + 1); @d[$r, $idx] = @d[$idx, $r]; } return [reverse @d]; } my $hand_idx = shift(@ARGV) // 11_982; my $cards = deal($hand_idx); my $num_cards_in_height = 8; my $string = ''; while (@$cards) { $string .= join(' ', splice(@$cards, 0, 8)) . "\n"; } binmode STDOUT, ':encoding(utf-8)'; print "Hand $hand_idx\n"; print $string;
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Produce a language-to-language conversion: from Perl to C#, same semantics.
use strict; use warnings; use utf8; sub deal { my $s = shift; my $rnd = sub { return (($s = ($s * 214013 + 2531011) & 0x7fffffff) >> 16 ); }; my @d; for my $b (split "", "A23456789TJQK") { push @d, map("$_$b", qw/♣ ♦ ♥ ♠/); } for my $idx (reverse 0 .. $ my $r = $rnd->() % ($idx + 1); @d[$r, $idx] = @d[$idx, $r]; } return [reverse @d]; } my $hand_idx = shift(@ARGV) // 11_982; my $cards = deal($hand_idx); my $num_cards_in_height = 8; my $string = ''; while (@$cards) { $string .= join(' ', splice(@$cards, 0, 8)) . "\n"; } binmode STDOUT, ':encoding(utf-8)'; print "Hand $hand_idx\n"; print $string;
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Write a version of this Perl function in C++ with identical behavior.
use strict; use warnings; use utf8; sub deal { my $s = shift; my $rnd = sub { return (($s = ($s * 214013 + 2531011) & 0x7fffffff) >> 16 ); }; my @d; for my $b (split "", "A23456789TJQK") { push @d, map("$_$b", qw/♣ ♦ ♥ ♠/); } for my $idx (reverse 0 .. $ my $r = $rnd->() % ($idx + 1); @d[$r, $idx] = @d[$idx, $r]; } return [reverse @d]; } my $hand_idx = shift(@ARGV) // 11_982; my $cards = deal($hand_idx); my $num_cards_in_height = 8; my $string = ''; while (@$cards) { $string .= join(' ', splice(@$cards, 0, 8)) . "\n"; } binmode STDOUT, ':encoding(utf-8)'; print "Hand $hand_idx\n"; print $string;
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Keep all operations the same but rewrite the snippet in Java.
use strict; use warnings; use utf8; sub deal { my $s = shift; my $rnd = sub { return (($s = ($s * 214013 + 2531011) & 0x7fffffff) >> 16 ); }; my @d; for my $b (split "", "A23456789TJQK") { push @d, map("$_$b", qw/♣ ♦ ♥ ♠/); } for my $idx (reverse 0 .. $ my $r = $rnd->() % ($idx + 1); @d[$r, $idx] = @d[$idx, $r]; } return [reverse @d]; } my $hand_idx = shift(@ARGV) // 11_982; my $cards = deal($hand_idx); my $num_cards_in_height = 8; my $string = ''; while (@$cards) { $string .= join(' ', splice(@$cards, 0, 8)) . "\n"; } binmode STDOUT, ':encoding(utf-8)'; print "Hand $hand_idx\n"; print $string;
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Can you help me rewrite this code in Python instead of Perl, keeping it the same logically?
use strict; use warnings; use utf8; sub deal { my $s = shift; my $rnd = sub { return (($s = ($s * 214013 + 2531011) & 0x7fffffff) >> 16 ); }; my @d; for my $b (split "", "A23456789TJQK") { push @d, map("$_$b", qw/♣ ♦ ♥ ♠/); } for my $idx (reverse 0 .. $ my $r = $rnd->() % ($idx + 1); @d[$r, $idx] = @d[$idx, $r]; } return [reverse @d]; } my $hand_idx = shift(@ARGV) // 11_982; my $cards = deal($hand_idx); my $num_cards_in_height = 8; my $string = ''; while (@$cards) { $string .= join(' ', splice(@$cards, 0, 8)) . "\n"; } binmode STDOUT, ':encoding(utf-8)'; print "Hand $hand_idx\n"; print $string;
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Port the following code from Perl to Go with equivalent syntax and logic.
use strict; use warnings; use utf8; sub deal { my $s = shift; my $rnd = sub { return (($s = ($s * 214013 + 2531011) & 0x7fffffff) >> 16 ); }; my @d; for my $b (split "", "A23456789TJQK") { push @d, map("$_$b", qw/♣ ♦ ♥ ♠/); } for my $idx (reverse 0 .. $ my $r = $rnd->() % ($idx + 1); @d[$r, $idx] = @d[$idx, $r]; } return [reverse @d]; } my $hand_idx = shift(@ARGV) // 11_982; my $cards = deal($hand_idx); my $num_cards_in_height = 8; my $string = ''; while (@$cards) { $string .= join(' ', splice(@$cards, 0, 8)) . "\n"; } binmode STDOUT, ':encoding(utf-8)'; print "Hand $hand_idx\n"; print $string;
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Convert the following code from R to C, ensuring the logic remains intact.
library(gmp) rand_MS <- function(n = 1, seed = 1) { a <- as.bigz(214013) c <- as.bigz(2531011) m <- as.bigz(2^31) x <- rep(as.bigz(0), n) x[1] <- (a * as.bigz(seed) + c) %% m i <- 1 while (i < n) { x[i+1] <- (a * x[i] + c) %% m i <- i + 1 } as.integer(x / 2^16) } dealFreeCell <- function(seedNum) { deck <- paste(rep(c("A",2,3,4,5,6,7,8,9,10,"J","Q","K"), each = 4), c("C","D","H","S"), sep = "") cards = rand_MS(52,seedNum) for (i in 52:1) { cardToPick <- (cards[53-i]%% i)+1 deck[c(cardToPick,i)] <- deck[c(i, cardToPick)] } deck <- rev(deck) deal = matrix(c(deck,NA,NA,NA,NA),ncol = 8, byrow = TRUE) print(paste("Hand numer:",seedNum), quote = FALSE) print(deal, quote = FALSE, na.print = "") }
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Translate this program into C# but keep the logic exactly as in R.
library(gmp) rand_MS <- function(n = 1, seed = 1) { a <- as.bigz(214013) c <- as.bigz(2531011) m <- as.bigz(2^31) x <- rep(as.bigz(0), n) x[1] <- (a * as.bigz(seed) + c) %% m i <- 1 while (i < n) { x[i+1] <- (a * x[i] + c) %% m i <- i + 1 } as.integer(x / 2^16) } dealFreeCell <- function(seedNum) { deck <- paste(rep(c("A",2,3,4,5,6,7,8,9,10,"J","Q","K"), each = 4), c("C","D","H","S"), sep = "") cards = rand_MS(52,seedNum) for (i in 52:1) { cardToPick <- (cards[53-i]%% i)+1 deck[c(cardToPick,i)] <- deck[c(i, cardToPick)] } deck <- rev(deck) deal = matrix(c(deck,NA,NA,NA,NA),ncol = 8, byrow = TRUE) print(paste("Hand numer:",seedNum), quote = FALSE) print(deal, quote = FALSE, na.print = "") }
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Generate an equivalent C++ version of this R code.
library(gmp) rand_MS <- function(n = 1, seed = 1) { a <- as.bigz(214013) c <- as.bigz(2531011) m <- as.bigz(2^31) x <- rep(as.bigz(0), n) x[1] <- (a * as.bigz(seed) + c) %% m i <- 1 while (i < n) { x[i+1] <- (a * x[i] + c) %% m i <- i + 1 } as.integer(x / 2^16) } dealFreeCell <- function(seedNum) { deck <- paste(rep(c("A",2,3,4,5,6,7,8,9,10,"J","Q","K"), each = 4), c("C","D","H","S"), sep = "") cards = rand_MS(52,seedNum) for (i in 52:1) { cardToPick <- (cards[53-i]%% i)+1 deck[c(cardToPick,i)] <- deck[c(i, cardToPick)] } deck <- rev(deck) deal = matrix(c(deck,NA,NA,NA,NA),ncol = 8, byrow = TRUE) print(paste("Hand numer:",seedNum), quote = FALSE) print(deal, quote = FALSE, na.print = "") }
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Change the following R code into Java without altering its purpose.
library(gmp) rand_MS <- function(n = 1, seed = 1) { a <- as.bigz(214013) c <- as.bigz(2531011) m <- as.bigz(2^31) x <- rep(as.bigz(0), n) x[1] <- (a * as.bigz(seed) + c) %% m i <- 1 while (i < n) { x[i+1] <- (a * x[i] + c) %% m i <- i + 1 } as.integer(x / 2^16) } dealFreeCell <- function(seedNum) { deck <- paste(rep(c("A",2,3,4,5,6,7,8,9,10,"J","Q","K"), each = 4), c("C","D","H","S"), sep = "") cards = rand_MS(52,seedNum) for (i in 52:1) { cardToPick <- (cards[53-i]%% i)+1 deck[c(cardToPick,i)] <- deck[c(i, cardToPick)] } deck <- rev(deck) deal = matrix(c(deck,NA,NA,NA,NA),ncol = 8, byrow = TRUE) print(paste("Hand numer:",seedNum), quote = FALSE) print(deal, quote = FALSE, na.print = "") }
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Transform the following R implementation into Python, maintaining the same output and logic.
library(gmp) rand_MS <- function(n = 1, seed = 1) { a <- as.bigz(214013) c <- as.bigz(2531011) m <- as.bigz(2^31) x <- rep(as.bigz(0), n) x[1] <- (a * as.bigz(seed) + c) %% m i <- 1 while (i < n) { x[i+1] <- (a * x[i] + c) %% m i <- i + 1 } as.integer(x / 2^16) } dealFreeCell <- function(seedNum) { deck <- paste(rep(c("A",2,3,4,5,6,7,8,9,10,"J","Q","K"), each = 4), c("C","D","H","S"), sep = "") cards = rand_MS(52,seedNum) for (i in 52:1) { cardToPick <- (cards[53-i]%% i)+1 deck[c(cardToPick,i)] <- deck[c(i, cardToPick)] } deck <- rev(deck) deal = matrix(c(deck,NA,NA,NA,NA),ncol = 8, byrow = TRUE) print(paste("Hand numer:",seedNum), quote = FALSE) print(deal, quote = FALSE, na.print = "") }
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Transform the following R implementation into Go, maintaining the same output and logic.
library(gmp) rand_MS <- function(n = 1, seed = 1) { a <- as.bigz(214013) c <- as.bigz(2531011) m <- as.bigz(2^31) x <- rep(as.bigz(0), n) x[1] <- (a * as.bigz(seed) + c) %% m i <- 1 while (i < n) { x[i+1] <- (a * x[i] + c) %% m i <- i + 1 } as.integer(x / 2^16) } dealFreeCell <- function(seedNum) { deck <- paste(rep(c("A",2,3,4,5,6,7,8,9,10,"J","Q","K"), each = 4), c("C","D","H","S"), sep = "") cards = rand_MS(52,seedNum) for (i in 52:1) { cardToPick <- (cards[53-i]%% i)+1 deck[c(cardToPick,i)] <- deck[c(i, cardToPick)] } deck <- rev(deck) deal = matrix(c(deck,NA,NA,NA,NA),ncol = 8, byrow = TRUE) print(paste("Hand numer:",seedNum), quote = FALSE) print(deal, quote = FALSE, na.print = "") }
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Can you help me rewrite this code in C instead of Racket, keeping it the same logically?
#lang racket (module Linear_congruential_generator racket (require racket/generator) (provide ms-rand) (define (ms-update state_n) (modulo (+ (* 214013 state_n) 2531011) (expt 2 31))) (define ((rand update ->rand) seed) (generator () (let loop ([state_n seed]) (define state_n+1 (update state_n)) (yield (->rand state_n+1)) (loop state_n+1)))) (define ms-rand (rand ms-update (lambda (x) (quotient x (expt 2 16)))))) (require (submod "." Linear_congruential_generator)) (define suits "CDHS") (define (initial-deck) (for*/vector #:length 52 ((face "A23456789TJQK") (suit suits)) (cons face suit))) (define (vector-swap! v i j) (let ((t (vector-ref v i))) (vector-set! v i (vector-ref v j)) (vector-set! v j t))) (define (deal hand) (define pack (initial-deck)) (define rnd (ms-rand hand)) (define (deal-nth-card pack-sz card-no deal) (vector-swap! pack card-no (sub1 pack-sz)) (cons (vector-ref pack (sub1 pack-sz)) deal)) (let inner-deal ((pack-sz (vector-length pack)) (deal null)) (if (zero? pack-sz) (reverse deal) (inner-deal (sub1 pack-sz) (deal-nth-card pack-sz (modulo (rnd) pack-sz) deal))))) (define (present-deal hand) (printf "Game #~a~%" hand) (let inner-present-deal ((pile 0) (deck (deal hand))) (unless (null? deck) (printf "~a~a~a" (caar deck) (cdar deck) (if (or (null? (cdr deck)) (= 7 (modulo pile 8))) "\n" " ")) (inner-present-deal (add1 pile) (cdr deck))))) (present-deal 1) (newline) (present-deal 617)
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Translate the given Racket code snippet into C# without altering its behavior.
#lang racket (module Linear_congruential_generator racket (require racket/generator) (provide ms-rand) (define (ms-update state_n) (modulo (+ (* 214013 state_n) 2531011) (expt 2 31))) (define ((rand update ->rand) seed) (generator () (let loop ([state_n seed]) (define state_n+1 (update state_n)) (yield (->rand state_n+1)) (loop state_n+1)))) (define ms-rand (rand ms-update (lambda (x) (quotient x (expt 2 16)))))) (require (submod "." Linear_congruential_generator)) (define suits "CDHS") (define (initial-deck) (for*/vector #:length 52 ((face "A23456789TJQK") (suit suits)) (cons face suit))) (define (vector-swap! v i j) (let ((t (vector-ref v i))) (vector-set! v i (vector-ref v j)) (vector-set! v j t))) (define (deal hand) (define pack (initial-deck)) (define rnd (ms-rand hand)) (define (deal-nth-card pack-sz card-no deal) (vector-swap! pack card-no (sub1 pack-sz)) (cons (vector-ref pack (sub1 pack-sz)) deal)) (let inner-deal ((pack-sz (vector-length pack)) (deal null)) (if (zero? pack-sz) (reverse deal) (inner-deal (sub1 pack-sz) (deal-nth-card pack-sz (modulo (rnd) pack-sz) deal))))) (define (present-deal hand) (printf "Game #~a~%" hand) (let inner-present-deal ((pile 0) (deck (deal hand))) (unless (null? deck) (printf "~a~a~a" (caar deck) (cdar deck) (if (or (null? (cdr deck)) (= 7 (modulo pile 8))) "\n" " ")) (inner-present-deal (add1 pile) (cdr deck))))) (present-deal 1) (newline) (present-deal 617)
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Produce a functionally identical C++ code for the snippet given in Racket.
#lang racket (module Linear_congruential_generator racket (require racket/generator) (provide ms-rand) (define (ms-update state_n) (modulo (+ (* 214013 state_n) 2531011) (expt 2 31))) (define ((rand update ->rand) seed) (generator () (let loop ([state_n seed]) (define state_n+1 (update state_n)) (yield (->rand state_n+1)) (loop state_n+1)))) (define ms-rand (rand ms-update (lambda (x) (quotient x (expt 2 16)))))) (require (submod "." Linear_congruential_generator)) (define suits "CDHS") (define (initial-deck) (for*/vector #:length 52 ((face "A23456789TJQK") (suit suits)) (cons face suit))) (define (vector-swap! v i j) (let ((t (vector-ref v i))) (vector-set! v i (vector-ref v j)) (vector-set! v j t))) (define (deal hand) (define pack (initial-deck)) (define rnd (ms-rand hand)) (define (deal-nth-card pack-sz card-no deal) (vector-swap! pack card-no (sub1 pack-sz)) (cons (vector-ref pack (sub1 pack-sz)) deal)) (let inner-deal ((pack-sz (vector-length pack)) (deal null)) (if (zero? pack-sz) (reverse deal) (inner-deal (sub1 pack-sz) (deal-nth-card pack-sz (modulo (rnd) pack-sz) deal))))) (define (present-deal hand) (printf "Game #~a~%" hand) (let inner-present-deal ((pile 0) (deck (deal hand))) (unless (null? deck) (printf "~a~a~a" (caar deck) (cdar deck) (if (or (null? (cdr deck)) (= 7 (modulo pile 8))) "\n" " ")) (inner-present-deal (add1 pile) (cdr deck))))) (present-deal 1) (newline) (present-deal 617)
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Port the provided Racket code into Java while preserving the original functionality.
#lang racket (module Linear_congruential_generator racket (require racket/generator) (provide ms-rand) (define (ms-update state_n) (modulo (+ (* 214013 state_n) 2531011) (expt 2 31))) (define ((rand update ->rand) seed) (generator () (let loop ([state_n seed]) (define state_n+1 (update state_n)) (yield (->rand state_n+1)) (loop state_n+1)))) (define ms-rand (rand ms-update (lambda (x) (quotient x (expt 2 16)))))) (require (submod "." Linear_congruential_generator)) (define suits "CDHS") (define (initial-deck) (for*/vector #:length 52 ((face "A23456789TJQK") (suit suits)) (cons face suit))) (define (vector-swap! v i j) (let ((t (vector-ref v i))) (vector-set! v i (vector-ref v j)) (vector-set! v j t))) (define (deal hand) (define pack (initial-deck)) (define rnd (ms-rand hand)) (define (deal-nth-card pack-sz card-no deal) (vector-swap! pack card-no (sub1 pack-sz)) (cons (vector-ref pack (sub1 pack-sz)) deal)) (let inner-deal ((pack-sz (vector-length pack)) (deal null)) (if (zero? pack-sz) (reverse deal) (inner-deal (sub1 pack-sz) (deal-nth-card pack-sz (modulo (rnd) pack-sz) deal))))) (define (present-deal hand) (printf "Game #~a~%" hand) (let inner-present-deal ((pile 0) (deck (deal hand))) (unless (null? deck) (printf "~a~a~a" (caar deck) (cdar deck) (if (or (null? (cdr deck)) (= 7 (modulo pile 8))) "\n" " ")) (inner-present-deal (add1 pile) (cdr deck))))) (present-deal 1) (newline) (present-deal 617)
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Generate a Python translation of this Racket snippet without changing its computational steps.
#lang racket (module Linear_congruential_generator racket (require racket/generator) (provide ms-rand) (define (ms-update state_n) (modulo (+ (* 214013 state_n) 2531011) (expt 2 31))) (define ((rand update ->rand) seed) (generator () (let loop ([state_n seed]) (define state_n+1 (update state_n)) (yield (->rand state_n+1)) (loop state_n+1)))) (define ms-rand (rand ms-update (lambda (x) (quotient x (expt 2 16)))))) (require (submod "." Linear_congruential_generator)) (define suits "CDHS") (define (initial-deck) (for*/vector #:length 52 ((face "A23456789TJQK") (suit suits)) (cons face suit))) (define (vector-swap! v i j) (let ((t (vector-ref v i))) (vector-set! v i (vector-ref v j)) (vector-set! v j t))) (define (deal hand) (define pack (initial-deck)) (define rnd (ms-rand hand)) (define (deal-nth-card pack-sz card-no deal) (vector-swap! pack card-no (sub1 pack-sz)) (cons (vector-ref pack (sub1 pack-sz)) deal)) (let inner-deal ((pack-sz (vector-length pack)) (deal null)) (if (zero? pack-sz) (reverse deal) (inner-deal (sub1 pack-sz) (deal-nth-card pack-sz (modulo (rnd) pack-sz) deal))))) (define (present-deal hand) (printf "Game #~a~%" hand) (let inner-present-deal ((pile 0) (deck (deal hand))) (unless (null? deck) (printf "~a~a~a" (caar deck) (cdar deck) (if (or (null? (cdr deck)) (= 7 (modulo pile 8))) "\n" " ")) (inner-present-deal (add1 pile) (cdr deck))))) (present-deal 1) (newline) (present-deal 617)
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Maintain the same structure and functionality when rewriting this code in Go.
#lang racket (module Linear_congruential_generator racket (require racket/generator) (provide ms-rand) (define (ms-update state_n) (modulo (+ (* 214013 state_n) 2531011) (expt 2 31))) (define ((rand update ->rand) seed) (generator () (let loop ([state_n seed]) (define state_n+1 (update state_n)) (yield (->rand state_n+1)) (loop state_n+1)))) (define ms-rand (rand ms-update (lambda (x) (quotient x (expt 2 16)))))) (require (submod "." Linear_congruential_generator)) (define suits "CDHS") (define (initial-deck) (for*/vector #:length 52 ((face "A23456789TJQK") (suit suits)) (cons face suit))) (define (vector-swap! v i j) (let ((t (vector-ref v i))) (vector-set! v i (vector-ref v j)) (vector-set! v j t))) (define (deal hand) (define pack (initial-deck)) (define rnd (ms-rand hand)) (define (deal-nth-card pack-sz card-no deal) (vector-swap! pack card-no (sub1 pack-sz)) (cons (vector-ref pack (sub1 pack-sz)) deal)) (let inner-deal ((pack-sz (vector-length pack)) (deal null)) (if (zero? pack-sz) (reverse deal) (inner-deal (sub1 pack-sz) (deal-nth-card pack-sz (modulo (rnd) pack-sz) deal))))) (define (present-deal hand) (printf "Game #~a~%" hand) (let inner-present-deal ((pile 0) (deck (deal hand))) (unless (null? deck) (printf "~a~a~a" (caar deck) (cdar deck) (if (or (null? (cdr deck)) (= 7 (modulo pile 8))) "\n" " ")) (inner-present-deal (add1 pile) (cdr deck))))) (present-deal 1) (newline) (present-deal 617)
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Translate this program into C but keep the logic exactly as in REXX.
numeric digits 15 parse arg game cols . if game=='' | game=="," then game=1 if cols=='' | cols=="," then cols=8 state=game if 8=='f8'x then suit= "cdhs" else suit= "♣♦♥♠" rank= 'A23456789tJQK' pad=left('', 13) say center('tableau for FreeCell game' game, 50, "─") say #=-1; do r=1 for length(rank) do s=1 for length(suit); #=#+1 @.#=substr(rank, r,1)substr(suit, s,1) end end $=pad do cards=51 by -1 for 52 ?=rand() // (cards+1) $=$ @.?; @.?=@.cards if words($)==cols then do; say $; $=pad end end if $\='' then say $ exit rand: state=(214013*state + 2531011) // 2**31; return state % 2**16
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Produce a functionally identical C# code for the snippet given in REXX.
numeric digits 15 parse arg game cols . if game=='' | game=="," then game=1 if cols=='' | cols=="," then cols=8 state=game if 8=='f8'x then suit= "cdhs" else suit= "♣♦♥♠" rank= 'A23456789tJQK' pad=left('', 13) say center('tableau for FreeCell game' game, 50, "─") say #=-1; do r=1 for length(rank) do s=1 for length(suit); #=#+1 @.#=substr(rank, r,1)substr(suit, s,1) end end $=pad do cards=51 by -1 for 52 ?=rand() // (cards+1) $=$ @.?; @.?=@.cards if words($)==cols then do; say $; $=pad end end if $\='' then say $ exit rand: state=(214013*state + 2531011) // 2**31; return state % 2**16
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Convert this REXX snippet to C++ and keep its semantics consistent.
numeric digits 15 parse arg game cols . if game=='' | game=="," then game=1 if cols=='' | cols=="," then cols=8 state=game if 8=='f8'x then suit= "cdhs" else suit= "♣♦♥♠" rank= 'A23456789tJQK' pad=left('', 13) say center('tableau for FreeCell game' game, 50, "─") say #=-1; do r=1 for length(rank) do s=1 for length(suit); #=#+1 @.#=substr(rank, r,1)substr(suit, s,1) end end $=pad do cards=51 by -1 for 52 ?=rand() // (cards+1) $=$ @.?; @.?=@.cards if words($)==cols then do; say $; $=pad end end if $\='' then say $ exit rand: state=(214013*state + 2531011) // 2**31; return state % 2**16
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Transform the following REXX implementation into Java, maintaining the same output and logic.
numeric digits 15 parse arg game cols . if game=='' | game=="," then game=1 if cols=='' | cols=="," then cols=8 state=game if 8=='f8'x then suit= "cdhs" else suit= "♣♦♥♠" rank= 'A23456789tJQK' pad=left('', 13) say center('tableau for FreeCell game' game, 50, "─") say #=-1; do r=1 for length(rank) do s=1 for length(suit); #=#+1 @.#=substr(rank, r,1)substr(suit, s,1) end end $=pad do cards=51 by -1 for 52 ?=rand() // (cards+1) $=$ @.?; @.?=@.cards if words($)==cols then do; say $; $=pad end end if $\='' then say $ exit rand: state=(214013*state + 2531011) // 2**31; return state % 2**16
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Change the following REXX code into Python without altering its purpose.
numeric digits 15 parse arg game cols . if game=='' | game=="," then game=1 if cols=='' | cols=="," then cols=8 state=game if 8=='f8'x then suit= "cdhs" else suit= "♣♦♥♠" rank= 'A23456789tJQK' pad=left('', 13) say center('tableau for FreeCell game' game, 50, "─") say #=-1; do r=1 for length(rank) do s=1 for length(suit); #=#+1 @.#=substr(rank, r,1)substr(suit, s,1) end end $=pad do cards=51 by -1 for 52 ?=rand() // (cards+1) $=$ @.?; @.?=@.cards if words($)==cols then do; say $; $=pad end end if $\='' then say $ exit rand: state=(214013*state + 2531011) // 2**31; return state % 2**16
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Generate a Go translation of this REXX snippet without changing its computational steps.
numeric digits 15 parse arg game cols . if game=='' | game=="," then game=1 if cols=='' | cols=="," then cols=8 state=game if 8=='f8'x then suit= "cdhs" else suit= "♣♦♥♠" rank= 'A23456789tJQK' pad=left('', 13) say center('tableau for FreeCell game' game, 50, "─") say #=-1; do r=1 for length(rank) do s=1 for length(suit); #=#+1 @.#=substr(rank, r,1)substr(suit, s,1) end end $=pad do cards=51 by -1 for 52 ?=rand() // (cards+1) $=$ @.?; @.?=@.cards if words($)==cols then do; say $; $=pad end end if $\='' then say $ exit rand: state=(214013*state + 2531011) // 2**31; return state % 2**16
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Change the following Ruby code into C without altering its purpose.
begin games = ARGV.map {|s| Integer(s)} rescue => err $stderr.puts err.inspect $stderr.puts "Usage: abort end games.empty? and games = [rand(32000)] orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join) games.each do |seed| deck = orig_deck.dup state = seed 52.downto(2) do |len| state = ((214013 * state) + 2531011) & 0x7fff_ffff index = (state >> 16) % len last = len - 1 deck[index], deck[last] = deck[last], deck[index] end deck.reverse! puts "Game deck.each_slice(8) {|row| puts " " + row.join(" ")} puts end
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
begin games = ARGV.map {|s| Integer(s)} rescue => err $stderr.puts err.inspect $stderr.puts "Usage: abort end games.empty? and games = [rand(32000)] orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join) games.each do |seed| deck = orig_deck.dup state = seed 52.downto(2) do |len| state = ((214013 * state) + 2531011) & 0x7fff_ffff index = (state >> 16) % len last = len - 1 deck[index], deck[last] = deck[last], deck[index] end deck.reverse! puts "Game deck.each_slice(8) {|row| puts " " + row.join(" ")} puts end
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Ensure the translated C++ code behaves exactly like the original Ruby snippet.
begin games = ARGV.map {|s| Integer(s)} rescue => err $stderr.puts err.inspect $stderr.puts "Usage: abort end games.empty? and games = [rand(32000)] orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join) games.each do |seed| deck = orig_deck.dup state = seed 52.downto(2) do |len| state = ((214013 * state) + 2531011) & 0x7fff_ffff index = (state >> 16) % len last = len - 1 deck[index], deck[last] = deck[last], deck[index] end deck.reverse! puts "Game deck.each_slice(8) {|row| puts " " + row.join(" ")} puts end
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Preserve the algorithm and functionality while converting the code from Ruby to Java.
begin games = ARGV.map {|s| Integer(s)} rescue => err $stderr.puts err.inspect $stderr.puts "Usage: abort end games.empty? and games = [rand(32000)] orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join) games.each do |seed| deck = orig_deck.dup state = seed 52.downto(2) do |len| state = ((214013 * state) + 2531011) & 0x7fff_ffff index = (state >> 16) % len last = len - 1 deck[index], deck[last] = deck[last], deck[index] end deck.reverse! puts "Game deck.each_slice(8) {|row| puts " " + row.join(" ")} puts end
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Change the following Ruby code into Python without altering its purpose.
begin games = ARGV.map {|s| Integer(s)} rescue => err $stderr.puts err.inspect $stderr.puts "Usage: abort end games.empty? and games = [rand(32000)] orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join) games.each do |seed| deck = orig_deck.dup state = seed 52.downto(2) do |len| state = ((214013 * state) + 2531011) & 0x7fff_ffff index = (state >> 16) % len last = len - 1 deck[index], deck[last] = deck[last], deck[index] end deck.reverse! puts "Game deck.each_slice(8) {|row| puts " " + row.join(" ")} puts end
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Convert the following code from Ruby to Go, ensuring the logic remains intact.
begin games = ARGV.map {|s| Integer(s)} rescue => err $stderr.puts err.inspect $stderr.puts "Usage: abort end games.empty? and games = [rand(32000)] orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join) games.each do |seed| deck = orig_deck.dup state = seed 52.downto(2) do |len| state = ((214013 * state) + 2531011) & 0x7fff_ffff index = (state >> 16) % len last = len - 1 deck[index], deck[last] = deck[last], deck[index] end deck.reverse! puts "Game deck.each_slice(8) {|row| puts " " + row.join(" ")} puts end
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Translate the given Scala code snippet into C without altering its behavior.
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) { private var state = s fun nextInt(): Long { state = (a * state + c) % m return state / d } } const val CARDS = "A23456789TJQK" const val SUITS = "♣♦♥♠" fun deal(): Array<String?> { val cards = arrayOfNulls<String>(52) for (i in 0 until 52) { val card = CARDS[i / 4] val suit = SUITS[i % 4] cards[i] = "$card$suit" } return cards } fun game(n: Int) { require(n > 0) println("Game #$n:") val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, n.toLong()) val cards = deal() for (m in 52 downTo 1) { val index = (msc.nextInt() % m).toInt() val temp = cards[index] cards[index] = cards[m - 1] print("$temp ") if ((53 - m) % 8 == 0) println() } println("\n") } fun main(args: Array<String>) { game(1) game(617) }
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Generate an equivalent C# version of this Scala code.
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) { private var state = s fun nextInt(): Long { state = (a * state + c) % m return state / d } } const val CARDS = "A23456789TJQK" const val SUITS = "♣♦♥♠" fun deal(): Array<String?> { val cards = arrayOfNulls<String>(52) for (i in 0 until 52) { val card = CARDS[i / 4] val suit = SUITS[i % 4] cards[i] = "$card$suit" } return cards } fun game(n: Int) { require(n > 0) println("Game #$n:") val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, n.toLong()) val cards = deal() for (m in 52 downTo 1) { val index = (msc.nextInt() % m).toInt() val temp = cards[index] cards[index] = cards[m - 1] print("$temp ") if ((53 - m) % 8 == 0) println() } println("\n") } fun main(args: Array<String>) { game(1) game(617) }
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Preserve the algorithm and functionality while converting the code from Scala to C++.
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) { private var state = s fun nextInt(): Long { state = (a * state + c) % m return state / d } } const val CARDS = "A23456789TJQK" const val SUITS = "♣♦♥♠" fun deal(): Array<String?> { val cards = arrayOfNulls<String>(52) for (i in 0 until 52) { val card = CARDS[i / 4] val suit = SUITS[i % 4] cards[i] = "$card$suit" } return cards } fun game(n: Int) { require(n > 0) println("Game #$n:") val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, n.toLong()) val cards = deal() for (m in 52 downTo 1) { val index = (msc.nextInt() % m).toInt() val temp = cards[index] cards[index] = cards[m - 1] print("$temp ") if ((53 - m) % 8 == 0) println() } println("\n") } fun main(args: Array<String>) { game(1) game(617) }
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Transform the following Scala implementation into Java, maintaining the same output and logic.
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) { private var state = s fun nextInt(): Long { state = (a * state + c) % m return state / d } } const val CARDS = "A23456789TJQK" const val SUITS = "♣♦♥♠" fun deal(): Array<String?> { val cards = arrayOfNulls<String>(52) for (i in 0 until 52) { val card = CARDS[i / 4] val suit = SUITS[i % 4] cards[i] = "$card$suit" } return cards } fun game(n: Int) { require(n > 0) println("Game #$n:") val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, n.toLong()) val cards = deal() for (m in 52 downTo 1) { val index = (msc.nextInt() % m).toInt() val temp = cards[index] cards[index] = cards[m - 1] print("$temp ") if ((53 - m) % 8 == 0) println() } println("\n") } fun main(args: Array<String>) { game(1) game(617) }
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Translate the given Scala code snippet into Python without altering its behavior.
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) { private var state = s fun nextInt(): Long { state = (a * state + c) % m return state / d } } const val CARDS = "A23456789TJQK" const val SUITS = "♣♦♥♠" fun deal(): Array<String?> { val cards = arrayOfNulls<String>(52) for (i in 0 until 52) { val card = CARDS[i / 4] val suit = SUITS[i % 4] cards[i] = "$card$suit" } return cards } fun game(n: Int) { require(n > 0) println("Game #$n:") val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, n.toLong()) val cards = deal() for (m in 52 downTo 1) { val index = (msc.nextInt() % m).toInt() val temp = cards[index] cards[index] = cards[m - 1] print("$temp ") if ((53 - m) % 8 == 0) println() } println("\n") } fun main(args: Array<String>) { game(1) game(617) }
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Write the same code in Go as shown below in Scala.
class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) { private var state = s fun nextInt(): Long { state = (a * state + c) % m return state / d } } const val CARDS = "A23456789TJQK" const val SUITS = "♣♦♥♠" fun deal(): Array<String?> { val cards = arrayOfNulls<String>(52) for (i in 0 until 52) { val card = CARDS[i / 4] val suit = SUITS[i % 4] cards[i] = "$card$suit" } return cards } fun game(n: Int) { require(n > 0) println("Game #$n:") val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, n.toLong()) val cards = deal() for (m in 52 downTo 1) { val index = (msc.nextInt() % m).toInt() val temp = cards[index] cards[index] = cards[m - 1] print("$temp ") if ((53 - m) % 8 == 0) println() } println("\n") } fun main(args: Array<String>) { game(1) game(617) }
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Please provide an equivalent version of this Swift code in C.
enum Suit : String, CustomStringConvertible, CaseIterable { case clubs = "C", diamonds = "D", hearts = "H", spades = "S" var description: String { return self.rawValue } } enum Rank : Int, CustomStringConvertible, CaseIterable { case ace=1, two, three, four, five, six, seven case eight, nine, ten, jack, queen, king var description: String { let d : [Rank:String] = [.ace:"A", .king:"K", .queen:"Q", .jack:"J", .ten:"T"] return d[self] ?? String(self.rawValue) } } struct Card : CustomStringConvertible { let rank : Rank, suit : Suit var description : String { return String(describing:self.rank) + String(describing:self.suit) } init(rank:Rank, suit:Suit) { self.rank = rank; self.suit = suit } init(sequence n:Int) { self.init(rank:Rank.allCases[n/4], suit:Suit.allCases[n%4]) } } struct Deck : CustomStringConvertible { var cards = [Card]() init(seed:Int) { for i in (0..<52).reversed() { self.cards.append(Card(sequence:i)) } struct MicrosoftLinearCongruentialGenerator { var seed : Int mutating func next() -> Int { self.seed = (self.seed * 214013 + 2531011) % (Int(Int32.max)+1) return self.seed >> 16 } } var r = MicrosoftLinearCongruentialGenerator(seed: seed) for i in 0..<51 { self.cards.swapAt(i, 51-r.next()%(52-i)) } } var description : String { var s = "" for (ix,c) in self.cards.enumerated() { s.write(String(describing:c)) s.write(ix % 8 == 7 ? "\n" : " ") } return s } } let d1 = Deck(seed: 1) print(d1) let d617 = Deck(seed: 617) print(d617)
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Produce a functionally identical C# code for the snippet given in Swift.
enum Suit : String, CustomStringConvertible, CaseIterable { case clubs = "C", diamonds = "D", hearts = "H", spades = "S" var description: String { return self.rawValue } } enum Rank : Int, CustomStringConvertible, CaseIterable { case ace=1, two, three, four, five, six, seven case eight, nine, ten, jack, queen, king var description: String { let d : [Rank:String] = [.ace:"A", .king:"K", .queen:"Q", .jack:"J", .ten:"T"] return d[self] ?? String(self.rawValue) } } struct Card : CustomStringConvertible { let rank : Rank, suit : Suit var description : String { return String(describing:self.rank) + String(describing:self.suit) } init(rank:Rank, suit:Suit) { self.rank = rank; self.suit = suit } init(sequence n:Int) { self.init(rank:Rank.allCases[n/4], suit:Suit.allCases[n%4]) } } struct Deck : CustomStringConvertible { var cards = [Card]() init(seed:Int) { for i in (0..<52).reversed() { self.cards.append(Card(sequence:i)) } struct MicrosoftLinearCongruentialGenerator { var seed : Int mutating func next() -> Int { self.seed = (self.seed * 214013 + 2531011) % (Int(Int32.max)+1) return self.seed >> 16 } } var r = MicrosoftLinearCongruentialGenerator(seed: seed) for i in 0..<51 { self.cards.swapAt(i, 51-r.next()%(52-i)) } } var description : String { var s = "" for (ix,c) in self.cards.enumerated() { s.write(String(describing:c)) s.write(ix % 8 == 7 ? "\n" : " ") } return s } } let d1 = Deck(seed: 1) print(d1) let d617 = Deck(seed: 617) print(d617)
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Preserve the algorithm and functionality while converting the code from Swift to C++.
enum Suit : String, CustomStringConvertible, CaseIterable { case clubs = "C", diamonds = "D", hearts = "H", spades = "S" var description: String { return self.rawValue } } enum Rank : Int, CustomStringConvertible, CaseIterable { case ace=1, two, three, four, five, six, seven case eight, nine, ten, jack, queen, king var description: String { let d : [Rank:String] = [.ace:"A", .king:"K", .queen:"Q", .jack:"J", .ten:"T"] return d[self] ?? String(self.rawValue) } } struct Card : CustomStringConvertible { let rank : Rank, suit : Suit var description : String { return String(describing:self.rank) + String(describing:self.suit) } init(rank:Rank, suit:Suit) { self.rank = rank; self.suit = suit } init(sequence n:Int) { self.init(rank:Rank.allCases[n/4], suit:Suit.allCases[n%4]) } } struct Deck : CustomStringConvertible { var cards = [Card]() init(seed:Int) { for i in (0..<52).reversed() { self.cards.append(Card(sequence:i)) } struct MicrosoftLinearCongruentialGenerator { var seed : Int mutating func next() -> Int { self.seed = (self.seed * 214013 + 2531011) % (Int(Int32.max)+1) return self.seed >> 16 } } var r = MicrosoftLinearCongruentialGenerator(seed: seed) for i in 0..<51 { self.cards.swapAt(i, 51-r.next()%(52-i)) } } var description : String { var s = "" for (ix,c) in self.cards.enumerated() { s.write(String(describing:c)) s.write(ix % 8 == 7 ? "\n" : " ") } return s } } let d1 = Deck(seed: 1) print(d1) let d617 = Deck(seed: 617) print(d617)
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Can you help me rewrite this code in Java instead of Swift, keeping it the same logically?
enum Suit : String, CustomStringConvertible, CaseIterable { case clubs = "C", diamonds = "D", hearts = "H", spades = "S" var description: String { return self.rawValue } } enum Rank : Int, CustomStringConvertible, CaseIterable { case ace=1, two, three, four, five, six, seven case eight, nine, ten, jack, queen, king var description: String { let d : [Rank:String] = [.ace:"A", .king:"K", .queen:"Q", .jack:"J", .ten:"T"] return d[self] ?? String(self.rawValue) } } struct Card : CustomStringConvertible { let rank : Rank, suit : Suit var description : String { return String(describing:self.rank) + String(describing:self.suit) } init(rank:Rank, suit:Suit) { self.rank = rank; self.suit = suit } init(sequence n:Int) { self.init(rank:Rank.allCases[n/4], suit:Suit.allCases[n%4]) } } struct Deck : CustomStringConvertible { var cards = [Card]() init(seed:Int) { for i in (0..<52).reversed() { self.cards.append(Card(sequence:i)) } struct MicrosoftLinearCongruentialGenerator { var seed : Int mutating func next() -> Int { self.seed = (self.seed * 214013 + 2531011) % (Int(Int32.max)+1) return self.seed >> 16 } } var r = MicrosoftLinearCongruentialGenerator(seed: seed) for i in 0..<51 { self.cards.swapAt(i, 51-r.next()%(52-i)) } } var description : String { var s = "" for (ix,c) in self.cards.enumerated() { s.write(String(describing:c)) s.write(ix % 8 == 7 ? "\n" : " ") } return s } } let d1 = Deck(seed: 1) print(d1) let d617 = Deck(seed: 617) print(d617)
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Convert this Swift block to Python, preserving its control flow and logic.
enum Suit : String, CustomStringConvertible, CaseIterable { case clubs = "C", diamonds = "D", hearts = "H", spades = "S" var description: String { return self.rawValue } } enum Rank : Int, CustomStringConvertible, CaseIterable { case ace=1, two, three, four, five, six, seven case eight, nine, ten, jack, queen, king var description: String { let d : [Rank:String] = [.ace:"A", .king:"K", .queen:"Q", .jack:"J", .ten:"T"] return d[self] ?? String(self.rawValue) } } struct Card : CustomStringConvertible { let rank : Rank, suit : Suit var description : String { return String(describing:self.rank) + String(describing:self.suit) } init(rank:Rank, suit:Suit) { self.rank = rank; self.suit = suit } init(sequence n:Int) { self.init(rank:Rank.allCases[n/4], suit:Suit.allCases[n%4]) } } struct Deck : CustomStringConvertible { var cards = [Card]() init(seed:Int) { for i in (0..<52).reversed() { self.cards.append(Card(sequence:i)) } struct MicrosoftLinearCongruentialGenerator { var seed : Int mutating func next() -> Int { self.seed = (self.seed * 214013 + 2531011) % (Int(Int32.max)+1) return self.seed >> 16 } } var r = MicrosoftLinearCongruentialGenerator(seed: seed) for i in 0..<51 { self.cards.swapAt(i, 51-r.next()%(52-i)) } } var description : String { var s = "" for (ix,c) in self.cards.enumerated() { s.write(String(describing:c)) s.write(ix % 8 == 7 ? "\n" : " ") } return s } } let d1 = Deck(seed: 1) print(d1) let d617 = Deck(seed: 617) print(d617)
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Convert this Swift block to Go, preserving its control flow and logic.
enum Suit : String, CustomStringConvertible, CaseIterable { case clubs = "C", diamonds = "D", hearts = "H", spades = "S" var description: String { return self.rawValue } } enum Rank : Int, CustomStringConvertible, CaseIterable { case ace=1, two, three, four, five, six, seven case eight, nine, ten, jack, queen, king var description: String { let d : [Rank:String] = [.ace:"A", .king:"K", .queen:"Q", .jack:"J", .ten:"T"] return d[self] ?? String(self.rawValue) } } struct Card : CustomStringConvertible { let rank : Rank, suit : Suit var description : String { return String(describing:self.rank) + String(describing:self.suit) } init(rank:Rank, suit:Suit) { self.rank = rank; self.suit = suit } init(sequence n:Int) { self.init(rank:Rank.allCases[n/4], suit:Suit.allCases[n%4]) } } struct Deck : CustomStringConvertible { var cards = [Card]() init(seed:Int) { for i in (0..<52).reversed() { self.cards.append(Card(sequence:i)) } struct MicrosoftLinearCongruentialGenerator { var seed : Int mutating func next() -> Int { self.seed = (self.seed * 214013 + 2531011) % (Int(Int32.max)+1) return self.seed >> 16 } } var r = MicrosoftLinearCongruentialGenerator(seed: seed) for i in 0..<51 { self.cards.swapAt(i, 51-r.next()%(52-i)) } } var description : String { var s = "" for (ix,c) in self.cards.enumerated() { s.write(String(describing:c)) s.write(ix % 8 == 7 ? "\n" : " ") } return s } } let d1 = Deck(seed: 1) print(d1) let d617 = Deck(seed: 617) print(d617)
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Produce a functionally identical C code for the snippet given in Tcl.
proc rnd {{*r seed}} { upvar 1 ${*r} r expr {[set r [expr {($r * 214013 + 2531011) & 0x7fffffff}]] >> 16} } proc show cards { set suits {\u2663 \u2666 \u2665 \u2660} set values {A 2 3 4 5 6 7 8 9 T J Q K} for {set i 0} {$i < 52} {incr i} { set c [lindex $cards $i] puts -nonewline [format " \033\[%dm%s\033\[m%s" [expr {32-(1+$c)%4/2}] \ [lindex $suits [expr {$c % 4}]] [lindex $values [expr {$c / 4}]]] if {($i&7)==7 || $i==51} {puts ""} } } proc deal {seed} { for {set i 0} {$i < 52} {incr i} {lappend cards [expr {51 - $i}]} for {set i 0} {$i < 51} {incr i} { set j [expr {51 - [rnd]%(52-$i)}] set tmp [lindex $cards $i] lset cards $i [lindex $cards $j] lset cards $j $tmp } return $cards } if {![scan =[lindex $argv 0]= =%d= s] || $s <= 0} { set s 11982 } set cards [deal $s] puts "Hand $s" show $cards
#include <stdio.h> #include <stdlib.h> #include <locale.h> wchar_t s_suits[] = L"♣♦♥♠", s_nums[] = L"A23456789TJQK"; #define RMAX32 ((1U << 31) - 1) static int seed = 1; int rnd(void) { return (seed = (seed * 214013 + 2531011) & RMAX32) >> 16; } void srnd(int x) { seed = x; } void show(const int *c) { int i; for (i = 0; i < 52; c++) { printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, s_suits[*c % 4], s_nums[*c / 4]); if (!(++i % 8) || i == 52) putchar('\n'); } } void deal(int s, int *t) { int i, j; srnd(s); for (i = 0; i < 52; i++) t[i] = 51 - i; for (i = 0; i < 51; i++) { j = 51 - rnd() % (52 - i); s = t[i], t[i] = t[j], t[j] = s; } } int main(int c, char **v) { int s, card[52]; if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; setlocale(LC_ALL, ""); deal(s, card); printf("Hand %d\n", s); show(card); return 0; }
Generate an equivalent C# version of this Tcl code.
proc rnd {{*r seed}} { upvar 1 ${*r} r expr {[set r [expr {($r * 214013 + 2531011) & 0x7fffffff}]] >> 16} } proc show cards { set suits {\u2663 \u2666 \u2665 \u2660} set values {A 2 3 4 5 6 7 8 9 T J Q K} for {set i 0} {$i < 52} {incr i} { set c [lindex $cards $i] puts -nonewline [format " \033\[%dm%s\033\[m%s" [expr {32-(1+$c)%4/2}] \ [lindex $suits [expr {$c % 4}]] [lindex $values [expr {$c / 4}]]] if {($i&7)==7 || $i==51} {puts ""} } } proc deal {seed} { for {set i 0} {$i < 52} {incr i} {lappend cards [expr {51 - $i}]} for {set i 0} {$i < 51} {incr i} { set j [expr {51 - [rnd]%(52-$i)}] set tmp [lindex $cards $i] lset cards $i [lindex $cards $j] lset cards $j $tmp } return $cards } if {![scan =[lindex $argv 0]= =%d= s] || $s <= 0} { set s 11982 } set cards [deal $s] puts "Hand $s" show $cards
using System; using System.Collections.Generic; using System.Text; namespace FreeCellDeals { public class RNG { private int _state; public RNG() { _state = (int)DateTime.Now.Ticks; } public RNG(int n) { _state = n; } public int Next() { return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16; } } public enum Rank { Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } public enum Suit { Clubs, Diamonds, Hearts, Spades } public class Card { private const string Ranks = "A23456789TJQK"; private const string Suits = "CDHS"; private Rank _rank; public Rank Rank { get { return _rank; } set { if ((int)value < 0 || (int)value > 12) { throw new InvalidOperationException("Setting card rank out of range"); } _rank = value; } } private Suit _suit; public Suit Suit { get { return _suit; } set { if ((int)value < 0 || (int)value > 3) { throw new InvalidOperationException("Setting card rank out of range"); } _suit = value; } } public Card(Rank rank, Suit suit) { Rank = rank; Suit = suit; } public int NRank() { return (int) Rank; } public int NSuit() { return (int) Suit; } public override string ToString() { return new string(new[] {Ranks[NRank()], Suits[NSuit()]}); } } public class FreeCellDeal { public List<Card> Deck { get; private set; } public FreeCellDeal(int iDeal) { RNG rng = new RNG(iDeal); List<Card> rDeck = new List<Card>(); Deck = new List<Card>(); for (int rank = 0; rank < 13; rank++) { for (int suit = 0; suit < 4; suit++) { rDeck.Add(new Card((Rank)rank, (Suit)suit)); } } for (int iCard = 51; iCard >= 0; iCard--) { int iSwap = rng.Next() % (iCard + 1); Deck.Add(rDeck[iSwap]); rDeck[iSwap] = rDeck[iCard]; } } public override string ToString() { StringBuilder sb = new StringBuilder(); for (int iRow = 0; iRow < 6; iRow++ ) { for (int iCol = 0; iCol < 8; iCol++) { sb.AppendFormat("{0} ", Deck[iRow * 8 + iCol]); } sb.Append("\n"); } for (int iCard = 48; iCard < 52; iCard++) { sb.AppendFormat("{0} ", Deck[iCard]); } return sb.ToString(); } } class Program { static void Main() { Console.WriteLine(new FreeCellDeal(1)); Console.WriteLine(); Console.WriteLine(new FreeCellDeal(617)); } } }
Ensure the translated C++ code behaves exactly like the original Tcl snippet.
proc rnd {{*r seed}} { upvar 1 ${*r} r expr {[set r [expr {($r * 214013 + 2531011) & 0x7fffffff}]] >> 16} } proc show cards { set suits {\u2663 \u2666 \u2665 \u2660} set values {A 2 3 4 5 6 7 8 9 T J Q K} for {set i 0} {$i < 52} {incr i} { set c [lindex $cards $i] puts -nonewline [format " \033\[%dm%s\033\[m%s" [expr {32-(1+$c)%4/2}] \ [lindex $suits [expr {$c % 4}]] [lindex $values [expr {$c / 4}]]] if {($i&7)==7 || $i==51} {puts ""} } } proc deal {seed} { for {set i 0} {$i < 52} {incr i} {lappend cards [expr {51 - $i}]} for {set i 0} {$i < 51} {incr i} { set j [expr {51 - [rnd]%(52-$i)}] set tmp [lindex $cards $i] lset cards $i [lindex $cards $j] lset cards $j $tmp } return $cards } if {![scan =[lindex $argv 0]= =%d= s] || $s <= 0} { set s 11982 } set cards [deal $s] puts "Hand $s" show $cards
#include <windows.h> #include <iostream> using namespace std; class fc_dealer { public: void deal( int game ) { _gn = game; fillDeck(); shuffle(); display(); } private: void fillDeck() { int p = 0; for( int c = 0; c < 13; c++ ) for( int s = 0; s < 4; s++ ) _cards[p++] = c | s << 4; } void shuffle() { srand( _gn ); int cc = 52, nc, lc; while( cc ) { nc = rand() % cc; lc = _cards[--cc]; _cards[cc] = _cards[nc]; _cards[nc] = lc; } } void display() { char* suit = "CDHS"; char* symb = "A23456789TJQK"; int z = 0; cout << "GAME #" << _gn << endl << "=======================" << endl; for( int c = 51; c >= 0; c-- ) { cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; if( ++z >= 8 ) { cout << endl; z = 0; } } } int _cards[52], _gn; }; int main( int argc, char* argv[] ) { fc_dealer dealer; int gn; while( true ) { cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; if( !gn ) break; system( "cls" ); dealer.deal( gn ); cout << endl << endl; } return 0; }
Rewrite the snippet below in Java so it works the same as the original Tcl code.
proc rnd {{*r seed}} { upvar 1 ${*r} r expr {[set r [expr {($r * 214013 + 2531011) & 0x7fffffff}]] >> 16} } proc show cards { set suits {\u2663 \u2666 \u2665 \u2660} set values {A 2 3 4 5 6 7 8 9 T J Q K} for {set i 0} {$i < 52} {incr i} { set c [lindex $cards $i] puts -nonewline [format " \033\[%dm%s\033\[m%s" [expr {32-(1+$c)%4/2}] \ [lindex $suits [expr {$c % 4}]] [lindex $values [expr {$c / 4}]]] if {($i&7)==7 || $i==51} {puts ""} } } proc deal {seed} { for {set i 0} {$i < 52} {incr i} {lappend cards [expr {51 - $i}]} for {set i 0} {$i < 51} {incr i} { set j [expr {51 - [rnd]%(52-$i)}] set tmp [lindex $cards $i] lset cards $i [lindex $cards $j] lset cards $j $tmp } return $cards } if {![scan =[lindex $argv 0]= =%d= s] || $s <= 0} { set s 11982 } set cards [deal $s] puts "Hand $s" show $cards
import java.util.Arrays; public class Shuffler { private int seed; private String[] deck = { "AC", "AD", "AH", "AS", "2C", "2D", "2H", "2S", "3C", "3D", "3H", "3S", "4C", "4D", "4H", "4S", "5C", "5D", "5H", "5S", "6C", "6D", "6H", "6S", "7C", "7D", "7H", "7S", "8C", "8D", "8H", "8S", "9C", "9D", "9H", "9S", "TC", "TD", "TH", "TS", "JC", "JD", "JH", "JS", "QC", "QD", "QH", "QS", "KC", "KD", "KH", "KS", }; private int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; return seed >> 16; } private String[] getShuffledDeck() { String[] deck = Arrays.copyOf(this.deck, this.deck.length); for(int i = deck.length - 1; i > 0; i--) { int r = random() % (i + 1); String card = deck[r]; deck[r] = deck[i]; deck[i] = card; } return deck; } public void dealGame(int seed) { this.seed = seed; String[] shuffledDeck = getShuffledDeck(); for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { System.out.print(shuffledDeck[i]); if(count % 8 == 0) { System.out.println(); } else { System.out.print(" "); } } System.out.println(); } public static void main(String[] args) { Shuffler s = new Shuffler(); s.dealGame(1); System.out.println(); s.dealGame(617); } }
Change the following Tcl code into Python without altering its purpose.
proc rnd {{*r seed}} { upvar 1 ${*r} r expr {[set r [expr {($r * 214013 + 2531011) & 0x7fffffff}]] >> 16} } proc show cards { set suits {\u2663 \u2666 \u2665 \u2660} set values {A 2 3 4 5 6 7 8 9 T J Q K} for {set i 0} {$i < 52} {incr i} { set c [lindex $cards $i] puts -nonewline [format " \033\[%dm%s\033\[m%s" [expr {32-(1+$c)%4/2}] \ [lindex $suits [expr {$c % 4}]] [lindex $values [expr {$c / 4}]]] if {($i&7)==7 || $i==51} {puts ""} } } proc deal {seed} { for {set i 0} {$i < 52} {incr i} {lappend cards [expr {51 - $i}]} for {set i 0} {$i < 51} {incr i} { set j [expr {51 - [rnd]%(52-$i)}] set tmp [lindex $cards $i] lset cards $i [lindex $cards $j] lset cards $j $tmp } return $cards } if {![scan =[lindex $argv 0]= =%d= s] || $s <= 0} { set s 11982 } set cards [deal $s] puts "Hand $s" show $cards
def randomGenerator(seed=1): max_int32 = (1 << 31) - 1 seed = seed & max_int32 while True: seed = (seed * 214013 + 2531011) & max_int32 yield seed >> 16 def deal(seed): nc = 52 cards = list(range(nc - 1, -1, -1)) rnd = randomGenerator(seed) for i, r in zip(range(nc), rnd): j = (nc - 1) - r % (nc - i) cards[i], cards[j] = cards[j], cards[i] return cards def show(cards): l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards] for i in range(0, len(cards), 8): print(" ".join(l[i : i+8])) if __name__ == '__main__': from sys import argv seed = int(argv[1]) if len(argv) == 2 else 11982 print("Hand {}".format(seed)) deck = deal(seed) show(deck)
Keep all operations the same but rewrite the snippet in Go.
proc rnd {{*r seed}} { upvar 1 ${*r} r expr {[set r [expr {($r * 214013 + 2531011) & 0x7fffffff}]] >> 16} } proc show cards { set suits {\u2663 \u2666 \u2665 \u2660} set values {A 2 3 4 5 6 7 8 9 T J Q K} for {set i 0} {$i < 52} {incr i} { set c [lindex $cards $i] puts -nonewline [format " \033\[%dm%s\033\[m%s" [expr {32-(1+$c)%4/2}] \ [lindex $suits [expr {$c % 4}]] [lindex $values [expr {$c / 4}]]] if {($i&7)==7 || $i==51} {puts ""} } } proc deal {seed} { for {set i 0} {$i < 52} {incr i} {lappend cards [expr {51 - $i}]} for {set i 0} {$i < 51} {incr i} { set j [expr {51 - [rnd]%(52-$i)}] set tmp [lindex $cards $i] lset cards $i [lindex $cards $j] lset cards $j $tmp } return $cards } if {![scan =[lindex $argv 0]= =%d= s] || $s <= 0} { set s 11982 } set cards [deal $s] puts "Hand $s" show $cards
package main import ( "fmt" "math" "math/rand" "os" "strconv" "time" ) const sSuits = "CDHS" const sNums = "A23456789TJQK" const rMax32 = math.MaxInt32 var seed = 1 func rnd() int { seed = (seed*214013 + 2531011) & rMax32 return seed >> 16 } func deal(s int) []int { seed = s t := make([]int, 52) for i := 0; i < 52; i++ { t[i] = 51 - i } for i := 0; i < 51; i++ { j := 51 - rnd()%(52-i) t[i], t[j] = t[j], t[i] } return t } func show(cs []int) { for i, c := range cs { fmt.Printf(" %c%c", sNums[c/4], sSuits[c%4]) if (i+1)%8 == 0 || i+1 == len(cs) { fmt.Println() } } } func main() { var game int switch len(os.Args) { case 1: rand.Seed(time.Now().UnixNano()) game = 1 + rand.Intn(32000) case 2: var err error game, err = strconv.Atoi(os.Args[1]) if err == nil && game >= 1 && game <= 32000 { break } fallthrough default: fmt.Println("usage: deal [game]") fmt.Println(" where game is a number in the range 1 to 32000") return } fmt.Printf("\nGame #%d\n", game) show(deal(game)) }
Keep all operations the same but rewrite the snippet in PHP.
extern crate linear_congruential_generator; use linear_congruential_generator::{MsLcg, Rng, SeedableRng}; fn shuffle<T>(rng: &mut MsLcg, deck: &mut [T]) { let len = deck.len() as u32; for i in (1..len).rev() { let j = rng.next_u32() % (i + 1); deck.swap(i as usize, j as usize); } } fn gen_deck() -> Vec<String> { const RANKS: [char; 13] = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']; const SUITS: [char; 4] = ['C', 'D', 'H', 'S']; let render_card = |card: usize| { let (suit, rank) = (card % 4, card / 4); format!("{}{}", RANKS[rank], SUITS[suit]) }; (0..52).map(render_card).collect() } fn deal_ms_fc_board(seed: u32) -> Vec<String> { let mut rng = MsLcg::from_seed(seed); let mut deck = gen_deck(); shuffle(&mut rng, &mut deck); deck.reverse(); deck.chunks(8).map(|row| row.join(" ")).collect::<Vec<_>>() } fn main() { let seed = std::env::args() .nth(1) .and_then(|n| n.parse().ok()) .expect("A 32-bit seed is required"); for row in deal_ms_fc_board(seed) { println!(": {}", row); } }
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Write a version of this Ada function in PHP with identical behavior.
with Ada.Text_IO; use Ada.Text_IO; procedure FreeCell is type State is mod 2**31; type Deck is array (0..51) of String(1..2); package Random is procedure Init(Seed: State); function Rand return State; end Random; package body Random is S : State := State'First; procedure Init(Seed: State) is begin S := Seed; end Init; function Rand return State is begin S := S * 214013 + 2531011; return S / 2**16; end Rand; end Random; procedure Deal (num : State) is thedeck : Deck; pick : State; Chars : constant String := "A23456789TJQKCDHS"; begin for i in thedeck'Range loop thedeck(i):= Chars(i/4+1) & Chars(i mod 4 + 14); end loop; Random.Init(num); for i in 0..51 loop pick := Random.Rand mod State(52-i); Put(thedeck(Natural(pick))&' '); if (i+1) mod 8 = 0 then New_Line; end if; thedeck(Natural(pick)) := thedeck(51-i); end loop; New_Line; end Deal; begin Deal(1); New_Line; Deal(617); end FreeCell;
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Translate the given AutoHotKey code snippet into PHP without altering its behavior.
FreeCell(num){ cards := "A23456789TJQK", suits := "♣♦♥♠", card := [], Counter := 0 loop, parse, cards { ThisCard := A_LoopField loop, parse, suits Card[Counter++] := ThisCard . A_LoopField } loop, 52 { a := MS(num) num:=a[1] MyCardNo := mod(a[2],53-A_Index) MyCard := Card[MyCardNo] Card[MyCardNo] := Card[52-A_Index] Card.Remove(52-A_Index) Res .= MyCard (Mod(A_Index,8)?" ":"`n") } return Res } MS(Seed) { Seed := Mod(214013 * Seed + 2531011, 2147483648) return, [Seed, Seed // 65536] }
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Translate this program into PHP but keep the logic exactly as in BBC_Basic.
*FLOAT 64 hand% = 617 SYS "LoadLibrary", "CARDS.DLL" TO cards% IF cards% = 0 ERROR 100, "No CARDS library" SYS "GetProcAddress", cards%, "cdtInit" TO cdtInit% SYS "GetProcAddress", cards%, "cdtDraw" TO cdtDraw% SYS cdtInit%, ^dx%, ^dy% VDU 23,22,8*dx%;5*dy%;8,16,16,128 DIM card&(51) FOR I% = 0 TO 51 : card&(I%) = I% : NEXT dummy% = FNrng(hand%) FOR I% = 51 TO 0 STEP -1 C% = FNrng(-1) MOD (I% + 1) SWAP card&(C%), card&(I%) NEXT FOR I% = 0 TO 51 C% = card&(51 - I%) X% = (I% MOD 8) * dx% Y% = (I% DIV 8) * dy% * 2 / 3 SYS cdtDraw%, @memhdc%, X%, Y%, C%, 0, 0 NEXT SYS "InvalidateRect", @hwnd%, 0, 0 *GSAVE freecell END DEF FNrng(seed) PRIVATE state, M% IF seed >= 0 THEN state = seed ELSE state = (state * 214013 + 2531011) FOR M% = 52 TO 31 STEP -1 IF state >= 2^M% state -= 2^M% NEXT ENDIF = state >> 16
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Produce a functionally identical PHP code for the snippet given in Clojure.
(def deck (into [] (for [rank "A23456789TJQK" suit "CDHS"] (str rank suit)))) (defn lcg [seed] (map #(bit-shift-right % 16) (rest (iterate #(mod (+ (* % 214013) 2531011) (bit-shift-left 1 31)) seed)))) (defn gen [seed] (map (fn [rnd rng] (into [] [(mod rnd rng) (dec rng)])) (lcg seed) (range 52 0 -1))) (defn xchg [v [src dst]] (assoc v dst (v src) src (v dst))) (defn show [seed] (map #(println %) (partition 8 8 "" (reverse (reduce xchg deck (gen seed)))))) (show 1)
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Rewrite this program in PHP while keeping its functionality equivalent to the Common_Lisp version.
(defun make-rng (seed) #'(lambda () (ash (setf seed (mod (+ (* 214013 seed) 2531011) (expt 2 31))) -16))) (defun split (s) (map 'list #'string s)) (defun make-deck (seed) (let ((hand (make-array 52 :fill-pointer 0)) (rng (make-rng seed))) (dolist (d (split "A23456789TJQK")) (dolist (s (split "♣♦♥♠")) (vector-push (concatenate 'string d s) hand))) (dotimes (i 52) (rotatef (aref hand (- 51 i)) (aref hand (mod (funcall rng) (- 52 i))))) (nreverse hand))) (defun show-deck (seed) (let ((hand (make-deck seed))) (format t "~%Hand ~d~%" seed) (dotimes (i 52) (format t "~A " (aref hand i)) (if (= (mod i 8) 7) (write-line ""))))) (show-deck 1) (show-deck 617)
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Can you help me rewrite this code in PHP instead of D, keeping it the same logically?
import std.stdio, std.conv, std.algorithm, std.range; struct RandomGenerator { uint seed = 1; @property uint next() pure nothrow @safe @nogc { seed = (seed * 214_013 + 2_531_011) & int.max; return seed >> 16; } } struct Deck { int[52] cards; void deal(in uint seed) pure nothrow @safe @nogc { enum int nc = cards.length; nc.iota.retro.copy(cards[]); auto rnd = RandomGenerator(seed); foreach (immutable i, ref c; cards) c.swap(cards[(nc - 1) - rnd.next % (nc - i)]); } void show() const @safe { writefln("%(%-( %s%)\n%)", cards[] .chunks(8) .map!(row => row.map!(c => only("A23456789TJQK"[c / 4], "CDHS"[c % 4])))); } } void main(in string[] args) @safe { immutable seed = (args.length == 2) ? args[1].to!uint : 11_982; writeln("Hand ", seed); Deck cards; cards.deal(seed); cards.show; }
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Preserve the algorithm and functionality while converting the code from Delphi to PHP.
program Deal_cards_for_FreeCell; uses System.SysUtils; type TRandom = record Seed: Int64; function Next: Integer; end; TCard = record const kSuits = '♣♦♥♠'; kValues = 'A23456789TJQK'; var Value: Integer; Suit: Integer; procedure Create(rawvalue: Integer); overload; procedure Create(value, suit: Integer); overload; procedure Assign(other: TCard); function ToString: string; end; TDeck = record Cards: TArray<TCard>; procedure Create(Seed: Integer); function ToString: string; end; function TRandom.Next: Integer; begin Seed := ((Seed * 214013 + 2531011) and Integer.MaxValue); Result := Seed shr 16; end; procedure TCard.Create(rawvalue: Integer); begin Create(rawvalue div 4, rawvalue mod 4); end; procedure TCard.Assign(other: TCard); begin Create(other.Value, other.Suit); end; procedure TCard.Create(value, suit: Integer); begin self.Value := value; self.Suit := suit; end; function TCard.ToString: string; begin result := format('%s%s', [kValues[value + 1], kSuits[suit + 1]]); end; procedure TDeck.Create(Seed: Integer); var r: TRandom; i, j: integer; tmp: Tcard; begin r.Seed := Seed; SetLength(Cards, 52); for i := 0 to 51 do Cards[i].Create(51 - i); for i := 0 to 50 do begin j := 51 - (r.Next mod (52 - i)); tmp.Assign(Cards[i]); Cards[i].Assign(Cards[j]); Cards[j].Assign(tmp); end; end; function TDeck.ToString: string; var i: Integer; begin Result := ''; for i := 0 to length(Cards) - 1 do begin Result := Result + Cards[i].ToString; if i mod 8 = 7 then Result := Result + #10 else Result := Result + ' '; end; end; var Deck: TDeck; begin Deck.Create(1); Writeln('Deck 1'#10, Deck.ToString, #10); Deck.Create(617); Writeln('Deck 617'#10, Deck.ToString); readln; end.
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Transform the following Elixir implementation into PHP, maintaining the same output and logic.
defmodule FreeCell do import Bitwise @suits ~w( C D H S ) @pips ~w( A 2 3 4 5 6 7 8 9 T J Q K ) @orig_deck for pip <- @pips, suit <- @suits, do: pip <> suit def deal(games) do games = if length(games) == 0, do: [Enum.random(1..32000)], else: games Enum.each(games, fn seed -> IO.puts "Game Enum.reduce(52..2, {seed,@orig_deck}, fn len,{state,deck} -> state = ((214013 * state) + 2531011) &&& 0x7fff_ffff index = rem(state >>> 16, len) last = len - 1 {a, b} = {Enum.at(deck, index), Enum.at(deck, last)} {state, deck |> List.replace_at(index, b) |> List.replace_at(last, a)} end) |> elem(1) |> Enum.reverse |> Enum.chunk(8,8,[]) |> Enum.each(fn row -> Enum.join(row, " ") |> IO.puts end) IO.puts "" end) end end System.argv |> Enum.map(&String.to_integer/1) |> FreeCell.deal
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Produce a language-to-language conversion: from F# to PHP, same semantics.
let msKindaRand seed = let state = ref seed (fun (_:unit) -> state := (214013 * !state + 2531011) &&& System.Int32.MaxValue !state / (1<<<16)) let unshuffledDeck = [0..51] |> List.map(fun n->sprintf "%c%c" "A23456789TJQK".[n / 4] "CDHS".[n % 4]) let deal boot idx = let (last,rest) = boot |> List.rev |> fun xs->(List.head xs),(xs |> List.tail |> List.rev) if idx=((List.length boot) - 1) then last, rest else rest |> List.mapi (fun i x -> i,x) |> List.partition (fst >> ((>) idx)) |> fun (xs,ys) -> (List.map snd xs),(List.map snd ys) |> fun (xs,ys) -> (List.head ys),(xs @ last::(List.tail ys)) let game gameNo = let rnd = msKindaRand gameNo [52..-1..1] |> List.map (fun i->rnd() % i) |> List.fold (fun (dealt, boot) idx->deal boot idx |> fun (x,xs) -> (x::dealt, xs)) ([],unshuffledDeck) |> fst |> List.rev |> List.chunkBySize 8 |> List.map (String.concat " ") |> String.concat "\n" |> printfn "Game #%d\n%s\n" gameNo [1; 617] |> List.iter game
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Translate the given Factor code snippet into PHP without altering its behavior.
USING: formatting grouping io kernel literals make math math.functions namespaces qw sequences sequences.extras ; IN: rosetta-code.freecell CONSTANT: max-rand-ms $[ 1 15 shift 1 - ] CONSTANT: suits qw{ C D H S } CONSTANT: ranks qw{ A 2 3 4 5 6 7 8 9 T J Q K } SYMBOL: seed : (random) ( n1 n2 -- n3 ) seed get * + dup seed set ; : rand-ms ( -- n ) max-rand-ms 2531011 214013 (random) -16 shift bitand ; : init-deck ( -- seq ) ranks suits [ append ] cartesian-map concat V{ } like ; : swap-cards ( seq -- seq' ) rand-ms over length [ mod ] [ 1 - ] bi pick exchange ; : (deal) ( seq -- seq' ) [ [ swap-cards dup pop , ] until-empty ] { } make ; : deal ( game# -- seq ) seed set init-deck (deal) ; : .cards ( seq -- ) 8 group [ [ write bl ] each nl ] each nl ; : .game ( game# -- ) dup "Game #%d\n" printf deal .cards ; : freecell ( -- ) 1 617 [ .game ] bi@ ; MAIN: freecell
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Convert the following code from Fortran to PHP, ensuring the logic remains intact.
module Freecell use lcgs implicit none character(4) :: suit = "CDHS" character(13) :: rank = "A23456789TJQK" character(2) :: deck(0:51) contains subroutine Createdeck() integer :: i, j, n n = 0 do i = 1, 13 do j = 1, 4 deck(n) = rank(i:i) // suit(j:j) n = n + 1 end do end do end subroutine subroutine Freecelldeal(game) integer, intent(in) :: game integer(i64) :: rnum integer :: i, n character(2) :: tmp call Createdeck() rnum = msrand(game) do i = 51, 1, -1 n = mod(rnum, i+1) tmp = deck(n) deck(n) = deck(i) deck(i) = tmp rnum = msrand() end do write(*, "(a, i0)") "Game #", game write(*, "(8(a, tr1))") deck(51:0:-1) write(*,*) end subroutine end module Freecell program Freecell_test use Freecell implicit none call Freecelldeal(1) call Freecelldeal(617) end program
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Port the provided Groovy code into PHP while preserving the original functionality.
class FreeCell{ int seed List<String> createDeck(){ List<String> suits = ['♣','♦','♥','♠'] List<String> values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] return [suits,values].combinations{suit,value -> "$suit$value"} } int random() { seed = (214013 * seed + 2531011) & Integer.MAX_VALUE return seed >> 16 } List<String> shuffledDeck(List<String> cards) { List<String> deck = cards.clone() (deck.size() - 1..1).each{index -> int r = random() % (index + 1) deck.swap(r, index) } return deck } List<String> dealGame(int seed = 1){ this.seed= seed List<String> cards = shuffledDeck(createDeck()) (1..cards.size()).each{ number-> print "${cards.pop()}\t" if(number % 8 == 0) println('') } println('\n') } } def freecell = new FreeCell() freecell.dealGame() freecell.dealGame(617)
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Write the same code in PHP as shown below in Haskell.
import Data.Int import Data.Bits import Data.List import Data.Array.ST import Control.Monad import Control.Monad.ST import System.Environment srnd :: Int32 -> [Int] srnd = map (fromIntegral . flip shiftR 16) . tail . iterate (\x -> (x * 214013 + 2531011) .&. maxBound) deal :: Int32 -> [String] deal s = runST (do ar <- newListArray (0,51) $ sequence ["A23456789TJQK", "CDHS"] :: ST s (STArray s Int String) forM (zip [52,51..1] rnd) $ \(n, r) -> do let j = r `mod` n vj <- readArray ar j vn <- readArray ar (n - 1) writeArray ar j vn return vj) where rnd = srnd s showCards :: [String] -> IO () showCards = mapM_ (putStrLn . unwords) . takeWhile (not . null) . unfoldr (Just . splitAt 8) main :: IO () main = do args <- getArgs let s = read (head args) :: Int32 putStrLn $ "Deal " ++ show s ++ ":" let cards = deal s showCards cards
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Can you help me rewrite this code in PHP instead of Icon, keeping it the same logically?
procedure main(A) freecelldealer(\A[1] | &null) end procedure newDeck() every D := list(52) & i := 0 & r := !"A23456789TJQK" & s := !"CDHS" do D[i +:= 1] := r || s return D end procedure freecelldealer(gamenum) /gamenum := 11982 return showHand(freecellshuffle(newDeck(),gamenum)) end procedure showHand(D) write("Hand:\n") every writes(" ",(1 to 8) | "\n") every writes(" ",D[i := 1 to *D]) do if i%8 = 0 then write() write("\n") return D end procedure freecellshuffle(D,gamenum) srand_freecell(gamenum) D2 := [] until *D = 0 do { D[r := rand_freecell() % *D + 1] :=: D[*D] put(D2,pull(D)) } return D2 end procedure srand_freecell(x) static seed return seed := \x | \seed | 0 end procedure rand_freecell() return ishift(srand_freecell((214013 * srand_freecell() + 2531011) % 2147483648),-16) end
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }
Port the following code from J to PHP with equivalent syntax and logic.
deck=: ,/ 'A23456789TJQK' ,"0/ 7 u: '♣♦♥♠' srnd=: 3 :'SEED=:{.y,11982' srnd '' seed=: do bind 'SEED' rnd=: (2^16) <.@%~ (2^31) srnd@| 2531011 + 214013 * seed pairs=: <@<@~.@(<: , (| rnd))@>:@i.@-@# swaps=: [: > C.&.>/@|.@; deal=: |.@(swaps pairs) bind deck show=: (,"2)@:(_8 ]\ ' '&,.)
class FreeCell_Deal { protected $deck = array( 'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S', '4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S', '7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S', 'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS', 'KC', 'KD', 'KH', 'KS' ); protected $game; // Freecell Game Number protected $state; // Current state of the LCG public $deal = array(); // Generated card sequence to deal function __construct( $game ) { $this->game = max( min( $game, 32000 ), 1 ); $this->state = $this->game; while ( ! empty( $this->deck ) ) { $i = $this->lcg_rnd() % count( $this->deck ); $this->deal[] = $this->deck[ $i ]; $this->deck[ $i ] = end( $this->deck ); array_pop( $this->deck ); } } protected function lcg_rnd() { return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16; } function print( $cols = 8 ) { echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL; foreach ( array_chunk( $this->deal, $cols ) as $row ) { echo implode( " ", $row ), PHP_EOL; } echo PHP_EOL; } } $tests = array( 1, 617, 11982 ); foreach ( $tests as $game_num ) { $deal = new FreeCell_Deal( $game_num ); $deal->print(); }