Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the provided Julia code into PHP while preserving the original functionality. | 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()
| 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 Lua function in PHP with identical behavior. | 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)
| 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 this Mathematica block to PHP, preserving its control flow and logic. | 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]]];
| 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 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
| 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 OCaml. | 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
| 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();
}
|
Change the following Perl code into PHP without altering its purpose. |
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;
| 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 R implementation into PHP, 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 = "")
}
| 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 Racket implementation into PHP, maintaining the same output and logic. | #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)
| 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();
}
|
Generate an equivalent PHP version of this REXX code. |
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
| 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 Ruby. |
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
| 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 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)
}
| 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 Swift implementation into PHP, maintaining the same output 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)
| 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 this Tcl snippet to PHP and keep its semantics consistent. | 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
| 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 Rust instead of C++, keeping it the same logically? | #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;
}
|
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);
}
}
|
Change the following Java code into Rust without altering its purpose. | 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);
}
}
|
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);
}
}
|
Translate the given C# code snippet into Rust without altering its behavior. | 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));
}
}
}
|
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);
}
}
|
Please provide an equivalent version of this C code in Rust. | #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;
}
|
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);
}
}
|
Please provide an equivalent version of this Go code in Rust. | 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))
}
|
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);
}
}
|
Generate an equivalent Python version of this Rust code. |
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);
}
}
| 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 Ada implementation into C#, maintaining the same output and logic. | with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
package Sigint_Handler is
protected Handler is
entry Wait;
procedure Handle;
pragma Interrupt_Handler(Handle);
pragma Attach_Handler(Handle, Sigint);
private
Call_Count : Natural := 0;
end Handler;
end Sigint_Handler;
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Port the provided Ada code into C while preserving the original functionality. | with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
package Sigint_Handler is
protected Handler is
entry Wait;
procedure Handle;
pragma Interrupt_Handler(Handle);
pragma Attach_Handler(Handle, Sigint);
private
Call_Count : Natural := 0;
end Handler;
end Sigint_Handler;
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
package Sigint_Handler is
protected Handler is
entry Wait;
procedure Handle;
pragma Interrupt_Handler(Handle);
pragma Attach_Handler(Handle, Sigint);
private
Call_Count : Natural := 0;
end Handler;
end Sigint_Handler;
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in Go. | with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
package Sigint_Handler is
protected Handler is
entry Wait;
procedure Handle;
pragma Interrupt_Handler(Handle);
pragma Attach_Handler(Handle, Sigint);
private
Call_Count : Natural := 0;
end Handler;
end Sigint_Handler;
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
package Sigint_Handler is
protected Handler is
entry Wait;
procedure Handle;
pragma Interrupt_Handler(Handle);
pragma Attach_Handler(Handle, Sigint);
private
Call_Count : Natural := 0;
end Handler;
end Sigint_Handler;
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Port the following code from Ada to Python with equivalent syntax and logic. | with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
package Sigint_Handler is
protected Handler is
entry Wait;
procedure Handle;
pragma Interrupt_Handler(Handle);
pragma Attach_Handler(Handle, Sigint);
private
Call_Count : Natural := 0;
end Handler;
end Sigint_Handler;
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Write the same code in VB as shown below in Ada. | with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
package Sigint_Handler is
protected Handler is
entry Wait;
procedure Handle;
pragma Interrupt_Handler(Handle);
pragma Attach_Handler(Handle, Sigint);
private
Call_Count : Natural := 0;
end Handler;
end Sigint_Handler;
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Produce a language-to-language conversion: from AutoHotKey to C, same semantics. | Start:=A_TickCount
counter=0
SetTimer, timer, 500
return
timer:
Send % ++Counter "`n"
return
^c::
SetTimer, timer, off
SetFormat, float, 0.3
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Convert this AutoHotKey block to C#, preserving its control flow and logic. | Start:=A_TickCount
counter=0
SetTimer, timer, 500
return
timer:
Send % ++Counter "`n"
return
^c::
SetTimer, timer, off
SetFormat, float, 0.3
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Convert this AutoHotKey snippet to C++ and keep its semantics consistent. | Start:=A_TickCount
counter=0
SetTimer, timer, 500
return
timer:
Send % ++Counter "`n"
return
^c::
SetTimer, timer, off
SetFormat, float, 0.3
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Port the following code from AutoHotKey to Java with equivalent syntax and logic. | Start:=A_TickCount
counter=0
SetTimer, timer, 500
return
timer:
Send % ++Counter "`n"
return
^c::
SetTimer, timer, off
SetFormat, float, 0.3
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | Start:=A_TickCount
counter=0
SetTimer, timer, 500
return
timer:
Send % ++Counter "`n"
return
^c::
SetTimer, timer, off
SetFormat, float, 0.3
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Transform the following AutoHotKey implementation into VB, maintaining the same output and logic. | Start:=A_TickCount
counter=0
SetTimer, timer, 500
return
timer:
Send % ++Counter "`n"
return
^c::
SetTimer, timer, off
SetFormat, float, 0.3
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Change the programming language of this snippet from AutoHotKey to Go without modifying what it does. | Start:=A_TickCount
counter=0
SetTimer, timer, 500
return
timer:
Send % ++Counter "`n"
return
^c::
SetTimer, timer, off
SetFormat, float, 0.3
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Preserve the algorithm and functionality while converting the code from BBC_Basic to C. |
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
SYS "GetStdHandle", -10 TO @hfile%(1)
SYS "GetStdHandle", -11 TO @hfile%(2)
*INPUT 13
*OUTPUT 14
ON ERROR PRINT REPORT$ : QUIT ERR
CtrlC% = FALSE
handler% = FN_callback(FNsigint(), 1)
SYS FN_syscalls("SetConsoleCtrlHandler"), handler%, 1 TO !FN_systo(res%)
IF res%=0 PRINT "Could not set SIGINT handler" : QUIT 1
PRINT "Press Ctrl+C to test...."
TIME = 0
Time% = 50
REPEAT
WAIT 1
IF TIME > Time% THEN
PRINT Time%
Time% += 50
ENDIF
UNTIL CtrlC%
PRINT "Ctrl+C was pressed after "; TIME/100 " seconds."
QUIT
DEF FNsigint(T%)
CASE T% OF
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Transform the following BBC_Basic implementation into C#, maintaining the same output and logic. |
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
SYS "GetStdHandle", -10 TO @hfile%(1)
SYS "GetStdHandle", -11 TO @hfile%(2)
*INPUT 13
*OUTPUT 14
ON ERROR PRINT REPORT$ : QUIT ERR
CtrlC% = FALSE
handler% = FN_callback(FNsigint(), 1)
SYS FN_syscalls("SetConsoleCtrlHandler"), handler%, 1 TO !FN_systo(res%)
IF res%=0 PRINT "Could not set SIGINT handler" : QUIT 1
PRINT "Press Ctrl+C to test...."
TIME = 0
Time% = 50
REPEAT
WAIT 1
IF TIME > Time% THEN
PRINT Time%
Time% += 50
ENDIF
UNTIL CtrlC%
PRINT "Ctrl+C was pressed after "; TIME/100 " seconds."
QUIT
DEF FNsigint(T%)
CASE T% OF
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Port the provided BBC_Basic code into C++ while preserving the original functionality. |
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
SYS "GetStdHandle", -10 TO @hfile%(1)
SYS "GetStdHandle", -11 TO @hfile%(2)
*INPUT 13
*OUTPUT 14
ON ERROR PRINT REPORT$ : QUIT ERR
CtrlC% = FALSE
handler% = FN_callback(FNsigint(), 1)
SYS FN_syscalls("SetConsoleCtrlHandler"), handler%, 1 TO !FN_systo(res%)
IF res%=0 PRINT "Could not set SIGINT handler" : QUIT 1
PRINT "Press Ctrl+C to test...."
TIME = 0
Time% = 50
REPEAT
WAIT 1
IF TIME > Time% THEN
PRINT Time%
Time% += 50
ENDIF
UNTIL CtrlC%
PRINT "Ctrl+C was pressed after "; TIME/100 " seconds."
QUIT
DEF FNsigint(T%)
CASE T% OF
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in Java. |
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
SYS "GetStdHandle", -10 TO @hfile%(1)
SYS "GetStdHandle", -11 TO @hfile%(2)
*INPUT 13
*OUTPUT 14
ON ERROR PRINT REPORT$ : QUIT ERR
CtrlC% = FALSE
handler% = FN_callback(FNsigint(), 1)
SYS FN_syscalls("SetConsoleCtrlHandler"), handler%, 1 TO !FN_systo(res%)
IF res%=0 PRINT "Could not set SIGINT handler" : QUIT 1
PRINT "Press Ctrl+C to test...."
TIME = 0
Time% = 50
REPEAT
WAIT 1
IF TIME > Time% THEN
PRINT Time%
Time% += 50
ENDIF
UNTIL CtrlC%
PRINT "Ctrl+C was pressed after "; TIME/100 " seconds."
QUIT
DEF FNsigint(T%)
CASE T% OF
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the BBC_Basic version. |
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
SYS "GetStdHandle", -10 TO @hfile%(1)
SYS "GetStdHandle", -11 TO @hfile%(2)
*INPUT 13
*OUTPUT 14
ON ERROR PRINT REPORT$ : QUIT ERR
CtrlC% = FALSE
handler% = FN_callback(FNsigint(), 1)
SYS FN_syscalls("SetConsoleCtrlHandler"), handler%, 1 TO !FN_systo(res%)
IF res%=0 PRINT "Could not set SIGINT handler" : QUIT 1
PRINT "Press Ctrl+C to test...."
TIME = 0
Time% = 50
REPEAT
WAIT 1
IF TIME > Time% THEN
PRINT Time%
Time% += 50
ENDIF
UNTIL CtrlC%
PRINT "Ctrl+C was pressed after "; TIME/100 " seconds."
QUIT
DEF FNsigint(T%)
CASE T% OF
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Generate a VB translation of this BBC_Basic snippet without changing its computational steps. |
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
SYS "GetStdHandle", -10 TO @hfile%(1)
SYS "GetStdHandle", -11 TO @hfile%(2)
*INPUT 13
*OUTPUT 14
ON ERROR PRINT REPORT$ : QUIT ERR
CtrlC% = FALSE
handler% = FN_callback(FNsigint(), 1)
SYS FN_syscalls("SetConsoleCtrlHandler"), handler%, 1 TO !FN_systo(res%)
IF res%=0 PRINT "Could not set SIGINT handler" : QUIT 1
PRINT "Press Ctrl+C to test...."
TIME = 0
Time% = 50
REPEAT
WAIT 1
IF TIME > Time% THEN
PRINT Time%
Time% += 50
ENDIF
UNTIL CtrlC%
PRINT "Ctrl+C was pressed after "; TIME/100 " seconds."
QUIT
DEF FNsigint(T%)
CASE T% OF
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Convert this BBC_Basic snippet to Go and keep its semantics consistent. |
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
SYS "GetStdHandle", -10 TO @hfile%(1)
SYS "GetStdHandle", -11 TO @hfile%(2)
*INPUT 13
*OUTPUT 14
ON ERROR PRINT REPORT$ : QUIT ERR
CtrlC% = FALSE
handler% = FN_callback(FNsigint(), 1)
SYS FN_syscalls("SetConsoleCtrlHandler"), handler%, 1 TO !FN_systo(res%)
IF res%=0 PRINT "Could not set SIGINT handler" : QUIT 1
PRINT "Press Ctrl+C to test...."
TIME = 0
Time% = 50
REPEAT
WAIT 1
IF TIME > Time% THEN
PRINT Time%
Time% += 50
ENDIF
UNTIL CtrlC%
PRINT "Ctrl+C was pressed after "; TIME/100 " seconds."
QUIT
DEF FNsigint(T%)
CASE T% OF
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C. | (require 'clojure.repl)
(def start (System/nanoTime))
(defn shutdown [_]
(println "Received INT after"
(/ (- (System/nanoTime) start) 1e9)
"seconds.")
(System/exit 0))
(clojure.repl/set-break-handler! shutdown)
(doseq [i (range)]
(prn i)
(Thread/sleep 500))
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Generate a C# translation of this Clojure snippet without changing its computational steps. | (require 'clojure.repl)
(def start (System/nanoTime))
(defn shutdown [_]
(println "Received INT after"
(/ (- (System/nanoTime) start) 1e9)
"seconds.")
(System/exit 0))
(clojure.repl/set-break-handler! shutdown)
(doseq [i (range)]
(prn i)
(Thread/sleep 500))
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Ensure the translated C++ code behaves exactly like the original Clojure snippet. | (require 'clojure.repl)
(def start (System/nanoTime))
(defn shutdown [_]
(println "Received INT after"
(/ (- (System/nanoTime) start) 1e9)
"seconds.")
(System/exit 0))
(clojure.repl/set-break-handler! shutdown)
(doseq [i (range)]
(prn i)
(Thread/sleep 500))
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Can you help me rewrite this code in Java instead of Clojure, keeping it the same logically? | (require 'clojure.repl)
(def start (System/nanoTime))
(defn shutdown [_]
(println "Received INT after"
(/ (- (System/nanoTime) start) 1e9)
"seconds.")
(System/exit 0))
(clojure.repl/set-break-handler! shutdown)
(doseq [i (range)]
(prn i)
(Thread/sleep 500))
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Produce a functionally identical Python code for the snippet given in Clojure. | (require 'clojure.repl)
(def start (System/nanoTime))
(defn shutdown [_]
(println "Received INT after"
(/ (- (System/nanoTime) start) 1e9)
"seconds.")
(System/exit 0))
(clojure.repl/set-break-handler! shutdown)
(doseq [i (range)]
(prn i)
(Thread/sleep 500))
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Translate the given Clojure code snippet into VB without altering its behavior. | (require 'clojure.repl)
(def start (System/nanoTime))
(defn shutdown [_]
(println "Received INT after"
(/ (- (System/nanoTime) start) 1e9)
"seconds.")
(System/exit 0))
(clojure.repl/set-break-handler! shutdown)
(doseq [i (range)]
(prn i)
(Thread/sleep 500))
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Transform the following Clojure implementation into Go, maintaining the same output and logic. | (require 'clojure.repl)
(def start (System/nanoTime))
(defn shutdown [_]
(println "Received INT after"
(/ (- (System/nanoTime) start) 1e9)
"seconds.")
(System/exit 0))
(clojure.repl/set-break-handler! shutdown)
(doseq [i (range)]
(prn i)
(Thread/sleep 500))
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Produce a functionally identical C code for the snippet given in Common_Lisp. | (ql:quickload :cffi)
(defconstant +SIGINT+ 2)
(defmacro set-signal-handler (signo &body body)
(let ((handler (gensym "HANDLER")))
`(progn
(cffi:defcallback ,handler :void ((signo :int))
(declare (ignore signo))
,@body)
(cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler)))))
(defvar *initial* (get-internal-real-time))
(set-signal-handler +SIGINT+
(format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second))
(quit))
(let ((i 0))
(loop do
(format t "~a~&" (incf i))
(sleep 0.5)))
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Ensure the translated C# code behaves exactly like the original Common_Lisp snippet. | (ql:quickload :cffi)
(defconstant +SIGINT+ 2)
(defmacro set-signal-handler (signo &body body)
(let ((handler (gensym "HANDLER")))
`(progn
(cffi:defcallback ,handler :void ((signo :int))
(declare (ignore signo))
,@body)
(cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler)))))
(defvar *initial* (get-internal-real-time))
(set-signal-handler +SIGINT+
(format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second))
(quit))
(let ((i 0))
(loop do
(format t "~a~&" (incf i))
(sleep 0.5)))
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Generate a C++ translation of this Common_Lisp snippet without changing its computational steps. | (ql:quickload :cffi)
(defconstant +SIGINT+ 2)
(defmacro set-signal-handler (signo &body body)
(let ((handler (gensym "HANDLER")))
`(progn
(cffi:defcallback ,handler :void ((signo :int))
(declare (ignore signo))
,@body)
(cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler)))))
(defvar *initial* (get-internal-real-time))
(set-signal-handler +SIGINT+
(format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second))
(quit))
(let ((i 0))
(loop do
(format t "~a~&" (incf i))
(sleep 0.5)))
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Rewrite the snippet below in Java so it works the same as the original Common_Lisp code. | (ql:quickload :cffi)
(defconstant +SIGINT+ 2)
(defmacro set-signal-handler (signo &body body)
(let ((handler (gensym "HANDLER")))
`(progn
(cffi:defcallback ,handler :void ((signo :int))
(declare (ignore signo))
,@body)
(cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler)))))
(defvar *initial* (get-internal-real-time))
(set-signal-handler +SIGINT+
(format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second))
(quit))
(let ((i 0))
(loop do
(format t "~a~&" (incf i))
(sleep 0.5)))
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Translate the given Common_Lisp code snippet into Python without altering its behavior. | (ql:quickload :cffi)
(defconstant +SIGINT+ 2)
(defmacro set-signal-handler (signo &body body)
(let ((handler (gensym "HANDLER")))
`(progn
(cffi:defcallback ,handler :void ((signo :int))
(declare (ignore signo))
,@body)
(cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler)))))
(defvar *initial* (get-internal-real-time))
(set-signal-handler +SIGINT+
(format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second))
(quit))
(let ((i 0))
(loop do
(format t "~a~&" (incf i))
(sleep 0.5)))
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Write a version of this Common_Lisp function in VB with identical behavior. | (ql:quickload :cffi)
(defconstant +SIGINT+ 2)
(defmacro set-signal-handler (signo &body body)
(let ((handler (gensym "HANDLER")))
`(progn
(cffi:defcallback ,handler :void ((signo :int))
(declare (ignore signo))
,@body)
(cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler)))))
(defvar *initial* (get-internal-real-time))
(set-signal-handler +SIGINT+
(format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second))
(quit))
(let ((i 0))
(loop do
(format t "~a~&" (incf i))
(sleep 0.5)))
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Translate this program into Go but keep the logic exactly as in Common_Lisp. | (ql:quickload :cffi)
(defconstant +SIGINT+ 2)
(defmacro set-signal-handler (signo &body body)
(let ((handler (gensym "HANDLER")))
`(progn
(cffi:defcallback ,handler :void ((signo :int))
(declare (ignore signo))
,@body)
(cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler)))))
(defvar *initial* (get-internal-real-time))
(set-signal-handler +SIGINT+
(format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second))
(quit))
(let ((i 0))
(loop do
(format t "~a~&" (incf i))
(sleep 0.5)))
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Port the provided D code into C while preserving the original functionality. | import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;
__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
gotint = 1;
}
void main() {
auto sw = StopWatch(AutoStart.yes);
signal(SIGINT, &handleSigint);
for (int i=0; !gotint;) {
Thread.sleep(500_000.usecs);
if (gotint) {
break;
}
writeln(++i);
}
sw.stop();
auto td = sw.peek();
writeln("Program has run for ", td);
}
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Rewrite the snippet below in C# so it works the same as the original D code. | import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;
__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
gotint = 1;
}
void main() {
auto sw = StopWatch(AutoStart.yes);
signal(SIGINT, &handleSigint);
for (int i=0; !gotint;) {
Thread.sleep(500_000.usecs);
if (gotint) {
break;
}
writeln(++i);
}
sw.stop();
auto td = sw.peek();
writeln("Program has run for ", td);
}
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Port the following code from D to C++ with equivalent syntax and logic. | import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;
__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
gotint = 1;
}
void main() {
auto sw = StopWatch(AutoStart.yes);
signal(SIGINT, &handleSigint);
for (int i=0; !gotint;) {
Thread.sleep(500_000.usecs);
if (gotint) {
break;
}
writeln(++i);
}
sw.stop();
auto td = sw.peek();
writeln("Program has run for ", td);
}
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Produce a language-to-language conversion: from D to Java, same semantics. | import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;
__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
gotint = 1;
}
void main() {
auto sw = StopWatch(AutoStart.yes);
signal(SIGINT, &handleSigint);
for (int i=0; !gotint;) {
Thread.sleep(500_000.usecs);
if (gotint) {
break;
}
writeln(++i);
}
sw.stop();
auto td = sw.peek();
writeln("Program has run for ", td);
}
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;
__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
gotint = 1;
}
void main() {
auto sw = StopWatch(AutoStart.yes);
signal(SIGINT, &handleSigint);
for (int i=0; !gotint;) {
Thread.sleep(500_000.usecs);
if (gotint) {
break;
}
writeln(++i);
}
sw.stop();
auto td = sw.peek();
writeln("Program has run for ", td);
}
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Generate a VB translation of this D snippet without changing its computational steps. | import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;
__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
gotint = 1;
}
void main() {
auto sw = StopWatch(AutoStart.yes);
signal(SIGINT, &handleSigint);
for (int i=0; !gotint;) {
Thread.sleep(500_000.usecs);
if (gotint) {
break;
}
writeln(++i);
}
sw.stop();
auto td = sw.peek();
writeln("Program has run for ", td);
}
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Change the following D code into Go without altering its purpose. | import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;
__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
gotint = 1;
}
void main() {
auto sw = StopWatch(AutoStart.yes);
signal(SIGINT, &handleSigint);
for (int i=0; !gotint;) {
Thread.sleep(500_000.usecs);
if (gotint) {
break;
}
writeln(++i);
}
sw.stop();
auto td = sw.peek();
writeln("Program has run for ", td);
}
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Change the programming language of this snippet from Erlang to C without modifying what it does. | #! /usr/bin/env escript
main([]) ->
erlang:unregister(erl_signal_server),
erlang:register(erl_signal_server, self()),
Start = seconds(),
os:set_signal(sigquit, handle),
Pid = spawn(fun() -> output_loop(1) end),
receive
{notify, sigquit} ->
erlang:exit(Pid, normal),
Seconds = seconds() - Start,
io:format("Program has run for ~b seconds~n", [Seconds])
end.
seconds() ->
calendar:datetime_to_gregorian_seconds({date(),time()}).
output_loop(N) ->
io:format("~b~n",[N]),
timer:sleep(500),
output_loop(N + 1).
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Please provide an equivalent version of this Erlang code in C#. | #! /usr/bin/env escript
main([]) ->
erlang:unregister(erl_signal_server),
erlang:register(erl_signal_server, self()),
Start = seconds(),
os:set_signal(sigquit, handle),
Pid = spawn(fun() -> output_loop(1) end),
receive
{notify, sigquit} ->
erlang:exit(Pid, normal),
Seconds = seconds() - Start,
io:format("Program has run for ~b seconds~n", [Seconds])
end.
seconds() ->
calendar:datetime_to_gregorian_seconds({date(),time()}).
output_loop(N) ->
io:format("~b~n",[N]),
timer:sleep(500),
output_loop(N + 1).
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Write the same code in C++ as shown below in Erlang. | #! /usr/bin/env escript
main([]) ->
erlang:unregister(erl_signal_server),
erlang:register(erl_signal_server, self()),
Start = seconds(),
os:set_signal(sigquit, handle),
Pid = spawn(fun() -> output_loop(1) end),
receive
{notify, sigquit} ->
erlang:exit(Pid, normal),
Seconds = seconds() - Start,
io:format("Program has run for ~b seconds~n", [Seconds])
end.
seconds() ->
calendar:datetime_to_gregorian_seconds({date(),time()}).
output_loop(N) ->
io:format("~b~n",[N]),
timer:sleep(500),
output_loop(N + 1).
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Change the programming language of this snippet from Erlang to Java without modifying what it does. | #! /usr/bin/env escript
main([]) ->
erlang:unregister(erl_signal_server),
erlang:register(erl_signal_server, self()),
Start = seconds(),
os:set_signal(sigquit, handle),
Pid = spawn(fun() -> output_loop(1) end),
receive
{notify, sigquit} ->
erlang:exit(Pid, normal),
Seconds = seconds() - Start,
io:format("Program has run for ~b seconds~n", [Seconds])
end.
seconds() ->
calendar:datetime_to_gregorian_seconds({date(),time()}).
output_loop(N) ->
io:format("~b~n",[N]),
timer:sleep(500),
output_loop(N + 1).
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Transform the following Erlang implementation into Python, maintaining the same output and logic. | #! /usr/bin/env escript
main([]) ->
erlang:unregister(erl_signal_server),
erlang:register(erl_signal_server, self()),
Start = seconds(),
os:set_signal(sigquit, handle),
Pid = spawn(fun() -> output_loop(1) end),
receive
{notify, sigquit} ->
erlang:exit(Pid, normal),
Seconds = seconds() - Start,
io:format("Program has run for ~b seconds~n", [Seconds])
end.
seconds() ->
calendar:datetime_to_gregorian_seconds({date(),time()}).
output_loop(N) ->
io:format("~b~n",[N]),
timer:sleep(500),
output_loop(N + 1).
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Ensure the translated VB code behaves exactly like the original Erlang snippet. | #! /usr/bin/env escript
main([]) ->
erlang:unregister(erl_signal_server),
erlang:register(erl_signal_server, self()),
Start = seconds(),
os:set_signal(sigquit, handle),
Pid = spawn(fun() -> output_loop(1) end),
receive
{notify, sigquit} ->
erlang:exit(Pid, normal),
Seconds = seconds() - Start,
io:format("Program has run for ~b seconds~n", [Seconds])
end.
seconds() ->
calendar:datetime_to_gregorian_seconds({date(),time()}).
output_loop(N) ->
io:format("~b~n",[N]),
timer:sleep(500),
output_loop(N + 1).
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Can you help me rewrite this code in Go instead of Erlang, keeping it the same logically? | #! /usr/bin/env escript
main([]) ->
erlang:unregister(erl_signal_server),
erlang:register(erl_signal_server, self()),
Start = seconds(),
os:set_signal(sigquit, handle),
Pid = spawn(fun() -> output_loop(1) end),
receive
{notify, sigquit} ->
erlang:exit(Pid, normal),
Seconds = seconds() - Start,
io:format("Program has run for ~b seconds~n", [Seconds])
end.
seconds() ->
calendar:datetime_to_gregorian_seconds({date(),time()}).
output_loop(N) ->
io:format("~b~n",[N]),
timer:sleep(500),
output_loop(N + 1).
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Convert this F# snippet to C and keep its semantics consistent. | open System
let rec loop n = Console.WriteLine( n:int )
Threading.Thread.Sleep( 500 )
loop (n + 1)
let main() =
let start = DateTime.Now
Console.CancelKeyPress.Add(
fun _ -> let span = DateTime.Now - start
printfn "Program has run for %.0f seconds" span.TotalSeconds
)
loop 1
main()
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Write the same code in C# as shown below in F#. | open System
let rec loop n = Console.WriteLine( n:int )
Threading.Thread.Sleep( 500 )
loop (n + 1)
let main() =
let start = DateTime.Now
Console.CancelKeyPress.Add(
fun _ -> let span = DateTime.Now - start
printfn "Program has run for %.0f seconds" span.TotalSeconds
)
loop 1
main()
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Ensure the translated C++ code behaves exactly like the original F# snippet. | open System
let rec loop n = Console.WriteLine( n:int )
Threading.Thread.Sleep( 500 )
loop (n + 1)
let main() =
let start = DateTime.Now
Console.CancelKeyPress.Add(
fun _ -> let span = DateTime.Now - start
printfn "Program has run for %.0f seconds" span.TotalSeconds
)
loop 1
main()
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Change the following F# code into Java without altering its purpose. | open System
let rec loop n = Console.WriteLine( n:int )
Threading.Thread.Sleep( 500 )
loop (n + 1)
let main() =
let start = DateTime.Now
Console.CancelKeyPress.Add(
fun _ -> let span = DateTime.Now - start
printfn "Program has run for %.0f seconds" span.TotalSeconds
)
loop 1
main()
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Please provide an equivalent version of this F# code in Python. | open System
let rec loop n = Console.WriteLine( n:int )
Threading.Thread.Sleep( 500 )
loop (n + 1)
let main() =
let start = DateTime.Now
Console.CancelKeyPress.Add(
fun _ -> let span = DateTime.Now - start
printfn "Program has run for %.0f seconds" span.TotalSeconds
)
loop 1
main()
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Write the same code in VB as shown below in F#. | open System
let rec loop n = Console.WriteLine( n:int )
Threading.Thread.Sleep( 500 )
loop (n + 1)
let main() =
let start = DateTime.Now
Console.CancelKeyPress.Add(
fun _ -> let span = DateTime.Now - start
printfn "Program has run for %.0f seconds" span.TotalSeconds
)
loop 1
main()
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in Go. | open System
let rec loop n = Console.WriteLine( n:int )
Threading.Thread.Sleep( 500 )
loop (n + 1)
let main() =
let start = DateTime.Now
Console.CancelKeyPress.Add(
fun _ -> let span = DateTime.Now - start
printfn "Program has run for %.0f seconds" span.TotalSeconds
)
loop 1
main()
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Write the same algorithm in C as shown in this Forth implementation. | -28 constant SIGINT
: numbers
begin dup . cr 1+ 500 ms again ;
: main
utime
0 begin
['] numbers catch
SIGINT =
until drop
utime d- dnegate
<# # # # # # # [char] . hold #s #> type ." seconds" ;
main bye
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Change the programming language of this snippet from Forth to C# without modifying what it does. | -28 constant SIGINT
: numbers
begin dup . cr 1+ 500 ms again ;
: main
utime
0 begin
['] numbers catch
SIGINT =
until drop
utime d- dnegate
<# # # # # # # [char] . hold #s #> type ." seconds" ;
main bye
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Write the same code in C++ as shown below in Forth. | -28 constant SIGINT
: numbers
begin dup . cr 1+ 500 ms again ;
: main
utime
0 begin
['] numbers catch
SIGINT =
until drop
utime d- dnegate
<# # # # # # # [char] . hold #s #> type ." seconds" ;
main bye
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Generate a Java translation of this Forth snippet without changing its computational steps. | -28 constant SIGINT
: numbers
begin dup . cr 1+ 500 ms again ;
: main
utime
0 begin
['] numbers catch
SIGINT =
until drop
utime d- dnegate
<# # # # # # # [char] . hold #s #> type ." seconds" ;
main bye
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Change the following Forth code into Python without altering its purpose. | -28 constant SIGINT
: numbers
begin dup . cr 1+ 500 ms again ;
: main
utime
0 begin
['] numbers catch
SIGINT =
until drop
utime d- dnegate
<# # # # # # # [char] . hold #s #> type ." seconds" ;
main bye
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Write the same code in VB as shown below in Forth. | -28 constant SIGINT
: numbers
begin dup . cr 1+ 500 ms again ;
: main
utime
0 begin
['] numbers catch
SIGINT =
until drop
utime d- dnegate
<# # # # # # # [char] . hold #s #> type ." seconds" ;
main bye
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Write the same algorithm in Go as shown in this Forth implementation. | -28 constant SIGINT
: numbers
begin dup . cr 1+ 500 ms again ;
: main
utime
0 begin
['] numbers catch
SIGINT =
until drop
utime d- dnegate
<# # # # # # # [char] . hold #s #> type ." seconds" ;
main bye
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Write the same algorithm in C# as shown in this Fortran implementation. | program signal_handling
use, intrinsic :: iso_fortran_env, only: atomic_logical_kind
implicit none
interface
integer(C_INT) function usleep(microseconds) bind(c)
use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T
integer(C_INT32_T), value :: microseconds
end function usleep
end interface
integer, parameter :: half_second = 500000
integer, parameter :: sigint = 2
integer, parameter :: sigquit = 3
logical(atomic_logical_kind) :: interrupt_received[*]
integer :: half_seconds
logical :: interrupt_received_ref
interrupt_received = .false.
half_seconds = 0
call signal(sigint, signal_handler)
call signal(sigquit, signal_handler)
do
if (usleep(half_second) == -1) &
print *, "Call to usleep interrupted."
call atomic_ref(interrupt_received_ref, interrupt_received)
if (interrupt_received_ref) then
print "(A,I0,A)", "Program ran for ", half_seconds / 2, " second(s)."
stop
end if
half_seconds = half_seconds + 1
print "(I0)", half_seconds
end do
contains
subroutine signal_handler(sig_num)
use, intrinsic :: iso_c_binding, only: C_INT
integer(C_INT), value, intent(in) :: sig_num
select case (sig_num)
case (sigint)
print *, "Received SIGINT."
case (sigquit)
print *, "Received SIGQUIT."
end select
call atomic_define(interrupt_received, .true.)
end subroutine signal_handler
end program signal_handling
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Rewrite the snippet below in C++ so it works the same as the original Fortran code. | program signal_handling
use, intrinsic :: iso_fortran_env, only: atomic_logical_kind
implicit none
interface
integer(C_INT) function usleep(microseconds) bind(c)
use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T
integer(C_INT32_T), value :: microseconds
end function usleep
end interface
integer, parameter :: half_second = 500000
integer, parameter :: sigint = 2
integer, parameter :: sigquit = 3
logical(atomic_logical_kind) :: interrupt_received[*]
integer :: half_seconds
logical :: interrupt_received_ref
interrupt_received = .false.
half_seconds = 0
call signal(sigint, signal_handler)
call signal(sigquit, signal_handler)
do
if (usleep(half_second) == -1) &
print *, "Call to usleep interrupted."
call atomic_ref(interrupt_received_ref, interrupt_received)
if (interrupt_received_ref) then
print "(A,I0,A)", "Program ran for ", half_seconds / 2, " second(s)."
stop
end if
half_seconds = half_seconds + 1
print "(I0)", half_seconds
end do
contains
subroutine signal_handler(sig_num)
use, intrinsic :: iso_c_binding, only: C_INT
integer(C_INT), value, intent(in) :: sig_num
select case (sig_num)
case (sigint)
print *, "Received SIGINT."
case (sigquit)
print *, "Received SIGQUIT."
end select
call atomic_define(interrupt_received, .true.)
end subroutine signal_handler
end program signal_handling
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Translate the given Fortran code snippet into C without altering its behavior. | program signal_handling
use, intrinsic :: iso_fortran_env, only: atomic_logical_kind
implicit none
interface
integer(C_INT) function usleep(microseconds) bind(c)
use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T
integer(C_INT32_T), value :: microseconds
end function usleep
end interface
integer, parameter :: half_second = 500000
integer, parameter :: sigint = 2
integer, parameter :: sigquit = 3
logical(atomic_logical_kind) :: interrupt_received[*]
integer :: half_seconds
logical :: interrupt_received_ref
interrupt_received = .false.
half_seconds = 0
call signal(sigint, signal_handler)
call signal(sigquit, signal_handler)
do
if (usleep(half_second) == -1) &
print *, "Call to usleep interrupted."
call atomic_ref(interrupt_received_ref, interrupt_received)
if (interrupt_received_ref) then
print "(A,I0,A)", "Program ran for ", half_seconds / 2, " second(s)."
stop
end if
half_seconds = half_seconds + 1
print "(I0)", half_seconds
end do
contains
subroutine signal_handler(sig_num)
use, intrinsic :: iso_c_binding, only: C_INT
integer(C_INT), value, intent(in) :: sig_num
select case (sig_num)
case (sigint)
print *, "Received SIGINT."
case (sigquit)
print *, "Received SIGQUIT."
end select
call atomic_define(interrupt_received, .true.)
end subroutine signal_handler
end program signal_handling
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Generate a Java translation of this Fortran snippet without changing its computational steps. | program signal_handling
use, intrinsic :: iso_fortran_env, only: atomic_logical_kind
implicit none
interface
integer(C_INT) function usleep(microseconds) bind(c)
use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T
integer(C_INT32_T), value :: microseconds
end function usleep
end interface
integer, parameter :: half_second = 500000
integer, parameter :: sigint = 2
integer, parameter :: sigquit = 3
logical(atomic_logical_kind) :: interrupt_received[*]
integer :: half_seconds
logical :: interrupt_received_ref
interrupt_received = .false.
half_seconds = 0
call signal(sigint, signal_handler)
call signal(sigquit, signal_handler)
do
if (usleep(half_second) == -1) &
print *, "Call to usleep interrupted."
call atomic_ref(interrupt_received_ref, interrupt_received)
if (interrupt_received_ref) then
print "(A,I0,A)", "Program ran for ", half_seconds / 2, " second(s)."
stop
end if
half_seconds = half_seconds + 1
print "(I0)", half_seconds
end do
contains
subroutine signal_handler(sig_num)
use, intrinsic :: iso_c_binding, only: C_INT
integer(C_INT), value, intent(in) :: sig_num
select case (sig_num)
case (sigint)
print *, "Received SIGINT."
case (sigquit)
print *, "Received SIGQUIT."
end select
call atomic_define(interrupt_received, .true.)
end subroutine signal_handler
end program signal_handling
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Generate a Python translation of this Fortran snippet without changing its computational steps. | program signal_handling
use, intrinsic :: iso_fortran_env, only: atomic_logical_kind
implicit none
interface
integer(C_INT) function usleep(microseconds) bind(c)
use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T
integer(C_INT32_T), value :: microseconds
end function usleep
end interface
integer, parameter :: half_second = 500000
integer, parameter :: sigint = 2
integer, parameter :: sigquit = 3
logical(atomic_logical_kind) :: interrupt_received[*]
integer :: half_seconds
logical :: interrupt_received_ref
interrupt_received = .false.
half_seconds = 0
call signal(sigint, signal_handler)
call signal(sigquit, signal_handler)
do
if (usleep(half_second) == -1) &
print *, "Call to usleep interrupted."
call atomic_ref(interrupt_received_ref, interrupt_received)
if (interrupt_received_ref) then
print "(A,I0,A)", "Program ran for ", half_seconds / 2, " second(s)."
stop
end if
half_seconds = half_seconds + 1
print "(I0)", half_seconds
end do
contains
subroutine signal_handler(sig_num)
use, intrinsic :: iso_c_binding, only: C_INT
integer(C_INT), value, intent(in) :: sig_num
select case (sig_num)
case (sigint)
print *, "Received SIGINT."
case (sigquit)
print *, "Received SIGQUIT."
end select
call atomic_define(interrupt_received, .true.)
end subroutine signal_handler
end program signal_handling
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Please provide an equivalent version of this Fortran code in VB. | program signal_handling
use, intrinsic :: iso_fortran_env, only: atomic_logical_kind
implicit none
interface
integer(C_INT) function usleep(microseconds) bind(c)
use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T
integer(C_INT32_T), value :: microseconds
end function usleep
end interface
integer, parameter :: half_second = 500000
integer, parameter :: sigint = 2
integer, parameter :: sigquit = 3
logical(atomic_logical_kind) :: interrupt_received[*]
integer :: half_seconds
logical :: interrupt_received_ref
interrupt_received = .false.
half_seconds = 0
call signal(sigint, signal_handler)
call signal(sigquit, signal_handler)
do
if (usleep(half_second) == -1) &
print *, "Call to usleep interrupted."
call atomic_ref(interrupt_received_ref, interrupt_received)
if (interrupt_received_ref) then
print "(A,I0,A)", "Program ran for ", half_seconds / 2, " second(s)."
stop
end if
half_seconds = half_seconds + 1
print "(I0)", half_seconds
end do
contains
subroutine signal_handler(sig_num)
use, intrinsic :: iso_c_binding, only: C_INT
integer(C_INT), value, intent(in) :: sig_num
select case (sig_num)
case (sigint)
print *, "Received SIGINT."
case (sigquit)
print *, "Received SIGQUIT."
end select
call atomic_define(interrupt_received, .true.)
end subroutine signal_handler
end program signal_handling
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Change the programming language of this snippet from Fortran to PHP without modifying what it does. | program signal_handling
use, intrinsic :: iso_fortran_env, only: atomic_logical_kind
implicit none
interface
integer(C_INT) function usleep(microseconds) bind(c)
use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T
integer(C_INT32_T), value :: microseconds
end function usleep
end interface
integer, parameter :: half_second = 500000
integer, parameter :: sigint = 2
integer, parameter :: sigquit = 3
logical(atomic_logical_kind) :: interrupt_received[*]
integer :: half_seconds
logical :: interrupt_received_ref
interrupt_received = .false.
half_seconds = 0
call signal(sigint, signal_handler)
call signal(sigquit, signal_handler)
do
if (usleep(half_second) == -1) &
print *, "Call to usleep interrupted."
call atomic_ref(interrupt_received_ref, interrupt_received)
if (interrupt_received_ref) then
print "(A,I0,A)", "Program ran for ", half_seconds / 2, " second(s)."
stop
end if
half_seconds = half_seconds + 1
print "(I0)", half_seconds
end do
contains
subroutine signal_handler(sig_num)
use, intrinsic :: iso_c_binding, only: C_INT
integer(C_INT), value, intent(in) :: sig_num
select case (sig_num)
case (sigint)
print *, "Received SIGINT."
case (sigquit)
print *, "Received SIGQUIT."
end select
call atomic_define(interrupt_received, .true.)
end subroutine signal_handler
end program signal_handling
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Can you help me rewrite this code in C instead of Haskell, keeping it the same logically? | import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
main = do t0 <- getCurrentTime
catch (loop 0)
(\e -> if e == UserInterrupt
then do t1 <- getCurrentTime
putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
else throwIO e)
loop i = do print i
threadDelay 500000
loop (i + 1)
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Produce a functionally identical C# code for the snippet given in Haskell. | import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
main = do t0 <- getCurrentTime
catch (loop 0)
(\e -> if e == UserInterrupt
then do t1 <- getCurrentTime
putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
else throwIO e)
loop i = do print i
threadDelay 500000
loop (i + 1)
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Produce a language-to-language conversion: from Haskell to C++, same semantics. | import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
main = do t0 <- getCurrentTime
catch (loop 0)
(\e -> if e == UserInterrupt
then do t1 <- getCurrentTime
putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
else throwIO e)
loop i = do print i
threadDelay 500000
loop (i + 1)
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Haskell version. | import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
main = do t0 <- getCurrentTime
catch (loop 0)
(\e -> if e == UserInterrupt
then do t1 <- getCurrentTime
putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
else throwIO e)
loop i = do print i
threadDelay 500000
loop (i + 1)
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Convert this Haskell snippet to Python and keep its semantics consistent. | import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
main = do t0 <- getCurrentTime
catch (loop 0)
(\e -> if e == UserInterrupt
then do t1 <- getCurrentTime
putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
else throwIO e)
loop i = do print i
threadDelay 500000
loop (i + 1)
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Rewrite the snippet below in VB so it works the same as the original Haskell code. | import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
main = do t0 <- getCurrentTime
catch (loop 0)
(\e -> if e == UserInterrupt
then do t1 <- getCurrentTime
putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
else throwIO e)
loop i = do print i
threadDelay 500000
loop (i + 1)
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Produce a functionally identical Go code for the snippet given in Haskell. | import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
main = do t0 <- getCurrentTime
catch (loop 0)
(\e -> if e == UserInterrupt
then do t1 <- getCurrentTime
putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
else throwIO e)
loop i = do print i
threadDelay 500000
loop (i + 1)
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Convert this Julia block to C, preserving its control flow and logic. | ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
function timeit()
ticks = 0
try
while true
sleep(0.5)
ticks += 1
println(ticks)
end
catch
end
end
@time timeit()
println("Done.")
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Write a version of this Julia function in C# with identical behavior. | ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
function timeit()
ticks = 0
try
while true
sleep(0.5)
ticks += 1
println(ticks)
end
catch
end
end
@time timeit()
println("Done.")
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Translate this program into C++ but keep the logic exactly as in Julia. | ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
function timeit()
ticks = 0
try
while true
sleep(0.5)
ticks += 1
println(ticks)
end
catch
end
end
@time timeit()
println("Done.")
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Julia to Java. | ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
function timeit()
ticks = 0
try
while true
sleep(0.5)
ticks += 1
println(ticks)
end
catch
end
end
@time timeit()
println("Done.")
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.