Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Please provide an equivalent version of this C code in PHP. | #include<math.h>
#include<stdio.h>
int
main ()
{
double inputs[11], check = 400, result;
int i;
printf ("\nPlease enter 11 numbers :");
for (i = 0; i < 11; i++)
{
scanf ("%lf", &inputs[i]);
}
printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for (i = 10; i >= 0; i--)
{
result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);
printf ("\nf(%lf) = ");
if (result > check)
{
printf ("Overflow!");
}
else
{
printf ("%lf", result);
}
}
return 0;
}
| <?php
function f($n)
{
return sqrt(abs($n)) + 5 * $n * $n * $n;
}
$sArray = [];
echo "Enter 11 numbers.\n";
for ($i = 0; $i <= 10; $i++) {
echo $i + 1, " - Enter number: ";
array_push($sArray, (float)fgets(STDIN));
}
echo PHP_EOL;
$sArray = array_reverse($sArray);
foreach ($sArray as $s) {
$r = f($s);
echo "f(", $s, ") = ";
if ($r > 400)
echo "overflow\n";
else
echo $r, PHP_EOL;
}
?>
|
Rewrite the snippet below in PHP so it works the same as the original C code. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * mid3(int n)
{
static char buf[32];
int l;
sprintf(buf, "%d", n > 0 ? n : -n);
l = strlen(buf);
if (l < 3 || !(l & 1)) return 0;
l = l / 2 - 1;
buf[l + 3] = 0;
return buf + l;
}
int main(void)
{
int x[] = {123, 12345, 1234567, 987654321, 10001, -10001,
-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,
1234567890};
int i;
char *m;
for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {
if (!(m = mid3(x[i])))
m = "error";
printf("%d: %s\n", x[i], m);
}
return 0;
}
|
function middlethree($integer)
{
$int = (int)str_replace('-','',$integer);
$length = strlen($int);
if(is_int($int))
{
if($length >= 3)
{
if($length % 2 == 1)
{
$middle = floor($length / 2) - 1;
return substr($int,$middle, 3);
}
else
{
return 'The value must contain an odd amount of digits...';
}
}
else
{
return 'The value must contain at least three digits...';
}
}
else
{
return 'The value does not appear to be an integer...';
}
}
$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);
foreach($numbers as $nums)
{
echo $nums.' : '.middlethree($nums). '<br>';
}
|
Produce a language-to-language conversion: from C to PHP, same semantics. | #include <stdio.h>
#include <ctype.h>
static int
owp(int odd)
{
int ch, ret;
ch = getc(stdin);
if (!odd) {
putc(ch, stdout);
if (ch == EOF || ch == '.')
return EOF;
if (ispunct(ch))
return 0;
owp(odd);
return 0;
} else {
if (ispunct(ch))
return ch;
ret = owp(odd);
putc(ch, stdout);
return ret;
}
}
int
main(int argc, char **argv)
{
int ch = 1;
while ((ch = owp(!ch)) != EOF) {
if (ch)
putc(ch, stdout);
if (ch == '.')
break;
}
return 0;
}
| $odd = function ($prev) use ( &$odd ) {
$a = fgetc(STDIN);
if (!ctype_alpha($a)) {
$prev();
fwrite(STDOUT, $a);
return $a != '.';
}
$clos = function () use ($a , $prev) {
fwrite(STDOUT, $a);
$prev();
};
return $odd($clos);
};
$even = function () {
while (true) {
$c = fgetc(STDIN);
fwrite(STDOUT, $c);
if (!ctype_alpha($c)) {
return $c != ".";
}
}
};
$prev = function(){};
$e = false;
while ($e ? $odd($prev) : $even()) {
$e = !$e;
}
|
Preserve the algorithm and functionality while converting the code from C to PHP. | #include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
const char *code =
"CREATE TABLE address (\n"
" addrID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
" addrStreet TEXT NOT NULL,\n"
" addrCity TEXT NOT NULL,\n"
" addrState TEXT NOT NULL,\n"
" addrZIP TEXT NOT NULL)\n" ;
int main()
{
sqlite3 *db = NULL;
char *errmsg;
if ( sqlite3_open("address.db", &db) == SQLITE_OK ) {
if ( sqlite3_exec(db, code, NULL, NULL, &errmsg) != SQLITE_OK ) {
fprintf(stderr, errmsg);
sqlite3_free(errmsg);
sqlite3_close(db);
exit(EXIT_FAILURE);
}
sqlite3_close(db);
} else {
fprintf(stderr, "cannot open db...\n");
sqlite3_close(db);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
| <?php
$db = new SQLite3(':memory:');
$db->exec("
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL
)
");
?>
|
Keep all operations the same but rewrite the snippet in PHP. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
static char code[128] = { 0 };
void add_code(const char *s, int c)
{
while (*s) {
code[(int)*s] = code[0x20 ^ (int)*s] = c;
s++;
}
}
void init()
{
static const char *cls[] =
{ "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", 0};
int i;
for (i = 0; cls[i]; i++)
add_code(cls[i], i - 1);
}
const char* soundex(const char *s)
{
static char out[5];
int c, prev, i;
out[0] = out[4] = 0;
if (!s || !*s) return out;
out[0] = *s++;
prev = code[(int)out[0]];
for (i = 1; *s && i < 4; s++) {
if ((c = code[(int)*s]) == prev) continue;
if (c == -1) prev = 0;
else if (c > 0) {
out[i++] = c + '0';
prev = c;
}
}
while (i < 4) out[i++] = '0';
return out;
}
int main()
{
int i;
const char *sdx, *names[][2] = {
{"Soundex", "S532"},
{"Example", "E251"},
{"Sownteks", "S532"},
{"Ekzampul", "E251"},
{"Euler", "E460"},
{"Gauss", "G200"},
{"Hilbert", "H416"},
{"Knuth", "K530"},
{"Lloyd", "L300"},
{"Lukasiewicz", "L222"},
{"Ellery", "E460"},
{"Ghosh", "G200"},
{"Heilbronn", "H416"},
{"Kant", "K530"},
{"Ladd", "L300"},
{"Lissajous", "L222"},
{"Wheaton", "W350"},
{"Burroughs", "B620"},
{"Burrows", "B620"},
{"O'Hara", "O600"},
{"Washington", "W252"},
{"Lee", "L000"},
{"Gutierrez", "G362"},
{"Pfister", "P236"},
{"Jackson", "J250"},
{"Tymczak", "T522"},
{"VanDeusen", "V532"},
{"Ashcraft", "A261"},
{0, 0}
};
init();
puts(" Test name Code Got\n----------------------");
for (i = 0; names[i][0]; i++) {
sdx = soundex(names[i][0]);
printf("%11s %s %s ", names[i][0], names[i][1], sdx);
printf("%s\n", strcmp(sdx, names[i][1]) ? "not ok" : "ok");
}
return 0;
}
| <?php
echo soundex("Soundex"), "\n"; // S532
echo soundex("Example"), "\n"; // E251
echo soundex("Sownteks"), "\n"; // S532
echo soundex("Ekzampul"), "\n"; // E251
?>
|
Produce a language-to-language conversion: from C to PHP, same semantics. | typedef unsigned int histogram_t;
typedef histogram_t *histogram;
#define GET_LUM(IMG, X, Y) ( (IMG)->buf[ (Y) * (IMG)->width + (X)][0] )
histogram get_histogram(grayimage im);
luminance histogram_median(histogram h);
| define('src_name', 'input.jpg'); // source image
define('dest_name', 'output.jpg'); // destination image
$img = imagecreatefromjpeg(src_name); // read image
if(empty($img)){
echo 'Image could not be loaded!';
exit;
}
$black = imagecolorallocate($img, 0, 0, 0);
$white = imagecolorallocate($img, 255, 255, 255);
$width = imagesx($img);
$height = imagesy($img);
$array_lum = array(); // for storage of luminosity of each pixel
$sum_lum = 0; // total sum of luminosity
$average_lum = 0; // average luminosity of whole image
for($x = 0; $x < $width; $x++){
for($y = 0; $y < $height; $y++){
$color = imagecolorat($img, $x, $y);
$r = ($color >> 16) & 0xFF;
$g = ($color >> 8) & 0xFF;
$b = $color & 0xFF;
$array_lum[$x][$y] = ($r + $g + $b);
$sum_lum += $array_lum[$x][$y];
}
}
$average_lum = $sum_lum / ($width * $height);
for($x = 0; $x < $width; $x++){
for($y = 0; $y < $height; $y++){
if($array_lum[$x][$y] > $average_lum){
imagesetpixel($img, $x, $y, $white);
}
else{
imagesetpixel($img, $x, $y, $black);
}
}
}
imagejpeg($img, dest_name);
if(!file_exists(dest_name)){
echo 'Image not saved! Check permission!';
}
|
Write the same code in PHP as shown below in C. | char ch = 'z';
| 'c'; # character
'hello'; # these two strings are the same
"hello";
'Hi $name. How are you?'; # result: "Hi $name. How are you?"
"Hi $name. How are you?"; # result: "Hi Bob. How are you?"
'\n'; # 2-character string with a backslash and "n"
"\n"; # newline character
`ls`; # runs a command in the shell and returns the output as a string
<<END # Here-Document
Hi, whatever goes here gets put into the string,
including newlines and $variables,
until the label we put above
END;
<<'END' # Here-Document like single-quoted
Same as above, but no interpolation of $variables.
END;
|
Port the following code from C to PHP with equivalent syntax and logic. | enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 };
|
$fruits = array( "apple", "banana", "cherry" );
$fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 );
class Fruit {
const APPLE = 0;
const BANANA = 1;
const CHERRY = 2;
}
$value = Fruit::APPLE;
define("FRUIT_APPLE", 0);
define("FRUIT_BANANA", 1);
define("FRUIT_CHERRY", 2);
|
Convert this C block to PHP, preserving its control flow and logic. | #include <curl/curl.h>
#include <string.h>
#include <stdio.h>
size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fwrite(ptr,size,nmeb,stream);
}
size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){
return fread(ptr,size,nmeb,stream);
}
void callSOAP(char* URL, char * inFile, char * outFile) {
FILE * rfp = fopen(inFile, "r");
if(!rfp)
perror("Read File Open:");
FILE * wfp = fopen(outFile, "w+");
if(!wfp)
perror("Write File Open:");
struct curl_slist *header = NULL;
header = curl_slist_append (header, "Content-Type:text/xml");
header = curl_slist_append (header, "SOAPAction: rsc");
header = curl_slist_append (header, "Transfer-Encoding: chunked");
header = curl_slist_append (header, "Expect:");
CURL *curl;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);
curl_easy_setopt(curl, CURLOPT_READDATA, rfp);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);
curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
}
int main(int argC,char* argV[])
{
if(argC!=4)
printf("Usage : %s <URL of WSDL> <Input file path> <Output File Path>",argV[0]);
else
callSOAP(argV[1],argV[2],argV[3]);
return 0;
}
| <?php
$client = new SoapClient("http://example.com/soap/definition.wsdl");
$result = $client->soapFunc("hello");
$result = $client->anotherSoapFunc(34234);
$client = new SoapClient("http://example.com/soap/definition.wsdl");
print_r($client->__getTypes());
print_r($client->__getFunctions());
?>
|
Convert this C snippet to PHP and keep its semantics consistent. | #include <stdio.h>
int main(){
int ptr=0, i=0, cell[7];
for( i=0; i<7; ++i) cell[i]=0;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 8;
while(cell[ptr])
{
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 9;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 2;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
cell[ptr]+= 1;
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 4;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 7;
putchar(cell[ptr]);
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 7;
putchar(cell[ptr]);
ptr-= 3;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 15;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
cell[ptr]-= 6;
putchar(cell[ptr]);
cell[ptr]-= 8;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
putchar(cell[ptr]);
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 4;
putchar(cell[ptr]);
return 0;
}
| <?php
function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {
do {
switch($s[$_s]) {
case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;
case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;
case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;
case '<': $_d--; break;
case '.': $o .= $d[$_d]; break;
case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;
case '[':
if((int)ord($d[$_d]) == 0) {
$brackets = 1;
while($brackets && $_s++ < strlen($s)) {
if($s[$_s] == '[')
$brackets++;
else if($s[$_s] == ']')
$brackets--;
}
}
else {
$pos = $_s++-1;
if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))
$_s = $pos;
}
break;
case ']': return ((int)ord($d[$_d]) != 0);
}
} while(++$_s < strlen($s));
}
function brainfuck($source, $input='') {
$data = array();
$data[0] = chr(0);
$data_index = 0;
$source_index = 0;
$input_index = 0;
$output = '';
brainfuck_interpret($source, $source_index,
$data, $data_index,
$input, $input_index,
$output);
return $output;
}
$code = "
>++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>
>+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.
";
$inp = '123';
print brainfuck( $code, $inp );
|
Write the same code in PHP as shown below in C. | #include <stdio.h>
int main(){
int ptr=0, i=0, cell[7];
for( i=0; i<7; ++i) cell[i]=0;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 8;
while(cell[ptr])
{
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 9;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 2;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
cell[ptr]+= 1;
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
while(cell[ptr])
{
cell[ptr]-= 1;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 4;
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 2;
if(ptr<0) perror("Program pointer underflow");
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 7;
putchar(cell[ptr]);
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 7;
putchar(cell[ptr]);
ptr-= 3;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
while(cell[ptr])
{
cell[ptr]-= 1;
}
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
}
ptr-= 1;
if(ptr<0) perror("Program pointer underflow");
cell[ptr]+= 15;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
putchar(cell[ptr]);
cell[ptr]+= 3;
putchar(cell[ptr]);
cell[ptr]-= 6;
putchar(cell[ptr]);
cell[ptr]-= 8;
putchar(cell[ptr]);
ptr+= 2;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 1;
putchar(cell[ptr]);
ptr+= 1;
if(ptr>=7) perror("Program pointer overflow");
cell[ptr]+= 4;
putchar(cell[ptr]);
return 0;
}
| <?php
function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) {
do {
switch($s[$_s]) {
case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break;
case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break;
case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break;
case '<': $_d--; break;
case '.': $o .= $d[$_d]; break;
case ',': $d[$_d] = $_i==strlen($i) ? chr(0) : $i[$_i++]; break;
case '[':
if((int)ord($d[$_d]) == 0) {
$brackets = 1;
while($brackets && $_s++ < strlen($s)) {
if($s[$_s] == '[')
$brackets++;
else if($s[$_s] == ']')
$brackets--;
}
}
else {
$pos = $_s++-1;
if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o))
$_s = $pos;
}
break;
case ']': return ((int)ord($d[$_d]) != 0);
}
} while(++$_s < strlen($s));
}
function brainfuck($source, $input='') {
$data = array();
$data[0] = chr(0);
$data_index = 0;
$source_index = 0;
$input_index = 0;
$output = '';
brainfuck_interpret($source, $source_index,
$data, $data_index,
$input, $input_index,
$output);
return $output;
}
$code = "
>++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.>
>+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.
";
$inp = '123';
print brainfuck( $code, $inp );
|
Translate this program into PHP but keep the logic exactly as in C. | int meaning_of_life();
| <?php
function meaning_of_life() {
return 42;
}
function main($args) {
echo "Main: The meaning of life is " . meaning_of_life() . "\n";
}
if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) {
main($argv);
}
?>
|
Translate this program into PHP but keep the logic exactly as in C. | int meaning_of_life();
| <?php
function meaning_of_life() {
return 42;
}
function main($args) {
echo "Main: The meaning of life is " . meaning_of_life() . "\n";
}
if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) {
main($argv);
}
?>
|
Write the same algorithm in PHP as shown in this C implementation. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
int cmpstr(const void *a, const void *b)
{
return strcmp(*(const char**)a, *(const char**)b);
}
int main(void)
{
DIR *basedir;
char path[PATH_MAX];
struct dirent *entry;
char **dirnames;
int diralloc = 128;
int dirsize = 0;
if (!(dirnames = malloc(diralloc * sizeof(char*)))) {
perror("malloc error:");
return 1;
}
if (!getcwd(path, PATH_MAX)) {
perror("getcwd error:");
return 1;
}
if (!(basedir = opendir(path))) {
perror("opendir error:");
return 1;
}
while ((entry = readdir(basedir))) {
if (dirsize >= diralloc) {
diralloc *= 2;
if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {
perror("realloc error:");
return 1;
}
}
dirnames[dirsize++] = strdup(entry->d_name);
}
qsort(dirnames, dirsize, sizeof(char*), cmpstr);
int i;
for (i = 0; i < dirsize; ++i) {
if (dirnames[i][0] != '.') {
printf("%s\n", dirnames[i]);
}
}
for (i = 0; i < dirsize; ++i)
free(dirnames[i]);
free(dirnames);
closedir(basedir);
return 0;
}
| <?php
foreach(scandir('.') as $fileName){
echo $fileName."\n";
}
|
Produce a language-to-language conversion: from C to PHP, same semantics. |
INT PUTCHAR(INT);
INT WIDTH = 80, YEAR = 1969;
INT COLS, LEAD, GAP;
CONST CHAR *WDAYS[] = { "SU", "MO", "TU", "WE", "TH", "FR", "SA" };
STRUCT MONTHS {
CONST CHAR *NAME;
INT DAYS, START_WDAY, AT;
} MONTHS[12] = {
{ "JANUARY", 31, 0, 0 },
{ "FEBRUARY", 28, 0, 0 },
{ "MARCH", 31, 0, 0 },
{ "APRIL", 30, 0, 0 },
{ "MAY", 31, 0, 0 },
{ "JUNE", 30, 0, 0 },
{ "JULY", 31, 0, 0 },
{ "AUGUST", 31, 0, 0 },
{ "SEPTEMBER", 30, 0, 0 },
{ "OCTOBER", 31, 0, 0 },
{ "NOVEMBER", 30, 0, 0 },
{ "DECEMBER", 31, 0, 0 }
};
VOID SPACE(INT N) { WHILE (N-- > 0) PUTCHAR(' '); }
VOID PRINT(CONST CHAR * S){ WHILE (*S != '\0') { PUTCHAR(*S++); } }
INT STRLEN(CONST CHAR * S)
{
INT L = 0;
WHILE (*S++ != '\0') { L ++; };
RETURN L;
}
INT ATOI(CONST CHAR * S)
{
INT I = 0;
INT SIGN = 1;
CHAR C;
WHILE ((C = *S++) != '\0') {
IF (C == '-')
SIGN *= -1;
ELSE {
I *= 10;
I += (C - '0');
}
}
RETURN I * SIGN;
}
VOID INIT_MONTHS(VOID)
{
INT I;
IF ((!(YEAR % 4) && (YEAR % 100)) || !(YEAR % 400))
MONTHS[1].DAYS = 29;
YEAR--;
MONTHS[0].START_WDAY
= (YEAR * 365 + YEAR/4 - YEAR/100 + YEAR/400 + 1) % 7;
FOR (I = 1; I < 12; I++)
MONTHS[I].START_WDAY =
(MONTHS[I-1].START_WDAY + MONTHS[I-1].DAYS) % 7;
COLS = (WIDTH + 2) / 22;
WHILE (12 % COLS) COLS--;
GAP = COLS - 1 ? (WIDTH - 20 * COLS) / (COLS - 1) : 0;
IF (GAP > 4) GAP = 4;
LEAD = (WIDTH - (20 + GAP) * COLS + GAP + 1) / 2;
YEAR++;
}
VOID PRINT_ROW(INT ROW)
{
INT C, I, FROM = ROW * COLS, TO = FROM + COLS;
SPACE(LEAD);
FOR (C = FROM; C < TO; C++) {
I = STRLEN(MONTHS[C].NAME);
SPACE((20 - I)/2);
PRINT(MONTHS[C].NAME);
SPACE(20 - I - (20 - I)/2 + ((C == TO - 1) ? 0 : GAP));
}
PUTCHAR('\012');
SPACE(LEAD);
FOR (C = FROM; C < TO; C++) {
FOR (I = 0; I < 7; I++) {
PRINT(WDAYS[I]);
PRINT(I == 6 ? "" : " ");
}
IF (C < TO - 1) SPACE(GAP);
ELSE PUTCHAR('\012');
}
WHILE (1) {
FOR (C = FROM; C < TO; C++)
IF (MONTHS[C].AT < MONTHS[C].DAYS) BREAK;
IF (C == TO) BREAK;
SPACE(LEAD);
FOR (C = FROM; C < TO; C++) {
FOR (I = 0; I < MONTHS[C].START_WDAY; I++) SPACE(3);
WHILE(I++ < 7 && MONTHS[C].AT < MONTHS[C].DAYS) {
INT MM = ++MONTHS[C].AT;
PUTCHAR((MM < 10) ? ' ' : '0' + (MM /10));
PUTCHAR('0' + (MM %10));
IF (I < 7 || C < TO - 1) PUTCHAR(' ');
}
WHILE (I++ <= 7 && C < TO - 1) SPACE(3);
IF (C < TO - 1) SPACE(GAP - 1);
MONTHS[C].START_WDAY = 0;
}
PUTCHAR('\012');
}
PUTCHAR('\012');
}
VOID PRINT_YEAR(VOID)
{
INT Y = YEAR;
INT ROW;
CHAR BUF[32];
CHAR * B = &(BUF[31]);
*B-- = '\0';
DO {
*B-- = '0' + (Y % 10);
Y /= 10;
} WHILE (Y > 0);
B++;
SPACE((WIDTH - STRLEN(B)) / 2);
PRINT(B);PUTCHAR('\012');PUTCHAR('\012');
FOR (ROW = 0; ROW * COLS < 12; ROW++)
PRINT_ROW(ROW);
}
INT MAIN(INT C, CHAR **V)
{
INT I, YEAR_SET = 0, RESULT = 0;
FOR (I = 1; I < C && RESULT == 0; I++) {
IF (V[I][0] == '-' && V[I][1] == 'W' && V[I][2] == '\0') {
IF (++I == C || (WIDTH = ATOI(V[I])) < 20)
RESULT = 1;
} ELSE IF (!YEAR_SET) {
YEAR = ATOI(V[I]);
IF (YEAR <= 0)
YEAR = 1969;
YEAR_SET = 1;
} ELSE
RESULT = 1;
}
IF (RESULT == 0) {
INIT_MONTHS();
PRINT_YEAR();
} ELSE {
PRINT("BAD ARGS\012USAGE: ");
PRINT(V[0]);
PRINT(" YEAR [-W WIDTH (>= 20)]\012");
}
RETURN RESULT;
}
| <?PHP
ECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT
JANUARY FEBRUARY MARCH APRIL MAY JUNE
MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO
1 2 3 4 5 1 2 1 2 1 2 3 4 5 6 1 2 3 4 1
6 7 8 9 10 11 12 3 4 5 6 7 8 9 3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8
13 14 15 16 17 18 19 10 11 12 13 14 15 16 10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15
20 21 22 23 24 25 26 17 18 19 20 21 22 23 17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22
27 28 29 30 31 24 25 26 27 28 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29
31 30
JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER
MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO
1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 1 2 1 2 3 4 5 6 7
7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14
14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21
21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28
28 29 30 31 25 26 27 28 29 30 31 29 30 27 28 29 30 31 24 25 26 27 28 29 30 29 30 31
REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT
; // MAGICAL SEMICOLON
|
Convert the following code from C to PHP, ensuring the logic remains intact. | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_SIZE 100
int move_to_front(char *str,char c)
{
char *q,*p;
int shift=0;
p=(char *)malloc(strlen(str)+1);
strcpy(p,str);
q=strchr(p,c);
shift=q-p;
strncpy(str+1,p,shift);
str[0]=c;
free(p);
return shift;
}
void decode(int* pass,int size,char *sym)
{
int i,index;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=table[pass[i]];
index=move_to_front(table,c);
if(pass[i]!=index) printf("there is an error");
sym[i]=c;
}
sym[size]='\0';
}
void encode(char *sym,int size,int *pass)
{
int i=0;
char c;
char table[]="abcdefghijklmnopqrstuvwxyz";
for(i=0;i<size;i++)
{
c=sym[i];
pass[i]=move_to_front(table,c);
}
}
int check(char *sym,int size,int *pass)
{
int *pass2=malloc(sizeof(int)*size);
char *sym2=malloc(sizeof(char)*size);
int i,val=1;
encode(sym,size,pass2);
i=0;
while(i<size && pass[i]==pass2[i])i++;
if(i!=size)val=0;
decode(pass,size,sym2);
if(strcmp(sym,sym2)!=0)val=0;
free(sym2);
free(pass2);
return val;
}
int main()
{
char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"};
int pass[MAX_SIZE]={0};
int i,len,j;
for(i=0;i<3;i++)
{
len=strlen(sym[i]);
encode(sym[i],len,pass);
printf("%s : [",sym[i]);
for(j=0;j<len;j++)
printf("%d ",pass[j]);
printf("]\n");
if(check(sym[i],len,pass))
printf("Correct :)\n");
else
printf("Incorrect :(\n");
}
return 0;
}
| <?php
function symbolTable() {
$symbol = array();
for ($c = ord('a') ; $c <= ord('z') ; $c++) {
$symbol[$c - ord('a')] = chr($c);
}
return $symbol;
}
function mtfEncode($original, $symbol) {
$encoded = array();
for ($i = 0 ; $i < strlen($original) ; $i++) {
$char = $original[$i];
$position = array_search($char, $symbol);
$encoded[] = $position;
$mtf = $symbol[$position];
unset($symbol[$position]);
array_unshift($symbol, $mtf);
}
return $encoded;
}
function mtfDecode($encoded, $symbol) {
$decoded = '';
foreach ($encoded AS $position) {
$char = $symbol[$position];
$decoded .= $char;
unset($symbol[$position]);
array_unshift($symbol, $char);
}
return $decoded;
}
foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {
$encoded = mtfEncode($original, symbolTable());
$decoded = mtfDecode($encoded, symbolTable());
echo
$original,
' -> [', implode(',', $encoded), ']',
' -> ', $decoded,
' : ', ($original === $decoded ? 'OK' : 'Error'),
PHP_EOL;
}
|
Ensure the translated PHP code behaves exactly like the original C snippet. | #include <ldap.h>
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
LDAPMessage **result;
ldap_search_s(ld, "dc=somewhere,dc=com", LDAP_SCOPE_SUBTREE,
"(&(objectclass=person)(|(cn=joe*)(cn=shmoe*)))",
NULL,
0,
result);
ldap_msgfree(*result);
ldap_unbind(ld);
| <?php
$l = ldap_connect('ldap.example.com');
ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($l, LDAP_OPT_REFERRALS, false);
$bind = ldap_bind($l, 'me@example.com', 'password');
$base = 'dc=example, dc=com';
$criteria = '(&(objectClass=user)(sAMAccountName=username))';
$attributes = array('displayName', 'company');
$search = ldap_search($l, $base, $criteria, $attributes);
$entries = ldap_get_entries($l, $search);
var_dump($entries);
|
Preserve the algorithm and functionality while converting the code from C to PHP. | #include <stdlib.h>
int main()
{
system("ls");
return 0;
}
| @exec($command,$output);
echo nl2br($output);
|
Write a version of this C function in PHP with identical behavior. | #include <libxml/xmlschemastypes.h>
int main(int argC, char** argV)
{
if (argC <= 2) {
printf("Usage: %s <XML Document Name> <XSD Document Name>\n", argV[0]);
return 0;
}
xmlDocPtr doc;
xmlSchemaPtr schema = NULL;
xmlSchemaParserCtxtPtr ctxt;
char *XMLFileName = argV[1];
char *XSDFileName = argV[2];
int ret;
xmlLineNumbersDefault(1);
ctxt = xmlSchemaNewParserCtxt(XSDFileName);
xmlSchemaSetParserErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
schema = xmlSchemaParse(ctxt);
xmlSchemaFreeParserCtxt(ctxt);
doc = xmlReadFile(XMLFileName, NULL, 0);
if (doc == NULL){
fprintf(stderr, "Could not parse %s\n", XMLFileName);
}
else{
xmlSchemaValidCtxtPtr ctxt;
ctxt = xmlSchemaNewValidCtxt(schema);
xmlSchemaSetValidErrors(ctxt, (xmlSchemaValidityErrorFunc) fprintf, (xmlSchemaValidityWarningFunc) fprintf, stderr);
ret = xmlSchemaValidateDoc(ctxt, doc);
if (ret == 0){
printf("%s validates\n", XMLFileName);
}
else if (ret > 0){
printf("%s fails to validate\n", XMLFileName);
}
else{
printf("%s validation generated an internal error\n", XMLFileName);
}
xmlSchemaFreeValidCtxt(ctxt);
xmlFreeDoc(doc);
}
if(schema != NULL)
xmlSchemaFree(schema);
xmlSchemaCleanupTypes();
xmlCleanupParser();
xmlMemoryDump();
return 0;
}
| libxml_use_internal_errors(true);
$xml = new DOMDocument();
$xml->load('shiporder.xml');
if (!$xml->schemaValidate('shiporder.xsd')) {
var_dump(libxml_get_errors()); exit;
} else {
echo 'success';
}
|
Port the provided C code into PHP while preserving the original functionality. | #include <stdio.h>
#include <stdlib.h>
struct node {
int val, len;
struct node *next;
};
void lis(int *v, int len)
{
int i;
struct node *p, *n = calloc(len, sizeof *n);
for (i = 0; i < len; i++)
n[i].val = v[i];
for (i = len; i--; ) {
for (p = n + i; p++ < n + len; ) {
if (p->val > n[i].val && p->len >= n[i].len) {
n[i].next = p;
n[i].len = p->len + 1;
}
}
}
for (i = 0, p = n; i < len; i++)
if (n[i].len > p->len) p = n + i;
do printf(" %d", p->val); while ((p = p->next));
putchar('\n');
free(n);
}
int main(void)
{
int x[] = { 3, 2, 6, 4, 5, 1 };
int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 };
lis(x, sizeof(x) / sizeof(int));
lis(y, sizeof(y) / sizeof(int));
return 0;
}
| <?php
class Node {
public $val;
public $back = NULL;
}
function lis($n) {
$pileTops = array();
foreach ($n as $x) {
$low = 0; $high = count($pileTops)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($pileTops[$mid]->val >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
$node = new Node();
$node->val = $x;
if ($i != 0)
$node->back = $pileTops[$i-1];
$pileTops[$i] = $node;
}
$result = array();
for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;
$node != NULL; $node = $node->back)
$result[] = $node->val;
return array_reverse($result);
}
print_r(lis(array(3, 2, 6, 4, 5, 1)));
print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));
?>
|
Ensure the translated PHP code behaves exactly like the original C snippet. | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 128
typedef unsigned char character;
typedef character *string;
typedef struct node_t node;
struct node_t {
enum tag_t {
NODE_LEAF,
NODE_TREE,
NODE_SEQ,
} tag;
union {
string str;
node *root;
} data;
node *next;
};
node *allocate_node(enum tag_t tag) {
node *n = malloc(sizeof(node));
if (n == NULL) {
fprintf(stderr, "Failed to allocate node for tag: %d\n", tag);
exit(1);
}
n->tag = tag;
n->next = NULL;
return n;
}
node *make_leaf(string str) {
node *n = allocate_node(NODE_LEAF);
n->data.str = str;
return n;
}
node *make_tree() {
node *n = allocate_node(NODE_TREE);
n->data.root = NULL;
return n;
}
node *make_seq() {
node *n = allocate_node(NODE_SEQ);
n->data.root = NULL;
return n;
}
void deallocate_node(node *n) {
if (n == NULL) {
return;
}
deallocate_node(n->next);
n->next = NULL;
if (n->tag == NODE_LEAF) {
free(n->data.str);
n->data.str = NULL;
} else if (n->tag == NODE_TREE || n->tag == NODE_SEQ) {
deallocate_node(n->data.root);
n->data.root = NULL;
} else {
fprintf(stderr, "Cannot deallocate node with tag: %d\n", n->tag);
exit(1);
}
free(n);
}
void append(node *root, node *elem) {
if (root == NULL) {
fprintf(stderr, "Cannot append to uninitialized node.");
exit(1);
}
if (elem == NULL) {
return;
}
if (root->tag == NODE_SEQ || root->tag == NODE_TREE) {
if (root->data.root == NULL) {
root->data.root = elem;
} else {
node *it = root->data.root;
while (it->next != NULL) {
it = it->next;
}
it->next = elem;
}
} else {
fprintf(stderr, "Cannot append to node with tag: %d\n", root->tag);
exit(1);
}
}
size_t count(node *n) {
if (n == NULL) {
return 0;
}
if (n->tag == NODE_LEAF) {
return 1;
}
if (n->tag == NODE_TREE) {
size_t sum = 0;
node *it = n->data.root;
while (it != NULL) {
sum += count(it);
it = it->next;
}
return sum;
}
if (n->tag == NODE_SEQ) {
size_t prod = 1;
node *it = n->data.root;
while (it != NULL) {
prod *= count(it);
it = it->next;
}
return prod;
}
fprintf(stderr, "Cannot count node with tag: %d\n", n->tag);
exit(1);
}
void expand(node *n, size_t pos) {
if (n == NULL) {
return;
}
if (n->tag == NODE_LEAF) {
printf(n->data.str);
} else if (n->tag == NODE_TREE) {
node *it = n->data.root;
while (true) {
size_t cnt = count(it);
if (pos < cnt) {
expand(it, pos);
break;
}
pos -= cnt;
it = it->next;
}
} else if (n->tag == NODE_SEQ) {
size_t prod = pos;
node *it = n->data.root;
while (it != NULL) {
size_t cnt = count(it);
size_t rem = prod % cnt;
expand(it, rem);
it = it->next;
}
} else {
fprintf(stderr, "Cannot expand node with tag: %d\n", n->tag);
exit(1);
}
}
string allocate_string(string src) {
size_t len = strlen(src);
string out = calloc(len + 1, sizeof(character));
if (out == NULL) {
fprintf(stderr, "Failed to allocate a copy of the string.");
exit(1);
}
strcpy(out, src);
return out;
}
node *parse_seq(string input, size_t *pos);
node *parse_tree(string input, size_t *pos) {
node *root = make_tree();
character buffer[BUFFER_SIZE] = { 0 };
size_t bufpos = 0;
size_t depth = 0;
bool asSeq = false;
bool allow = false;
while (input[*pos] != 0) {
character c = input[(*pos)++];
if (c == '\\') {
c = input[(*pos)++];
if (c == 0) {
break;
}
buffer[bufpos++] = '\\';
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else if (c == '{') {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
asSeq = true;
depth++;
} else if (c == '}') {
if (depth-- > 0) {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else {
if (asSeq) {
size_t new_pos = 0;
node *seq = parse_seq(buffer, &new_pos);
append(root, seq);
} else {
append(root, make_leaf(allocate_string(buffer)));
}
break;
}
} else if (c == ',') {
if (depth == 0) {
if (asSeq) {
size_t new_pos = 0;
node *seq = parse_seq(buffer, &new_pos);
append(root, seq);
bufpos = 0;
buffer[bufpos] = 0;
asSeq = false;
} else {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
}
return root;
}
node *parse_seq(string input, size_t *pos) {
node *root = make_seq();
character buffer[BUFFER_SIZE] = { 0 };
size_t bufpos = 0;
while (input[*pos] != 0) {
character c = input[(*pos)++];
if (c == '\\') {
c = input[(*pos)++];
if (c == 0) {
break;
}
buffer[bufpos++] = c;
buffer[bufpos] = 0;
} else if (c == '{') {
node *tree = parse_tree(input, pos);
if (bufpos > 0) {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
append(root, tree);
} else {
buffer[bufpos++] = c;
buffer[bufpos] = 0;
}
}
if (bufpos > 0) {
append(root, make_leaf(allocate_string(buffer)));
bufpos = 0;
buffer[bufpos] = 0;
}
return root;
}
void test(string input) {
size_t pos = 0;
node *n = parse_seq(input, &pos);
size_t cnt = count(n);
size_t i;
printf("Pattern: %s\n", input);
for (i = 0; i < cnt; i++) {
expand(n, i);
printf("\n");
}
printf("\n");
deallocate_node(n);
}
int main() {
test("~/{Downloads,Pictures}/*.{jpg,gif,png}");
test("It{{em,alic}iz,erat}e{d,}, please.");
test("{,{,gotta have{ ,\\, again\\, }}more }cowbell!");
return 0;
}
| function getitem($s,$depth=0) {
$out = [''];
while ($s) {
$c = $s[0];
if ($depth && ($c == ',' || $c == '}')) {
return [$out, $s];
}
if ($c == '{') {
$x = getgroup(substr($s, 1), $depth + 1);
if($x) {
$tmp = [];
foreach($out as $a) {
foreach($x[0] as $b) {
$tmp[] = $a . $b;
}
}
$out = $tmp;
$s = $x[1];
continue;
}
}
if ($c == '\\' && strlen($s) > 1) {
list($s, $c) = [substr($s, 1), ($c . $s[1])];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = $a . $c;
}
$out = $tmp;
$s = substr($s, 1);
}
return [$out, $s];
}
function getgroup($s,$depth) {
list($out, $comma) = [[], false];
while ($s) {
list($g, $s) = getitem($s, $depth);
if (!$s) {
break;
}
$out = array_merge($out, $g);
if ($s[0] == '}') {
if ($comma) {
return [$out, substr($s, 1)];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = '{' . $a . '}';
}
return [$tmp, substr($s, 1)];
}
if ($s[0] == ',') {
list($comma, $s) = [true, substr($s, 1)];
}
}
return null;
}
$lines = <<< 'END'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
END;
foreach( explode("\n", $lines) as $line ) {
printf("\n%s\n", $line);
foreach( getitem($line)[0] as $expansion ) {
printf(" %s\n", $expansion);
}
}
|
Produce a functionally identical PHP code for the snippet given in C. | #include <stdio.h>
inline int self_desc(unsigned long long xx)
{
register unsigned int d, x;
unsigned char cnt[10] = {0}, dig[10] = {0};
for (d = 0; xx > ~0U; xx /= 10)
cnt[ dig[d++] = xx % 10 ]++;
for (x = xx; x; x /= 10)
cnt[ dig[d++] = x % 10 ]++;
while(d-- && dig[x++] == cnt[d]);
return d == -1;
}
int main()
{
int i;
for (i = 1; i < 100000000; i++)
if (self_desc(i)) printf("%d\n", i);
return 0;
}
| <?php
function is_describing($number) {
foreach (str_split((int) $number) as $place => $value) {
if (substr_count($number, $place) != $value) {
return false;
}
}
return true;
}
for ($i = 0; $i <= 50000000; $i += 10) {
if (is_describing($i)) {
echo $i . PHP_EOL;
}
}
?>
|
Port the provided C code into PHP while preserving the original functionality. | #include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int main(void) {
printf("%d\n", mul_inv(42, 2017));
return 0;
}
| <?php
function invmod($a,$n){
if ($n < 0) $n = -$n;
if ($a < 0) $a = $n - (-$a % $n);
$t = 0; $nt = 1; $r = $n; $nr = $a % $n;
while ($nr != 0) {
$quot= intval($r/$nr);
$tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp;
$tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp;
}
if ($r > 1) return -1;
if ($t < 0) $t += $n;
return $t;
}
printf("%d\n", invmod(42, 2017));
?>
|
Translate the given C code snippet into PHP without altering its behavior. | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>
char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>"
"<style>body { background-color: #111 }"
"h1 { font-size:4cm; text-align: center; color: black;"
" text-shadow: 0 0 2mm red}</style></head>"
"<body><h1>Goodbye, world!</h1></body></html>\r\n";
int main()
{
int one = 1, client_fd;
struct sockaddr_in svr_addr, cli_addr;
socklen_t sin_len = sizeof(cli_addr);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
err(1, "can't open socket");
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));
int port = 8080;
svr_addr.sin_family = AF_INET;
svr_addr.sin_addr.s_addr = INADDR_ANY;
svr_addr.sin_port = htons(port);
if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
close(sock);
err(1, "Can't bind");
}
listen(sock, 5);
while (1) {
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
printf("got connection\n");
if (client_fd == -1) {
perror("Can't accept");
continue;
}
write(client_fd, response, sizeof(response) - 1);
close(client_fd);
}
}
| <?php
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die('Failed to create socket!');
socket_bind($socket, 0, 8080);
socket_listen($socket);
$msg = '<html><head><title>Goodbye, world!</title></head><body>Goodbye, world!</body></html>';
for (;;) {
if ($client = @socket_accept($socket)) {
socket_write($client, "HTTP/1.1 200 OK\r\n" .
"Content-length: " . strlen($msg) . "\r\n" .
"Content-Type: text/html; charset=UTF-8\r\n\r\n" .
$msg);
}
else usleep(100000); // limits CPU usage by sleeping after doing every request
}
?>
|
Convert this C block to PHP, preserving its control flow and logic. | void cubic_bezier(
image img,
unsigned int x1, unsigned int y1,
unsigned int x2, unsigned int y2,
unsigned int x3, unsigned int y3,
unsigned int x4, unsigned int y4,
color_component r,
color_component g,
color_component b );
| <?
$image = imagecreate(200, 200);
imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 255, 0, 0);
cubicbezier($image, $color, 160, 10, 10, 40, 30, 160, 150, 110);
imagepng($image);
function cubicbezier($img, $col, $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3, $n = 20) {
$pts = array();
for($i = 0; $i <= $n; $i++) {
$t = $i / $n;
$t1 = 1 - $t;
$a = pow($t1, 3);
$b = 3 * $t * pow($t1, 2);
$c = 3 * pow($t, 2) * $t1;
$d = pow($t, 3);
$x = round($a * $x0 + $b * $x1 + $c * $x2 + $d * $x3);
$y = round($a * $y0 + $b * $y1 + $c * $y2 + $d * $y3);
$pts[$i] = array($x, $y);
}
for($i = 0; $i < $n; $i++) {
imageline($img, $pts[$i][0], $pts[$i][1], $pts[$i+1][0], $pts[$i+1][1], $col);
}
}
|
Translate the given C code snippet into PHP without altering its behavior. | #include <ldap.h>
...
char *name, *password;
...
LDAP *ld = ldap_init("ldap.somewhere.com", 389);
ldap_simple_bind_s(ld, name, password);
... after done with it...
ldap_unbind(ld);
| <?php
$ldap = ldap_connect($hostname, $port);
$success = ldap_bind($ldap, $username, $password);
|
Convert the following code from C to PHP, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define strcomp(X, Y) strcasecmp(X, Y)
struct option
{ const char *name, *value;
int flag; };
struct option updlist[] =
{ { "NEEDSPEELING", NULL },
{ "SEEDSREMOVED", "" },
{ "NUMBEROFBANANAS", "1024" },
{ "NUMBEROFSTRAWBERRIES", "62000" },
{ NULL, NULL } };
int output_opt(FILE *to, struct option *opt)
{ if (opt->value == NULL)
return fprintf(to, "; %s\n", opt->name);
else if (opt->value[0] == 0)
return fprintf(to, "%s\n", opt->name);
else
return fprintf(to, "%s %s\n", opt->name, opt->value); }
int update(FILE *from, FILE *to, struct option *updlist)
{ char line_buf[256], opt_name[128];
int i;
for (;;)
{ size_t len, space_span, span_to_hash;
if (fgets(line_buf, sizeof line_buf, from) == NULL)
break;
len = strlen(line_buf);
space_span = strspn(line_buf, "\t ");
span_to_hash = strcspn(line_buf, "#");
if (space_span == span_to_hash)
goto line_out;
if (space_span == len)
goto line_out;
if ((sscanf(line_buf, "; %127s", opt_name) == 1) ||
(sscanf(line_buf, "%127s", opt_name) == 1))
{ int flag = 0;
for (i = 0; updlist[i].name; i++)
{ if (strcomp(updlist[i].name, opt_name) == 0)
{ if (output_opt(to, &updlist[i]) < 0)
return -1;
updlist[i].flag = 1;
flag = 1; } }
if (flag == 0)
goto line_out; }
else
line_out:
if (fprintf(to, "%s", line_buf) < 0)
return -1;
continue; }
{ for (i = 0; updlist[i].name; i++)
{ if (!updlist[i].flag)
if (output_opt(to, &updlist[i]) < 0)
return -1; } }
return feof(from) ? 0 : -1; }
int main(void)
{ if (update(stdin, stdout, updlist) < 0)
{ fprintf(stderr, "failed\n");
return (EXIT_FAILURE); }
return 0; }
| <?php
$conf = file_get_contents('update-conf-file.txt');
$conf = preg_replace('/^(needspeeling)(|\s*\S*)$/mi', '; $1', $conf);
$conf = preg_replace('/^;?\s*(seedsremoved)/mi', '$1', $conf);
$conf = preg_replace('/^(numberofbananas)(|\s*\S*)$/mi', '$1 1024', $conf);
if (preg_match('/^;?\s*(numberofstrawberries)/mi', $conf, $matches)) {
$conf = preg_replace('/^(numberofstrawberries)(|\s*\S*)$/mi', '$1 62000', $conf);
} else {
$conf .= 'NUMBEROFSTRAWBERRIES 62000' . PHP_EOL;
}
echo $conf;
|
Port the provided C code into PHP while preserving the original functionality. | int j;
| <?php
# NULL typed variable
$null = NULL; var_dump($null); // output: null
# defining a boolean
$boolean = true; var_dump($boolean); // output: boolean true
$boolean = false; var_dump($boolean); // output: boolean false
# bool and boolean is the same
$boolean = (bool)1; var_dump($boolean); // output: boolean true
$boolean = (boolean)1; var_dump($boolean); // output: boolean true
$boolean = (bool)0; var_dump($boolean); // output: boolean false
$boolean = (boolean)0; var_dump($boolean); // output: boolean false
# defining an integer
$int = 0; var_dump($int); // output: int 0
# defining a float,
$float = 0.01; var_dump($float); // output: float 0.01
# which is also identical to "real" and "double"
var_dump((double)$float); // output: float 0.01
var_dump((real)$float); // output: float 0.01
# casting back to int (auto flooring the value)
var_dump((int)$float); // output: int 0
var_dump((int)($float+1)); // output: int 1
var_dump((int)($float+1.9)); // output: int 1
# defining a string
$string = 'string';
var_dump($string); // output: string 'string' (length=6)
# referencing a variable (there are no pointers in PHP).
$another_string = &$string;
var_dump($another_string);
$string = "I'm the same string!";
var_dump($another_string);
# "deleting" a variable from memory
unset($another_string);
$string = 'string';
$parsed_string = "This is a $string";
var_dump($parsed_string);
$parsed_string .= " with another {$string}";
var_dump($parsed_string);
# with string parsing
$heredoc = <<<HEREDOC
This is the content of \$string: {$string}
HEREDOC;
var_dump($heredoc);
# without string parsing (notice the single quotes surrounding NOWDOC)
$nowdoc = <<<'NOWDOC'
This is the content of \$string: {$string}
NOWDOC;
var_dump($nowdoc);
# as of PHP5, defining an object typed stdClass => standard class
$stdObject = new stdClass(); var_dump($stdObject);
# defining an object typed Foo
class Foo {}
$foo = new Foo(); var_dump($foo);
# defining an empty array
$array = array(); var_dump($array);
$assoc = array(
0 => $int,
'integer' => $int,
1 => $float,
'float' => $float,
2 => $string,
'string' => $string,
3 => NULL, // <=== key 3 is NULL
3, // <=== this is a value, not a key (key is 4)
5 => $stdObject,
'Foo' => $foo,
);
var_dump($assoc);
function a_function()
{
# not reachable
var_dump(isset($foo)); // output: boolean false
global $foo;
# "global" (reachable) inside a_function()'s scope
var_dump(isset($foo)); // output: boolean true
}
a_function();
|
Transform the following C implementation into PHP, maintaining the same output and logic. | #include <gadget/gadget.h>
LIB_GADGET_START
GD_VIDEO put_chemical_cell( GD_VIDEO table, MT_CELL * E, DS_ARRAY E_data );
MT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data );
int select_box_chemical_elem( RDS(MT_CELL, Elements) );
void put_information(RDS( MT_CELL, elem), int i);
Main
GD_VIDEO table;
Resize_terminal(42,135);
Init_video( &table );
Gpm_Connect conn;
if ( ! Init_mouse(&conn)){
Msg_red("No se puede conectar al servidor del ratón\n");
Stop(1);
}
Enable_raw_mode();
Hide_cursor;
New multitype Elements;
Elements = load_chem_elements( pSDS(Elements) );
Throw( load_fail );
New objects Btn_exit;
Btn_exit = New_object_mouse( SMD(&Btn_exit), BUTTOM, " Terminar ", 6,44, 15, 0);
table = put_chemical_cell( table, SDS(Elements) );
Refresh(table);
Put object Btn_exit;
int c;
Waiting_some_clic(c)
{
if( select_box_chemical_elem(SDS(Elements)) ){
Waiting_some_clic(c) break;
}
if (Object_mouse( Btn_exit)) break;
Refresh(table);
Put object Btn_exit;
}
Free object Btn_exit;
Free multitype Elements;
Exception( load_fail ){
Msg_red("No es un archivo matriciable");
}
Free video table;
Disable_raw_mode();
Close_mouse();
Show_cursor;
At SIZE_TERM_ROWS,0;
Prnl;
End
void put_information(RDS(MT_CELL, elem), int i)
{
At 2,19;
Box_solid(11,64,67,17);
Color(15,17);
At 4,22; Print "Elemento (%s) = %s", (char*)$s-elem[i,5],(char*)$s-elem[i,6];
if (Cell_type(elem,i,7) == double_TYPE ){
At 5,22; Print "Peso atómico = %f", $d-elem[i,7];
}else{
At 5,22; Print "Peso atómico = (%ld)", $l-elem[i,7];
}
At 6,22; Print "Posición = (%ld, %ld)",$l-elem[i,0]+ ($l-elem[i,0]>=8 ? 0:1),$l-elem[i,1]+1;
At 8,22; Print "1ª energía de";
if (Cell_type(elem,i,12) == double_TYPE ){
At 9,22; Print "ionización (kJ/mol) = %.*f",2,$d-elem[i,12];
}else{
At 9,22; Print "ionización (kJ/mol) = ---";
}
if (Cell_type(elem,i,13) == double_TYPE ){
At 10,22; Print "Electronegatividad = %.*f",2,$d-elem[i,13];
}else{
At 10,22; Print "Electronegatividad = ---";
}
At 4,56; Print "Conf. electrónica:";
At 5,56; Print " %s", (char*)$s-elem[i,14];
At 7,56; Print "Estados de oxidación:";
if ( Cell_type(elem,i,15) == string_TYPE ){
At 8,56; Print " %s", (char*)$s-elem[i,15];
}else{
At 8,56; Print " %ld", $l-elem[i,15];
}
At 10,56; Print "Número Atómico: %ld",$l-elem[i,4];
Reset_color;
}
int select_box_chemical_elem( RDS(MT_CELL, elem) )
{
int i;
Iterator up i [0:1:Rows(elem)]{
if ( Is_range_box( $l-elem[i,8], $l-elem[i,9], $l-elem[i,10], $l-elem[i,11]) ){
Gotoxy( $l-elem[i,8], $l-elem[i,9] );
Color_fore( 15 ); Color_back( 0 );
Box( 4,5, DOUB_ALL );
Gotoxy( $l-elem[i,8]+1, $l-elem[i,9]+2); Print "%ld",$l-elem[i,4];
Gotoxy( $l-elem[i,8]+2, $l-elem[i,9]+2); Print "%s",(char*)$s-elem[i,5];
Flush_out;
Reset_color;
put_information(SDS(elem),i);
return 1;
}
}
return 0;
}
GD_VIDEO put_chemical_cell(GD_VIDEO table, MT_CELL * elem, DS_ARRAY elem_data)
{
int i;
Iterator up i [0:1:Rows(elem)]{
long rx = 2+($l-elem[i,0]*4);
long cx = 3+($l-elem[i,1]*7);
long offr = rx+3;
long offc = cx+6;
Gotoxy(table, rx, cx);
Color_fore(table, $l-elem[i,2]);
Color_back(table,$l-elem[i,3]);
Box(table, 4,5, SING_ALL );
char Atnum[50], Elem[50];
sprintf(Atnum,"\x1b[3m%ld\x1b[23m",$l-elem[i,4]);
sprintf(Elem, "\x1b[1m%s\x1b[22m",(char*)$s-elem[i,5]);
Outvid(table,rx+1, cx+2, Atnum);
Outvid(table,rx+2, cx+2, Elem);
Reset_text(table);
$l-elem[i,8] = rx;
$l-elem[i,9] = cx;
$l-elem[i,10] = offr;
$l-elem[i,11] = offc;
}
Iterator up i [ 1: 1: 19 ]{
Gotoxy(table, 31, 5+(i-1)*7);
char num[5]; sprintf( num, "%d",i );
Outvid(table, num );
}
Iterator up i [ 1: 1: 8 ]{
Gotoxy(table, 3+(i-1)*4, 130);
char num[5]; sprintf( num, "%d",i );
Outvid(table, num );
}
Outvid( table, 35,116, "8");
Outvid( table, 39,116, "9");
Color_fore(table, 15);
Color_back(table, 0);
Outvid(table,35,2,"Lantánidos ->");
Outvid(table,39,2,"Actínidos ->");
Reset_text(table);
return table;
}
MT_CELL* load_chem_elements( MT_CELL * E, DS_ARRAY * E_data )
{
F_STAT dataFile = Stat_file("chem_table.txt");
if( dataFile.is_matrix ){
Range ptr E [0:1:dataFile.total_lines-1, 0:1:dataFile.max_tokens_per_line-1];
E = Load_matrix_mt( SDS(E), "chem_table.txt", dataFile, DET_LONG);
}else{
Is_ok=0;
}
return E;
}
| <?php
class PeriodicTable
{
private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);
private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);
public function rowAndColumn($n)
{
$i = 7;
while ($this->aArray[$i] > $n)
$i--;
$m = $n + $this->bArray[$i];
return array(floor($m / 18) + 1, $m % 18 + 1);
}
}
$pt = new PeriodicTable();
foreach ([1, 2, 29, 42, 57, 58, 72, 89, 90, 103] as $n) {
list($r, $c) = $pt->rowAndColumn($n);
echo $n, " -> ", $r, " ", $c, PHP_EOL;
}
?>
|
Keep all operations the same but rewrite the snippet in PHP. | #include <cmath>
bool is_prime(unsigned int n)
{
if (n <= 1)
return false;
if (n == 2)
return true;
for (unsigned int i = 2; i <= sqrt(n); ++i)
if (n % i == 0)
return false;
return true;
}
| <?php
function prime($a) {
if (($a % 2 == 0 && $a != 2) || $a < 2)
return false;
$limit = sqrt($a);
for ($i = 2; $i <= $limit; $i++)
if ($a % $i == 0)
return false;
return true;
}
foreach (range(1, 100) as $x)
if (prime($x)) echo "$x\n";
?>
|
Write the same code in PHP as shown below in C++. | double Factorial(double nValue)
{
double result = nValue;
double result_next;
double pc = nValue;
do
{
result_next = result*(pc-1);
result = result_next;
pc--;
}while(pc>2);
nValue = result;
return nValue;
}
double binomialCoefficient(double n, double k)
{
if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0;
if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;
return Factorial(n) /(Factorial(k)*Factorial((n - k)));
}
| <?php
$n=5;
$k=3;
function factorial($val){
for($f=2;$val-1>1;$f*=$val--);
return $f;
}
$binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k));
echo $binomial_coefficient;
?>
|
Write the same algorithm in PHP as shown in this C++ implementation. | int a[5];
a[0] = 1;
int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
#include <string>
std::string strings[4];
| <?php
$a = array();
# add elements "at the end"
array_push($a, 55, 10, 20);
print_r($a);
# using an explicit key
$a['one'] = 1;
$a['two'] = 2;
print_r($a);
?>
|
Port the following code from C++ to PHP with equivalent syntax and logic. | #include <fstream>
int main() {
constexpr auto dimx = 800u, dimy = 800u;
std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary);
ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n";
for (auto j = 0u; j < dimy; ++j)
for (auto i = 0u; i < dimx; ++i)
ofs << static_cast<char>(i % 256)
<< static_cast<char>(j % 256)
<< static_cast<char>((i * j) % 256);
}
| class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
public function writeP6($filename){
$fh = fopen($filename, 'w');
if (!$fh) return false;
fputs($fh, "P6 {$this->w} {$this->h} 255\n");
foreach ($this->data as $row){
foreach($row as $pixel){
fputs($fh, pack('C', $pixel[0]));
fputs($fh, pack('C', $pixel[1]));
fputs($fh, pack('C', $pixel[2]));
}
}
fclose($fh);
}
}
$b = new Bitmap(16,16);
$b->fill();
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');
|
Convert the following code from C++ to PHP, ensuring the logic remains intact. | #include <cstdio>
#include <direct.h>
int main() {
remove( "input.txt" );
remove( "/input.txt" );
_rmdir( "docs" );
_rmdir( "/docs" );
return 0;
}
| <?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/docs');
?>
|
Can you help me rewrite this code in PHP instead of C++, keeping it the same logically? | #include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
class myTuple
{
public:
void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }
bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }
string second() { return t.second; }
private:
pair<pair<int, int>, string> t;
};
class discordian
{
public:
discordian() {
myTuple t;
t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t );
t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t );
t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t );
t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t );
t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t );
t.set( 8, 12, "Afflux" ); holyday.push_back( t );
seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" );
seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" );
wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" );
wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" );
}
void convert( int d, int m, int y ) {
if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) {
cout << "\nThis is not a date!";
return;
}
vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) );
int dd = d, day, wday, sea, yr = y + 1166;
for( int x = 1; x < m; x++ )
dd += getMaxDay( x, 1 );
day = dd % 73; if( !day ) day = 73;
wday = dd % 5;
sea = ( dd - 1 ) / 73;
if( d == 29 && m == 2 && isLeap( y ) ) {
cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr;
return;
}
cout << wdays[wday] << " " << seasons[sea] << " " << day;
if( day > 10 && day < 14 ) cout << "th";
else switch( day % 10) {
case 1: cout << "st"; break;
case 2: cout << "nd"; break;
case 3: cout << "rd"; break;
default: cout << "th";
}
cout << ", Year of Our Lady of Discord " << yr;
if( f != holyday.end() ) cout << " - " << ( *f ).second();
}
private:
int getMaxDay( int m, int y ) {
int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m];
}
bool isLeap( int y ) {
bool l = false;
if( !( y % 4 ) ) {
if( y % 100 ) l = true;
else if( !( y % 400 ) ) l = true;
}
return l;
}
vector<myTuple> holyday; vector<string> seasons, wdays;
};
int main( int argc, char* argv[] ) {
string date; discordian disc;
while( true ) {
cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break;
if( date.length() == 10 ) {
istringstream iss( date );
vector<string> vc;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );
disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) );
cout << "\n\n\n";
} else cout << "\nIs this a date?!\n\n";
}
return 0;
}
| <?php
$Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);
$MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath");
$DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle");
$Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');
$Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay");
$Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux");
$edate = explode(" ",date('Y m j L'));
$usery = $edate[0];
$userm = $edate[1];
$userd = $edate[2];
$IsLeap = $edate[3];
if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) {
$usery = $_GET['y'];
$userm = $_GET['m'];
$userd = $_GET['d'];
$IsLeap = 0;
if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1;
if ($usery%400 == 0) $IsLeap = 1;
}
$userdays = 0;
$i = 0;
while ($i < ($userm-1)) {
$userdays = $userdays + $Anerisia[$i];
$i = $i +1;
}
$userdays = $userdays + $userd;
$IsHolyday = 0;
$dyear = $usery + 1166;
$dmonth = $MONTHS[$userdays/73.2];
$dday = $userdays%73;
if (0 == $dday) $dday = 73;
$Dname = $DAYS[$userdays%5];
$Holyday = "St. Tibs Day";
if ($dday == 5) {
$Holyday = $Holy5[$userdays/73.2];
$IsHolyday =1;
}
if ($dday == 50) {
$Holyday = $Holy50[$userdays/73.2];
$IsHolyday =1;
}
if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2;
$suff = $Dsuff[$dday%10] ;
if ((11 <= $dday) && (19 >= $dday)) $suff='th';
if ($IsHolyday ==2)
echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear;
if ($IsHolyday ==1)
echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday;
if ($IsHolyday == 0)
echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear;
?>
|
Convert the following code from C++ to PHP, ensuring the logic remains intact. | #include <string>
#include <iostream>
int main( ) {
std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) ,
replacement ( "little" ) ;
std::string newString = original.replace( original.find( "X" ) ,
toBeReplaced.length( ) , replacement ) ;
std::cout << "String after replacement: " << newString << " \n" ;
return 0 ;
}
| <?php
$extra = 'little';
echo "Mary had a $extra lamb.\n";
printf("Mary had a %s lamb.\n", $extra);
?>
|
Convert this C++ snippet to PHP and keep its semantics consistent. | #include <iostream>
#include <vector>
#include <stack>
#include <iterator>
#include <algorithm>
#include <cassert>
template <class E>
struct pile_less {
bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {
return pile1.top() < pile2.top();
}
};
template <class E>
struct pile_greater {
bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const {
return pile1.top() > pile2.top();
}
};
template <class Iterator>
void patience_sort(Iterator first, Iterator last) {
typedef typename std::iterator_traits<Iterator>::value_type E;
typedef std::stack<E> Pile;
std::vector<Pile> piles;
for (Iterator it = first; it != last; it++) {
E& x = *it;
Pile newPile;
newPile.push(x);
typename std::vector<Pile>::iterator i =
std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>());
if (i != piles.end())
i->push(x);
else
piles.push_back(newPile);
}
std::make_heap(piles.begin(), piles.end(), pile_greater<E>());
for (Iterator it = first; it != last; it++) {
std::pop_heap(piles.begin(), piles.end(), pile_greater<E>());
Pile &smallPile = piles.back();
*it = smallPile.top();
smallPile.pop();
if (smallPile.empty())
piles.pop_back();
else
std::push_heap(piles.begin(), piles.end(), pile_greater<E>());
}
assert(piles.empty());
}
int main() {
int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1};
patience_sort(a, a+sizeof(a)/sizeof(*a));
std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, ", "));
std::cout << std::endl;
return 0;
}
| <?php
class PilesHeap extends SplMinHeap {
public function compare($pile1, $pile2) {
return parent::compare($pile1->top(), $pile2->top());
}
}
function patience_sort(&$n) {
$piles = array();
foreach ($n as $x) {
$low = 0; $high = count($piles)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($piles[$mid]->top() >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
if ($i == count($piles))
$piles[] = new SplStack();
$piles[$i]->push($x);
}
$heap = new PilesHeap();
foreach ($piles as $pile)
$heap->insert($pile);
for ($c = 0; $c < count($n); $c++) {
$smallPile = $heap->extract();
$n[$c] = $smallPile->pop();
if (!$smallPile->isEmpty())
$heap->insert($smallPile);
}
assert($heap->isEmpty());
}
$a = array(4, 65, 2, -31, 0, 99, 83, 782, 1);
patience_sort($a);
print_r($a);
?>
|
Write a version of this C++ function in PHP with identical behavior. | #include <ggi/ggi.h>
#include <set>
#include <map>
#include <utility>
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
enum cell_type { none, wire, head, tail };
class display
{
public:
display(int sizex, int sizey, int pixsizex, int pixsizey,
ggi_color* colors);
~display()
{
ggiClose(visual);
ggiExit();
}
void flush();
bool keypressed() { return ggiKbhit(visual); }
void clear();
void putpixel(int x, int y, cell_type c);
private:
ggi_visual_t visual;
int size_x, size_y;
int pixel_size_x, pixel_size_y;
ggi_pixel pixels[4];
};
display::display(int sizex, int sizey, int pixsizex, int pixsizey,
ggi_color* colors):
pixel_size_x(pixsizex),
pixel_size_y(pixsizey)
{
if (ggiInit() < 0)
{
std::cerr << "couldn't open ggi\n";
exit(1);
}
visual = ggiOpen(NULL);
if (!visual)
{
ggiPanic("couldn't open visual\n");
}
ggi_mode mode;
if (ggiCheckGraphMode(visual, sizex, sizey,
GGI_AUTO, GGI_AUTO, GT_4BIT,
&mode) != 0)
{
if (GT_DEPTH(mode.graphtype) < 2)
ggiPanic("low-color displays are not supported!\n");
}
if (ggiSetMode(visual, &mode) != 0)
{
ggiPanic("couldn't set graph mode\n");
}
ggiAddFlags(visual, GGIFLAG_ASYNC);
size_x = mode.virt.x;
size_y = mode.virt.y;
for (int i = 0; i < 4; ++i)
pixels[i] = ggiMapColor(visual, colors+i);
}
void display::flush()
{
ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual));
ggiFlush(visual);
ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual));
}
void display::clear()
{
ggiSetGCForeground(visual, pixels[0]);
ggiDrawBox(visual, 0, 0, size_x, size_y);
}
void display::putpixel(int x, int y, cell_type cell)
{
ggiSetGCForeground(visual, pixels[cell]);
ggiDrawBox(visual,
x*pixel_size_x, y*pixel_size_y,
pixel_size_x, pixel_size_y);
}
class wireworld
{
public:
void set(int posx, int posy, cell_type type);
void draw(display& destination);
void step();
private:
typedef std::pair<int, int> position;
typedef std::set<position> position_set;
typedef position_set::iterator positer;
position_set wires, heads, tails;
};
void wireworld::set(int posx, int posy, cell_type type)
{
position p(posx, posy);
wires.erase(p);
heads.erase(p);
tails.erase(p);
switch(type)
{
case head:
heads.insert(p);
break;
case tail:
tails.insert(p);
break;
case wire:
wires.insert(p);
break;
}
}
void wireworld::draw(display& destination)
{
destination.clear();
for (positer i = heads.begin(); i != heads.end(); ++i)
destination.putpixel(i->first, i->second, head);
for (positer i = tails.begin(); i != tails.end(); ++i)
destination.putpixel(i->first, i->second, tail);
for (positer i = wires.begin(); i != wires.end(); ++i)
destination.putpixel(i->first, i->second, wire);
destination.flush();
}
void wireworld::step()
{
std::map<position, int> new_heads;
for (positer i = heads.begin(); i != heads.end(); ++i)
for (int dx = -1; dx <= 1; ++dx)
for (int dy = -1; dy <= 1; ++dy)
{
position pos(i->first + dx, i->second + dy);
if (wires.count(pos))
new_heads[pos]++;
}
wires.insert(tails.begin(), tails.end());
tails.swap(heads);
heads.clear();
for (std::map<position, int>::iterator i = new_heads.begin();
i != new_heads.end();
++i)
{
if (i->second < 3)
{
wires.erase(i->first);
heads.insert(i->first);
}
}
}
ggi_color colors[4] =
{{ 0x0000, 0x0000, 0x0000 },
{ 0x8000, 0x8000, 0x8000 },
{ 0xffff, 0xffff, 0x0000 },
{ 0xffff, 0x0000, 0x0000 }};
int main(int argc, char* argv[])
{
int display_x = 800;
int display_y = 600;
int pixel_x = 5;
int pixel_y = 5;
if (argc < 2)
{
std::cerr << "No file name given!\n";
return 1;
}
std::ifstream f(argv[1]);
wireworld w;
std::string line;
int line_number = 0;
while (std::getline(f, line))
{
for (int col = 0; col < line.size(); ++col)
{
switch (line[col])
{
case 'h': case 'H':
w.set(col, line_number, head);
break;
case 't': case 'T':
w.set(col, line_number, tail);
break;
case 'w': case 'W': case '.':
w.set(col, line_number, wire);
break;
default:
std::cerr << "unrecognized character: " << line[col] << "\n";
return 1;
case ' ':
;
}
}
++line_number;
}
display d(display_x, display_y, pixel_x, pixel_y, colors);
w.draw(d);
while (!d.keypressed())
{
usleep(100000);
w.step();
w.draw(d);
}
std::cout << std::endl;
}
| $desc = 'tH.........
. .
........
. .
Ht.. ......
..
tH.... .......
..
..
tH..... ......
..';
$steps = 30;
$world = array(array());
$row = 0;
$col = 0;
foreach(str_split($desc) as $i){
switch($i){
case "\n":
$row++;
$col = 0;
$world[] = array();
break;
case '.':
$world[$row][$col] = 1;//conductor
$col++;
break;
case 'H':
$world[$row][$col] = 2;//head
$col++;
break;
case 't':
$world[$row][$col] = 3;//tail
$col++;
break;
default:
$world[$row][$col] = 0;//insulator/air
$col++;
break;
};
};
function draw_world($world){
foreach($world as $rowc){
foreach($rowc as $cell){
switch($cell){
case 0:
echo ' ';
break;
case 1:
echo '.';
break;
case 2:
echo 'H';
break;
case 3:
echo 't';
};
};
echo "\n";
};
};
echo "Original world:\n";
draw_world($world);
for($i = 0; $i < $steps; $i++){
$old_world = $world; //backup to look up where was an electron head
foreach($world as $row => &$rowc){
foreach($rowc as $col => &$cell){
switch($cell){
case 2:
$cell = 3;
break;
case 3:
$cell = 1;
break;
case 1:
$neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row - 1][$col] == 2;
$neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2;
$neigh_heads += (int) @$old_world[$row][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row][$col + 1] == 2;
$neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2;
$neigh_heads += (int) @$old_world[$row + 1][$col] == 2;
if($neigh_heads == 1 || $neigh_heads == 2){
$cell = 2;
};
};
};
unset($cell); //just to be safe
};
unset($rowc); //just to be safe
echo "\nStep " . ($i + 1) . ":\n";
draw_world($world);
};
|
Please provide an equivalent version of this C++ code in PHP. | #include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
using namespace std;
const double epsilon = numeric_limits<float>().epsilon();
const numeric_limits<double> DOUBLE;
const double MIN = DOUBLE.min();
const double MAX = DOUBLE.max();
struct Point { const double x, y; };
struct Edge {
const Point a, b;
bool operator()(const Point& p) const
{
if (a.y > b.y) return Edge{ b, a }(p);
if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon });
if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false;
if (p.x < min(a.x, b.x)) return true;
auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX;
auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX;
return blue >= red;
}
};
struct Figure {
const string name;
const initializer_list<Edge> edges;
bool contains(const Point& p) const
{
auto c = 0;
for (auto e : edges) if (e(p)) c++;
return c % 2 != 0;
}
template<unsigned char W = 3>
void check(const initializer_list<Point>& points, ostream& os) const
{
os << "Is point inside figure " << name << '?' << endl;
for (auto p : points)
os << " (" << setw(W) << p.x << ',' << setw(W) << p.y << "): " << boolalpha << contains(p) << endl;
os << endl;
}
};
int main()
{
const initializer_list<Point> points = { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} };
const Figure square = { "Square",
{ {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} }
};
const Figure square_hole = { "Square hole",
{ {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}},
{{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}}
}
};
const Figure strange = { "Strange",
{ {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}},
{{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}}
}
};
const Figure exagon = { "Exagon",
{ {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}},
{{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}}
}
};
for(auto f : {square, square_hole, strange, exagon})
f.check(points, cout);
return EXIT_SUCCESS;
}
| <?php
function contains($bounds, $lat, $lng)
{
$count = 0;
$bounds_count = count($bounds);
for ($b = 0; $b < $bounds_count; $b++) {
$vertex1 = $bounds[$b];
$vertex2 = $bounds[($b + 1) % $bounds_count];
if (west($vertex1, $vertex2, $lng, $lat))
$count++;
}
return $count % 2;
}
function west($A, $B, $x, $y)
{
if ($A['y'] <= $B['y']) {
if ($y <= $A['y'] || $y > $B['y'] ||
$x >= $A['x'] && $x >= $B['x']) {
return false;
}
if ($x < $A['x'] && $x < $B['x']) {
return true;
}
if ($x == $A['x']) {
if ($y == $A['y']) {
$result1 = NAN;
} else {
$result1 = INF;
}
} else {
$result1 = ($y - $A['y']) / ($x - $A['x']);
}
if ($B['x'] == $A['x']) {
if ($B['y'] == $A['y']) {
$result2 = NAN;
} else {
$result2 = INF;
}
} else {
$result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']);
}
return $result1 > $result2;
}
return west($B, $A, $x, $y);
}
$square = [
'name' => 'square',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]]
];
$squareHole = [
'name' => 'squareHole',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]]
];
$strange = [
'name' => 'strange',
'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]]
];
$hexagon = [
'name' => 'hexagon',
'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]]
];
$shapes = [$square, $squareHole, $strange, $hexagon];
$testPoints = [
['lng' => 10, 'lat' => 10],
['lng' => 10, 'lat' => 16],
['lng' => -20, 'lat' => 10],
['lng' => 0, 'lat' => 10],
['lng' => 20, 'lat' => 10],
['lng' => 16, 'lat' => 10],
['lng' => 20, 'lat' => 20]
];
for ($s = 0; $s < count($shapes); $s++) {
$shape = $shapes[$s];
for ($tp = 0; $tp < count($testPoints); $tp++) {
$testPoint = $testPoints[$tp];
echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL;
}
}
|
Maintain the same structure and functionality when rewriting this code in PHP. | #include <iostream>
#include <string>
int countSubstring(const std::string& str, const std::string& sub)
{
if (sub.length() == 0) return 0;
int count = 0;
for (size_t offset = str.find(sub); offset != std::string::npos;
offset = str.find(sub, offset + sub.length()))
{
++count;
}
return count;
}
int main()
{
std::cout << countSubstring("the three truths", "th") << '\n';
std::cout << countSubstring("ababababab", "abab") << '\n';
std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n';
return 0;
}
| <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
|
Convert this C++ snippet to PHP and keep its semantics consistent. | #include <fstream>
#include <iostream>
#include <ctime>
using namespace std;
#define note_file "NOTES.TXT"
int main(int argc, char **argv)
{
if(argc>1)
{
ofstream Notes(note_file, ios::app);
time_t timer = time(NULL);
if(Notes.is_open())
{
Notes << asctime(localtime(&timer)) << '\t';
for(int i=1;i<argc;i++)
Notes << argv[i] << ' ';
Notes << endl;
Notes.close();
}
}
else
{
ifstream Notes(note_file, ios::in);
string line;
if(Notes.is_open())
{
while(!Notes.eof())
{
getline(Notes, line);
cout << line << endl;
}
Notes.close();
}
}
}
| #!/usr/bin/php
<?php
if ($argc > 1)
file_put_contents(
'notes.txt',
date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
FILE_APPEND
);
else
@readfile('notes.txt');
|
Generate an equivalent PHP version of this C++ code. | #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
std::string longestPath( const std::vector<std::string> & , char ) ;
int main( ) {
std::string dirs[ ] = {
"/home/user1/tmp/coverage/test" ,
"/home/user1/tmp/covert/operator" ,
"/home/user1/tmp/coven/members" } ;
std::vector<std::string> myDirs ( dirs , dirs + 3 ) ;
std::cout << "The longest common path of the given directories is "
<< longestPath( myDirs , '/' ) << "!\n" ;
return 0 ;
}
std::string longestPath( const std::vector<std::string> & dirs , char separator ) {
std::vector<std::string>::const_iterator vsi = dirs.begin( ) ;
int maxCharactersCommon = vsi->length( ) ;
std::string compareString = *vsi ;
for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) {
std::pair<std::string::const_iterator , std::string::const_iterator> p =
std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ;
if (( p.first - compareString.begin( ) ) < maxCharactersCommon )
maxCharactersCommon = p.first - compareString.begin( ) ;
}
std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;
return compareString.substr( 0 , found ) ;
}
| <?php
function _commonPath($dirList)
{
$arr = array();
foreach($dirList as $i => $path)
{
$dirList[$i] = explode('/', $path);
unset($dirList[$i][0]);
$arr[$i] = count($dirList[$i]);
}
$min = min($arr);
for($i = 0; $i < count($dirList); $i++)
{
while(count($dirList[$i]) > $min)
{
array_pop($dirList[$i]);
}
$dirList[$i] = '/' . implode('/' , $dirList[$i]);
}
$dirList = array_unique($dirList);
while(count($dirList) !== 1)
{
$dirList = array_map('dirname', $dirList);
$dirList = array_unique($dirList);
}
reset($dirList);
return current($dirList);
}
$dirs = array(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members',
);
if('/home/user1/tmp' !== common_path($dirs))
{
echo 'test fail';
} else {
echo 'test success';
}
?>
|
Generate an equivalent PHP version of this C++ code. | #include <iostream>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto i = v.cbegin();
auto e = v.cend();
os << '[';
if (i != e) {
os << *i;
i = std::next(i);
}
while (i != e) {
os << ", " << *i;
i = std::next(i);
}
return os << ']';
}
int main() {
using namespace std;
vector<int> a{ 0 };
set<int> used{ 0 };
set<int> used1000{ 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.find(next) != used.end()) {
next += 2 * n;
}
bool alreadyUsed = used.find(next) != used.end();
a.push_back(next);
if (!alreadyUsed) {
used.insert(next);
if (0 <= next && next <= 1000) {
used1000.insert(next);
}
}
if (n == 14) {
cout << "The first 15 terms of the Recaman sequence are: " << a << '\n';
}
if (!foundDup && alreadyUsed) {
cout << "The first duplicated term is a[" << n << "] = " << next << '\n';
foundDup = true;
}
if (used1000.size() == 1001) {
cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n";
}
n++;
}
return 0;
}
| <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
|
Rewrite this program in PHP while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto i = v.cbegin();
auto e = v.cend();
os << '[';
if (i != e) {
os << *i;
i = std::next(i);
}
while (i != e) {
os << ", " << *i;
i = std::next(i);
}
return os << ']';
}
int main() {
using namespace std;
vector<int> a{ 0 };
set<int> used{ 0 };
set<int> used1000{ 0 };
bool foundDup = false;
int n = 1;
while (n <= 15 || !foundDup || used1000.size() < 1001) {
int next = a[n - 1] - n;
if (next < 1 || used.find(next) != used.end()) {
next += 2 * n;
}
bool alreadyUsed = used.find(next) != used.end();
a.push_back(next);
if (!alreadyUsed) {
used.insert(next);
if (0 <= next && next <= 1000) {
used1000.insert(next);
}
}
if (n == 14) {
cout << "The first 15 terms of the Recaman sequence are: " << a << '\n';
}
if (!foundDup && alreadyUsed) {
cout << "The first duplicated term is a[" << n << "] = " << next << '\n';
foundDup = true;
}
if (used1000.size() == 1001) {
cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n";
}
n++;
}
return 0;
}
| <?php
$a = array();
array_push($a, 0);
$used = array();
array_push($used, 0);
$used1000 = array();
array_push($used1000, 0);
$foundDup = false;
$n = 1;
while($n <= 15 || !$foundDup || count($used1000) < 1001) {
$next = $a[$n - 1] - $n;
if ($next < 1 || in_array($next, $used)) {
$next += 2 * $n;
}
$alreadyUsed = in_array($next, $used);
array_push($a, $next);
if (!$alreadyUsed) {
array_push($used, $next);
if (0 <= $next && $next <= 1000) {
array_push($used1000, $next);
}
}
if ($n == 14) {
echo "The first 15 terms of the Recaman sequence are : [";
foreach($a as $i => $v) {
if ( $i == count($a) - 1)
echo "$v";
else
echo "$v, ";
}
echo "]\n";
}
if (!$foundDup && $alreadyUsed) {
printf("The first duplicate term is a[%d] = %d\n", $n, $next);
$foundDup = true;
}
if (count($used1000) == 1001) {
printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n);
}
$n++;
}
|
Can you help me rewrite this code in PHP instead of C++, keeping it the same logically? | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
enum players { Computer, Human, Draw, None };
const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } };
class ttt
{
public:
ttt() { _p = rand() % 2; reset(); }
void play()
{
int res = Draw;
while( true )
{
drawGrid();
while( true )
{
if( _p ) getHumanMove();
else getComputerMove();
drawGrid();
res = checkVictory();
if( res != None ) break;
++_p %= 2;
}
if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!";
else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!";
else cout << "It's a draw!";
cout << endl << endl;
string r;
cout << "Play again( Y / N )? "; cin >> r;
if( r != "Y" && r != "y" ) return;
++_p %= 2;
reset();
}
}
private:
void reset()
{
for( int x = 0; x < 9; x++ )
_field[x] = None;
}
void drawGrid()
{
system( "cls" );
COORD c = { 0, 2 };
SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
cout << " 1 | 2 | 3 " << endl;
cout << "---+---+---" << endl;
cout << " 4 | 5 | 6 " << endl;
cout << "---+---+---" << endl;
cout << " 7 | 8 | 9 " << endl << endl << endl;
int f = 0;
for( int y = 0; y < 5; y += 2 )
for( int x = 1; x < 11; x += 4 )
{
if( _field[f] != None )
{
COORD c = { x, 2 + y };
SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
string o = _field[f] == Computer ? "X" : "O";
cout << o;
}
f++;
}
c.Y = 9;
SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c );
}
int checkVictory()
{
for( int i = 0; i < 8; i++ )
{
if( _field[iWin[i][0]] != None &&
_field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] )
{
return _field[iWin[i][0]];
}
}
int i = 0;
for( int f = 0; f < 9; f++ )
{
if( _field[f] != None )
i++;
}
if( i == 9 ) return Draw;
return None;
}
void getHumanMove()
{
int m;
cout << "Enter your move ( 1 - 9 ) ";
while( true )
{
m = 0;
do
{ cin >> m; }
while( m < 1 && m > 9 );
if( _field[m - 1] != None )
cout << "Invalid move. Try again!" << endl;
else break;
}
_field[m - 1] = Human;
}
void getComputerMove()
{
int move = 0;
do{ move = rand() % 9; }
while( _field[move] != None );
for( int i = 0; i < 8; i++ )
{
int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2];
if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None )
{
move = try3;
if( _field[try1] == Computer ) break;
}
if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None )
{
move = try2;
if( _field[try1] == Computer ) break;
}
if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None )
{
move = try1;
if( _field[try2] == Computer ) break;
}
}
_field[move] = Computer;
}
int _p;
int _field[9];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
ttt tic;
tic.play();
return 0;
}
| <?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);
function isGameOver($board, $pin) {
$pat =
'/X{3}|' . //Horz
'X..X..X..|' . //Vert Left
'.X..X..X.|' . //Vert Middle
'..X..X..X|' . //Vert Right
'..X.X.X..|' . //Diag TL->BR
'X...X...X|' . //Diag TR->BL
'[^\.]{9}/i'; //Cat's game
if ($pin == 'O') $pat = str_replace('X', 'O', $pat);
return preg_match($pat, $board);
}
$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;
$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';
$oppTurn = $turn == 'X'? 'O' : 'X';
$gameOver = isGameOver($boardStr, $oppTurn);
echo '<style>';
echo 'td {width: 200px; height: 200px; text-align: center; }';
echo '.pin {font-size:72pt; text-decoration:none; color: black}';
echo '.pin.X {color:red}';
echo '.pin.O {color:blue}';
echo '</style>';
echo '<table border="1">';
$p = 0;
for ($r = 0; $r < ROW_NUM; $r++) {
echo '<tr>';
for ($c = 0; $c < ROW_NUM; $c++) {
$pin = $boardStr[$p];
echo '<td>';
if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied
else { //Available
$boardDelta = $boardStr;
$boardDelta[$p] = $turn;
echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">';
echo $boardStr[$p];
echo '</a>';
}
echo '</td>';
$p++;
}
echo '</tr>';
echo '<input type="hidden" name="b" value="', $boardStr, '"/>';
}
echo '</table>';
echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>';
if ($gameOver) echo '<h1>Game Over!</h1>';
|
Generate a PHP translation of this C++ snippet without changing its computational steps. | #include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
string readFile (string path) {
string contents;
string line;
ifstream inFile(path);
while (getline (inFile, line)) {
contents.append(line);
contents.append("\n");
}
inFile.close();
return contents;
}
double entropy (string X) {
const int MAXCHAR = 127;
int N = X.length();
int count[MAXCHAR];
double count_i;
char ch;
double sum = 0.0;
for (int i = 0; i < MAXCHAR; i++) count[i] = 0;
for (int pos = 0; pos < N; pos++) {
ch = X[pos];
count[(int)ch]++;
}
for (int n_i = 0; n_i < MAXCHAR; n_i++) {
count_i = count[n_i];
if (count_i > 0) sum -= count_i / N * log2(count_i / N);
}
return sum;
}
int main () {
cout<<entropy(readFile("entropy.cpp"));
return 0;
}
| <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h;
|
Translate this program into PHP but keep the logic exactly as in C++. | #include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
string readFile (string path) {
string contents;
string line;
ifstream inFile(path);
while (getline (inFile, line)) {
contents.append(line);
contents.append("\n");
}
inFile.close();
return contents;
}
double entropy (string X) {
const int MAXCHAR = 127;
int N = X.length();
int count[MAXCHAR];
double count_i;
char ch;
double sum = 0.0;
for (int i = 0; i < MAXCHAR; i++) count[i] = 0;
for (int pos = 0; pos < N; pos++) {
ch = X[pos];
count[(int)ch]++;
}
for (int n_i = 0; n_i < MAXCHAR; n_i++) {
count_i = count[n_i];
if (count_i > 0) sum -= count_i / N * log2(count_i / N);
}
return sum;
}
int main () {
cout<<entropy(readFile("entropy.cpp"));
return 0;
}
| <?php
$h = 0;
$s = file_get_contents(__FILE__);
$l = strlen($s);
foreach ( count_chars($s, 1) as $c )
$h -=
( $c / $l ) *
log( $c / $l, 2 );
echo $h;
|
Keep all operations the same but rewrite the snippet in PHP. | #include <Rcpp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace Rcpp ;
CharacterVector getNameInfo(std::string fqdn) {
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0);
if (error) { return(NA_STRING); }
int i = 0 ;
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (!error) { i++ ; }
}
CharacterVector results(i) ;
i = 0;
for (res = res0; res; res = res->ai_next) {
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (!error) { results[i++] = host ; }
}
freeaddrinfo(res0);
return(results) ;
}
| <?php
$ipv4_record = dns_get_record("www.kame.net",DNS_A);
$ipv6_record = dns_get_record("www.kame.net",DNS_AAAA);
print "ipv4: " . $ipv4_record[0]["ip"] . "\n";
print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n";
?>
|
Ensure the translated PHP code behaves exactly like the original C++ snippet. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };
enum indexes { PLAYER, COMPUTER, DRAW };
class stats
{
public:
stats() : _draw( 0 )
{
ZeroMemory( _moves, sizeof( _moves ) );
ZeroMemory( _win, sizeof( _win ) );
}
void draw() { _draw++; }
void win( int p ) { _win[p]++; }
void move( int p, int m ) { _moves[p][m]++; }
int getMove( int p, int m ) { return _moves[p][m]; }
string format( int a )
{
char t[32];
wsprintf( t, "%.3d", a );
string d( t );
return d;
}
void print()
{
string d = format( _draw ),
pw = format( _win[PLAYER] ), cw = format( _win[COMPUTER] ),
pr = format( _moves[PLAYER][ROCK] ), cr = format( _moves[COMPUTER][ROCK] ),
pp = format( _moves[PLAYER][PAPER] ), cp = format( _moves[COMPUTER][PAPER] ),
ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),
pl = format( _moves[PLAYER][LIZARD] ), cl = format( _moves[COMPUTER][LIZARD] ),
pk = format( _moves[PLAYER][SPOCK] ), ck = format( _moves[COMPUTER][SPOCK] );
system( "cls" );
cout << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |" << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << "| PLAYER | " << pw << " | | " << pr << " | " << pp << " | " << ps << " | " << pl << " | " << pk << " |" << endl;
cout << "+----------+-------+ " << d << " +--------+---------+----------+--------+---------+" << endl;
cout << "| COMPUTER | " << cw << " | | " << cr << " | " << cp << " | " << cs << " | " << cl << " | " << ck << " |" << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << endl << endl;
system( "pause" );
}
private:
int _moves[2][MX_C], _win[2], _draw;
};
class rps
{
private:
int makeMove()
{
int total = 0, r, s;
for( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );
r = rand() % total;
for( int i = ROCK; i < SCISSORS; i++ )
{
s = statistics.getMove( PLAYER, i );
if( r < s ) return ( i + 1 );
r -= s;
}
return ROCK;
}
void printMove( int p, int m )
{
if( p == COMPUTER ) cout << "My move: ";
else cout << "Your move: ";
switch( m )
{
case ROCK: cout << "ROCK\n"; break;
case PAPER: cout << "PAPER\n"; break;
case SCISSORS: cout << "SCISSORS\n"; break;
case LIZARD: cout << "LIZARD\n"; break;
case SPOCK: cout << "SPOCK\n";
}
}
public:
rps()
{
checker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;
checker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;
checker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;
checker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;
checker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;
}
void play()
{
int p, r, m;
while( true )
{
cout << "What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? ";
cin >> p;
if( !p || p < 0 ) break;
if( p > 0 && p < 6 )
{
p--;
cout << endl;
printMove( PLAYER, p );
statistics.move( PLAYER, p );
m = makeMove();
statistics.move( COMPUTER, m );
printMove( COMPUTER, m );
r = checker[p][m];
switch( r )
{
case DRAW:
cout << endl << "DRAW!" << endl << endl;
statistics.draw();
break;
case COMPUTER:
cout << endl << "I WIN!" << endl << endl;
statistics.win( COMPUTER );
break;
case PLAYER:
cout << endl << "YOU WIN!" << endl << endl;
statistics.win( PLAYER );
}
system( "pause" );
}
system( "cls" );
}
statistics.print();
}
private:
stats statistics;
int checker[MX_C][MX_C];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
rps game;
game.play();
return 0;
}
| <?php
echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>";
echo "<h2>";
echo "";
$player = strtoupper( $_GET["moves"] );
$wins = [
'ROCK' => 'SCISSORS',
'PAPER' => 'ROCK',
'SCISSORS' => 'PAPER'
];
$a_i = array_rand($wins);
echo "<br>";
echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>";
echo "<br>";
echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>";
$results = "";
if ($player == $a_i){
$results = "Draw";
} else if($wins[$a_i] == $player ){
$results = "A.I wins";
} else {
$results = "Player wins";
}
echo "<br>" . $results;
?>
|
Convert this C++ snippet to PHP and keep its semantics consistent. | #include <iostream>
#include <functional>
template <typename F>
struct RecursiveFunc {
std::function<F(RecursiveFunc)> o;
};
template <typename A, typename B>
std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {
RecursiveFunc<std::function<B(A)>> r = {
std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) {
return f(std::function<B(A)>([w](A x) {
return w.o(w)(x);
}));
})
};
return r.o(r);
}
typedef std::function<int(int)> Func;
typedef std::function<Func(Func)> FuncFunc;
FuncFunc almost_fac = [](Func f) {
return Func([f](int n) {
if (n <= 1) return 1;
return n * f(n - 1);
});
};
FuncFunc almost_fib = [](Func f) {
return Func([f](int n) {
if (n <= 2) return 1;
return f(n - 1) + f(n - 2);
});
};
int main() {
auto fib = Y(almost_fib);
auto fac = Y(almost_fac);
std::cout << "fib(10) = " << fib(10) << std::endl;
std::cout << "fac(10) = " << fac(10) << std::endl;
return 0;
}
| <?php
function Y($f) {
$g = function($w) use($f) {
return $f(function() use($w) {
return call_user_func_array($w($w), func_get_args());
});
};
return $g($g);
}
$fibonacci = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});
echo $fibonacci(10), "\n";
$factorial = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); };
});
echo $factorial(10), "\n";
?>
|
Convert the following code from C++ to PHP, ensuring the logic remains intact. | #include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <tuple>
std::tuple<int, int> minmax(const int * numbers, const std::size_t num) {
const auto maximum = std::max_element(numbers, numbers + num);
const auto minimum = std::min_element(numbers, numbers + num);
return std::make_tuple(*minimum, *maximum) ;
}
int main( ) {
const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}};
int min{};
int max{};
std::tie(min, max) = minmax(numbers.data(), numbers.size());
std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ;
}
| function addsub($x, $y) {
return array($x + $y, $x - $y);
}
|
Generate a PHP translation of this C++ snippet without changing its computational steps. |
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <sys/stat.h>
#include <ftplib.h>
#include <ftp++.hpp>
int stat(const char *pathname, struct stat *buf);
char *strerror(int errnum);
char *basename(char *path);
namespace stl
{
using std::cout;
using std::cerr;
using std::string;
using std::ifstream;
using std::remove;
};
using namespace stl;
using Mode = ftp::Connection::Mode;
Mode PASV = Mode::PASSIVE;
Mode PORT = Mode::PORT;
using TransferMode = ftp::Connection::TransferMode;
TransferMode BINARY = TransferMode::BINARY;
TransferMode TEXT = TransferMode::TEXT;
struct session
{
const string server;
const string port;
const string user;
const string pass;
Mode mode;
TransferMode txmode;
string dir;
};
ftp::Connection connect_ftp( const session& sess);
size_t get_ftp( ftp::Connection& conn, string const& path);
string readFile( const string& filename);
string login_ftp(ftp::Connection& conn, const session& sess);
string dir_listing( ftp::Connection& conn, const string& path);
string readFile( const string& filename)
{
struct stat stat_buf;
string contents;
errno = 0;
if (stat(filename.c_str() , &stat_buf) != -1)
{
size_t len = stat_buf.st_size;
string bytes(len+1, '\0');
ifstream ifs(filename);
ifs.read(&bytes[0], len);
if (! ifs.fail() ) contents.swap(bytes);
ifs.close();
}
else
{
cerr << "stat error: " << strerror(errno);
}
return contents;
}
ftp::Connection connect_ftp( const session& sess)
try
{
string constr = sess.server + ":" + sess.port;
cerr << "connecting to " << constr << " ...\n";
ftp::Connection conn{ constr.c_str() };
cerr << "connected to " << constr << "\n";
conn.setConnectionMode(sess.mode);
return conn;
}
catch (ftp::ConnectException e)
{
cerr << "FTP error: could not connect to server" << "\n";
}
string login_ftp(ftp::Connection& conn, const session& sess)
{
conn.login(sess.user.c_str() , sess.pass.c_str() );
return conn.getLastResponse();
}
string dir_listing( ftp::Connection& conn, const string& path)
try
{
const char* dirdata = "/dev/shm/dirdata";
conn.getList(dirdata, path.c_str() );
string dir_string = readFile(dirdata);
cerr << conn.getLastResponse() << "\n";
errno = 0;
if ( remove(dirdata) != 0 )
{
cerr << "error: " << strerror(errno) << "\n";
}
return dir_string;
}
catch (...) {
cerr << "error: getting dir contents: \n"
<< strerror(errno) << "\n";
}
size_t get_ftp( ftp::Connection& conn, const string& r_path)
{
size_t received = 0;
const char* path = r_path.c_str();
unsigned remotefile_size = conn.size(path , BINARY);
const char* localfile = basename(path);
conn.get(localfile, path, BINARY);
cerr << conn.getLastResponse() << "\n";
struct stat stat_buf;
errno = 0;
if (stat(localfile, &stat_buf) != -1)
received = stat_buf.st_size;
else
cerr << strerror(errno);
return received;
}
const session sonic
{
"mirrors.sonic.net",
"21" ,
"anonymous",
"xxxx@nohost.org",
PASV,
BINARY,
"/pub/OpenBSD"
};
int main(int argc, char* argv[], char * env[] )
{
const session remote = sonic;
try
{
ftp::Connection conn = connect_ftp(remote);
cerr << login_ftp(conn, remote);
cout << "System type: " << conn.getSystemType() << "\n";
cerr << conn.getLastResponse() << "\n";
conn.cd(remote.dir.c_str());
cerr << conn.getLastResponse() << "\n";
string pwdstr = conn.getDirectory();
cout << "PWD: " << pwdstr << "\n";
cerr << conn.getLastResponse() << "\n";
string dirlist = dir_listing(conn, pwdstr.c_str() );
cout << dirlist << "\n";
string filename = "ftplist";
auto pos = dirlist.find(filename);
auto notfound = string::npos;
if (pos != notfound)
{
size_t received = get_ftp(conn, filename.c_str() );
if (received == 0)
cerr << "got 0 bytes\n";
else
cerr << "got " << filename
<< " (" << received << " bytes)\n";
}
else
{
cerr << "file " << filename
<< "not found on server. \n";
}
}
catch (ftp::ConnectException e)
{
cerr << "FTP error: could not connect to server" << "\n";
}
catch (ftp::Exception e)
{
cerr << "FTP error: " << e << "\n";
}
catch (...)
{
cerr << "error: " << strerror(errno) << "\n";
}
return 0;
}
| $server = "speedtest.tele2.net";
$user = "anonymous";
$pass = "ftptest@example.com";
$conn = ftp_connect($server);
if (!$conn) {
die('unable to connect to: '. $server);
}
$login = ftp_login($conn, $user, $pass);
if (!$login) {
echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;
} else{
echo 'connected successfully'.PHP_EOL;
$directory = ftp_nlist($conn,'');
print_r($directory);
}
if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) {
echo "Successfully downloaded file".PHP_EOL;
} else {
echo "failed to download file";
}
|
Please provide an equivalent version of this C++ code in PHP. | #include <random>
#include <iostream>
#include <stack>
#include <set>
#include <string>
#include <functional>
using namespace std;
class RPNParse
{
public:
stack<double> stk;
multiset<int> digits;
void op(function<double(double,double)> f)
{
if(stk.size() < 2)
throw "Improperly written expression";
int b = stk.top(); stk.pop();
int a = stk.top(); stk.pop();
stk.push(f(a, b));
}
void parse(char c)
{
if(c >= '0' && c <= '9')
{
stk.push(c - '0');
digits.insert(c - '0');
}
else if(c == '+')
op([](double a, double b) {return a+b;});
else if(c == '-')
op([](double a, double b) {return a-b;});
else if(c == '*')
op([](double a, double b) {return a*b;});
else if(c == '/')
op([](double a, double b) {return a/b;});
}
void parse(string s)
{
for(int i = 0; i < s.size(); ++i)
parse(s[i]);
}
double getResult()
{
if(stk.size() != 1)
throw "Improperly written expression";
return stk.top();
}
};
int main()
{
random_device seed;
mt19937 engine(seed());
uniform_int_distribution<> distribution(1, 9);
auto rnd = bind(distribution, engine);
multiset<int> digits;
cout << "Make 24 with the digits: ";
for(int i = 0; i < 4; ++i)
{
int n = rnd();
cout << " " << n;
digits.insert(n);
}
cout << endl;
RPNParse parser;
try
{
string input;
getline(cin, input);
parser.parse(input);
if(digits != parser.digits)
cout << "Error: Not using the given digits" << endl;
else
{
double r = parser.getResult();
cout << "Result: " << r << endl;
if(r > 23.999 && r < 24.001)
cout << "Good job!" << endl;
else
cout << "Try again." << endl;
}
}
catch(char* e)
{
cout << "Error: " << e << endl;
}
return 0;
}
| #!/usr/bin/env php
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
<?php
while (true) {
$numbers = make_numbers();
for ($iteration_num = 1; ; $iteration_num++) {
echo "Expresion $iteration_num: ";
$entry = rtrim(fgets(STDIN));
if ($entry === '!') break;
if ($entry === 'q') exit;
$result = play($numbers, $entry);
if ($result === null) {
echo "That's not valid\n";
continue;
}
elseif ($result != 24) {
echo "Sorry, that's $result\n";
continue;
}
else {
echo "That's right! 24!!\n";
exit;
}
}
}
function make_numbers() {
$numbers = array();
echo "Your four digits: ";
for ($i = 0; $i < 4; $i++) {
$number = rand(1, 9);
if (!isset($numbers[$number])) {
$numbers[$number] = 0;
}
$numbers[$number]++;
print "$number ";
}
print "\n";
return $numbers;
}
function play($numbers, $expression) {
$operator = true;
for ($i = 0, $length = strlen($expression); $i < $length; $i++) {
$character = $expression[$i];
if (in_array($character, array('(', ')', ' ', "\t"))) continue;
$operator = !$operator;
if (!$operator) {
if (!empty($numbers[$character])) {
$numbers[$character]--;
continue;
}
return;
}
elseif (!in_array($character, array('+', '-', '*', '/'))) {
return;
}
}
foreach ($numbers as $remaining) {
if ($remaining > 0) {
return;
}
}
return eval("return $expression;");
}
?>
|
Generate an equivalent PHP version of this C++ code. | #include <random>
#include <iostream>
#include <stack>
#include <set>
#include <string>
#include <functional>
using namespace std;
class RPNParse
{
public:
stack<double> stk;
multiset<int> digits;
void op(function<double(double,double)> f)
{
if(stk.size() < 2)
throw "Improperly written expression";
int b = stk.top(); stk.pop();
int a = stk.top(); stk.pop();
stk.push(f(a, b));
}
void parse(char c)
{
if(c >= '0' && c <= '9')
{
stk.push(c - '0');
digits.insert(c - '0');
}
else if(c == '+')
op([](double a, double b) {return a+b;});
else if(c == '-')
op([](double a, double b) {return a-b;});
else if(c == '*')
op([](double a, double b) {return a*b;});
else if(c == '/')
op([](double a, double b) {return a/b;});
}
void parse(string s)
{
for(int i = 0; i < s.size(); ++i)
parse(s[i]);
}
double getResult()
{
if(stk.size() != 1)
throw "Improperly written expression";
return stk.top();
}
};
int main()
{
random_device seed;
mt19937 engine(seed());
uniform_int_distribution<> distribution(1, 9);
auto rnd = bind(distribution, engine);
multiset<int> digits;
cout << "Make 24 with the digits: ";
for(int i = 0; i < 4; ++i)
{
int n = rnd();
cout << " " << n;
digits.insert(n);
}
cout << endl;
RPNParse parser;
try
{
string input;
getline(cin, input);
parser.parse(input);
if(digits != parser.digits)
cout << "Error: Not using the given digits" << endl;
else
{
double r = parser.getResult();
cout << "Result: " << r << endl;
if(r > 23.999 && r < 24.001)
cout << "Good job!" << endl;
else
cout << "Try again." << endl;
}
}
catch(char* e)
{
cout << "Error: " << e << endl;
}
return 0;
}
| #!/usr/bin/env php
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwise you are repeatedly asked for an expression until it evaluates to 24
Note: you cannot form multiple digit numbers from the supplied digits,
so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
<?php
while (true) {
$numbers = make_numbers();
for ($iteration_num = 1; ; $iteration_num++) {
echo "Expresion $iteration_num: ";
$entry = rtrim(fgets(STDIN));
if ($entry === '!') break;
if ($entry === 'q') exit;
$result = play($numbers, $entry);
if ($result === null) {
echo "That's not valid\n";
continue;
}
elseif ($result != 24) {
echo "Sorry, that's $result\n";
continue;
}
else {
echo "That's right! 24!!\n";
exit;
}
}
}
function make_numbers() {
$numbers = array();
echo "Your four digits: ";
for ($i = 0; $i < 4; $i++) {
$number = rand(1, 9);
if (!isset($numbers[$number])) {
$numbers[$number] = 0;
}
$numbers[$number]++;
print "$number ";
}
print "\n";
return $numbers;
}
function play($numbers, $expression) {
$operator = true;
for ($i = 0, $length = strlen($expression); $i < $length; $i++) {
$character = $expression[$i];
if (in_array($character, array('(', ')', ' ', "\t"))) continue;
$operator = !$operator;
if (!$operator) {
if (!empty($numbers[$character])) {
$numbers[$character]--;
continue;
}
return;
}
elseif (!in_array($character, array('+', '-', '*', '/'))) {
return;
}
}
foreach ($numbers as $remaining) {
if ($remaining > 0) {
return;
}
}
return eval("return $expression;");
}
?>
|
Translate the given C++ code snippet into PHP without altering its behavior. | for(int i = 1;i <= 10; i++){
cout << i;
if(i % 5 == 0){
cout << endl;
continue;
}
cout << ", ";
}
| for ($i = 1; $i <= 10; $i++) {
echo $i;
if ($i % 5 == 0) {
echo "\n";
continue;
}
echo ', ';
}
|
Produce a functionally identical PHP code for the snippet given in C++. | #ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class QPaintEvent ;
class MyWidget : public QWidget {
public :
MyWidget( ) ;
protected :
void paintEvent( QPaintEvent * ) ;
private :
int width ;
int height ;
const int colornumber ;
} ;
#endif
| <?php
$colors = array(array( 0, 0, 0), // black
array(255, 0, 0), // red
array( 0, 255, 0), // green
array( 0, 0, 255), // blue
array(255, 0, 255), // magenta
array( 0, 255, 255), // cyan
array(255, 255, 0), // yellow
array(255, 255, 255)); // white
define('BARWIDTH', 640 / count($colors));
define('HEIGHT', 480);
$image = imagecreate(BARWIDTH * count($colors), HEIGHT);
foreach ($colors as $position => $color) {
$color = imagecolorallocate($image, $color[0], $color[1], $color[2]);
imagefilledrectangle($image, $position * BARWIDTH, 0,
$position * BARWIDTH + BARWIDTH - 1,
HEIGHT - 1, $color);
}
header('Content-type:image/png');
imagepng($image);
imagedestroy($image);
|
Preserve the algorithm and functionality while converting the code from C++ to PHP. | #ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class QPaintEvent ;
class MyWidget : public QWidget {
public :
MyWidget( ) ;
protected :
void paintEvent( QPaintEvent * ) ;
private :
int width ;
int height ;
const int colornumber ;
} ;
#endif
| <?php
$colors = array(array( 0, 0, 0), // black
array(255, 0, 0), // red
array( 0, 255, 0), // green
array( 0, 0, 255), // blue
array(255, 0, 255), // magenta
array( 0, 255, 255), // cyan
array(255, 255, 0), // yellow
array(255, 255, 255)); // white
define('BARWIDTH', 640 / count($colors));
define('HEIGHT', 480);
$image = imagecreate(BARWIDTH * count($colors), HEIGHT);
foreach ($colors as $position => $color) {
$color = imagecolorallocate($image, $color[0], $color[1], $color[2]);
imagefilledrectangle($image, $position * BARWIDTH, 0,
$position * BARWIDTH + BARWIDTH - 1,
HEIGHT - 1, $color);
}
header('Content-type:image/png');
imagepng($image);
imagedestroy($image);
|
Port the following code from C++ to PHP with equivalent syntax and logic. | #include <algorithm>
#include <iostream>
#include <vector>
#include <string>
class pair {
public:
pair( int s, std::string z ) { p = std::make_pair( s, z ); }
bool operator < ( const pair& o ) const { return i() < o.i(); }
int i() const { return p.first; }
std::string s() const { return p.second; }
private:
std::pair<int, std::string> p;
};
void gFizzBuzz( int c, std::vector<pair>& v ) {
bool output;
for( int x = 1; x <= c; x++ ) {
output = false;
for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {
if( !( x % ( *i ).i() ) ) {
std::cout << ( *i ).s();
output = true;
}
}
if( !output ) std::cout << x;
std::cout << "\n";
}
}
int main( int argc, char* argv[] ) {
std::vector<pair> v;
v.push_back( pair( 7, "Baxx" ) );
v.push_back( pair( 3, "Fizz" ) );
v.push_back( pair( 5, "Buzz" ) );
std::sort( v.begin(), v.end() );
gFizzBuzz( 20, v );
return 0;
}
| <?php
$max = 20;
$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');
for ($i = 1 ; $i <= $max ; $i++) {
$matched = false;
foreach ($factor AS $number => $word) {
if ($i % $number == 0) {
echo $word;
$matched = true;
}
}
echo ($matched ? '' : $i), PHP_EOL;
}
?>
|
Write the same code in PHP as shown below in C++. | #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ;
std::getline( std::cin , input ) ;
int linenumber = std::stoi( input ) ;
int lines_read = 0 ;
std::string line ;
if ( infile.is_open( ) ) {
while ( infile ) {
getline( infile , line ) ;
lines_read++ ;
if ( lines_read == linenumber ) {
std::cout << line << std::endl ;
break ;
}
}
infile.close( ) ;
if ( lines_read < linenumber )
std::cout << "No " << linenumber << " lines in " << file << " !\n" ;
return 0 ;
}
else {
std::cerr << "Could not find file " << file << " !\n" ;
return 1 ;
}
}
| <?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?>
|
Translate the given C++ code snippet into PHP without altering its behavior. | #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ;
std::getline( std::cin , input ) ;
int linenumber = std::stoi( input ) ;
int lines_read = 0 ;
std::string line ;
if ( infile.is_open( ) ) {
while ( infile ) {
getline( infile , line ) ;
lines_read++ ;
if ( lines_read == linenumber ) {
std::cout << line << std::endl ;
break ;
}
}
infile.close( ) ;
if ( lines_read < linenumber )
std::cout << "No " << linenumber << " lines in " << file << " !\n" ;
return 0 ;
}
else {
std::cerr << "Could not find file " << file << " !\n" ;
return 1 ;
}
}
| <?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOCROOT/exercises/words.txt", 'r');
if (!$fp) die("Input file not found!");
echo fileLine(7, $fp);
?>
|
Change the programming language of this snippet from C++ to PHP without modifying what it does. | #include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
const size_t n1 = str.length();
const size_t n2 = suffix.length();
if (n1 < n2)
return false;
return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),
[](char c1, char c2) {
return std::tolower(static_cast<unsigned char>(c1))
== std::tolower(static_cast<unsigned char>(c2));
});
}
bool filenameHasExtension(const std::string& filename,
const std::vector<std::string>& extensions) {
return std::any_of(extensions.begin(), extensions.end(),
[&filename](const std::string& extension) {
return endsWithIgnoreCase(filename, "." + extension);
});
}
void test(const std::string& filename,
const std::vector<std::string>& extensions) {
std::cout << std::setw(20) << std::left << filename
<< ": " << std::boolalpha
<< filenameHasExtension(filename, extensions) << '\n';
}
int main() {
const std::vector<std::string> extensions{"zip", "rar", "7z",
"gz", "archive", "A##", "tar.bz2"};
test("MyData.a##", extensions);
test("MyData.tar.Gz", extensions);
test("MyData.gzip", extensions);
test("MyData.7z.backup", extensions);
test("MyData...", extensions);
test("MyData", extensions);
test("MyData_v1.0.tar.bz2", extensions);
test("MyData_v1.0.bz2", extensions);
return 0;
}
| $allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];
$lc_allowed = array_map('strtolower', $allowed);
$tests = [
['MyData.a##',true],
['MyData.tar.Gz',true],
['MyData.gzip',false],
['MyData.7z.backup',false],
['MyData...',false],
['MyData',false],
['archive.tar.gz', true]
];
foreach ($tests as $test) {
$ext = pathinfo($test[0], PATHINFO_EXTENSION);
if (in_array(strtolower($ext), $lc_allowed)) {
$result = 'true';
} else {
$result = 'false';
}
printf("%20s : %s \n", $test[0],$result);
}
|
Write a version of this C++ function in PHP with identical behavior. | #include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
const size_t n1 = str.length();
const size_t n2 = suffix.length();
if (n1 < n2)
return false;
return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(),
[](char c1, char c2) {
return std::tolower(static_cast<unsigned char>(c1))
== std::tolower(static_cast<unsigned char>(c2));
});
}
bool filenameHasExtension(const std::string& filename,
const std::vector<std::string>& extensions) {
return std::any_of(extensions.begin(), extensions.end(),
[&filename](const std::string& extension) {
return endsWithIgnoreCase(filename, "." + extension);
});
}
void test(const std::string& filename,
const std::vector<std::string>& extensions) {
std::cout << std::setw(20) << std::left << filename
<< ": " << std::boolalpha
<< filenameHasExtension(filename, extensions) << '\n';
}
int main() {
const std::vector<std::string> extensions{"zip", "rar", "7z",
"gz", "archive", "A##", "tar.bz2"};
test("MyData.a##", extensions);
test("MyData.tar.Gz", extensions);
test("MyData.gzip", extensions);
test("MyData.7z.backup", extensions);
test("MyData...", extensions);
test("MyData", extensions);
test("MyData_v1.0.tar.bz2", extensions);
test("MyData_v1.0.bz2", extensions);
return 0;
}
| $allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];
$lc_allowed = array_map('strtolower', $allowed);
$tests = [
['MyData.a##',true],
['MyData.tar.Gz',true],
['MyData.gzip',false],
['MyData.7z.backup',false],
['MyData...',false],
['MyData',false],
['archive.tar.gz', true]
];
foreach ($tests as $test) {
$ext = pathinfo($test[0], PATHINFO_EXTENSION);
if (in_array(strtolower($ext), $lc_allowed)) {
$result = 'true';
} else {
$result = 'false';
}
printf("%20s : %s \n", $test[0],$result);
}
|
Port the following code from C++ to PHP with equivalent syntax and logic. | #include <algorithm>
#include <string>
#include <cctype>
void str_toupper(std::string &str) {
std::transform(str.begin(),
str.end(),
str.begin(),
(int(*)(int)) std::toupper);
}
void str_tolower(std::string &str) {
std::transform(str.begin(),
str.end(),
str.begin(),
(int(*)(int)) std::tolower);
}
| $str = "alphaBETA";
echo strtoupper($str), "\n"; // ALPHABETA
echo strtolower($str), "\n"; // alphabeta
echo ucfirst($str), "\n"; // AlphaBETA
echo lcfirst("FOObar"), "\n"; // fOObar
echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ
echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
|
Write the same code in PHP as shown below in C++. | #include <string>
#include <iostream>
#include "Poco/MD5Engine.h"
#include "Poco/DigestStream.h"
using Poco::DigestEngine ;
using Poco::MD5Engine ;
using Poco::DigestOutputStream ;
int main( ) {
std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ;
MD5Engine md5 ;
DigestOutputStream outstr( md5 ) ;
outstr << myphrase ;
outstr.flush( ) ;
const DigestEngine::Digest& digest = md5.digest( ) ;
std::cout << myphrase << " as a MD5 digest :\n" << DigestEngine::digestToHex( digest )
<< " !" << std::endl ;
return 0 ;
}
| $string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $string );
|
Generate a PHP translation of this C++ snippet without changing its computational steps. | #include <string>
#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>
#include <sstream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <locale>
int main( ) {
std::string datestring ("March 7 2009 7:30pm EST" ) ;
std::vector<std::string> elements ;
boost::split( elements , datestring , boost::is_any_of( " " ) ) ;
std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " +
elements[ 2 ] ;
std::string timepart = elements[ 3 ] ;
std::string timezone = elements[ 4 ] ;
const char meridians[ ] = { 'a' , 'p' } ;
std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;
std::string twelve_hour ( timepart.substr( found , 1 ) ) ;
timepart = timepart.substr( 0 , found ) ;
elements.clear( ) ;
boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ;
long hour = std::atol( (elements.begin( ))->c_str( ) ) ;
if ( twelve_hour == "p" )
hour += 12 ;
long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ;
boost::local_time::tz_database tz_db ;
tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ;
boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ;
boost::gregorian::date_input_facet *f =
new boost::gregorian::date_input_facet( "%B %d %Y" ) ;
std::stringstream ss ;
ss << datepart ;
ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;
boost::gregorian::date d ;
ss >> d ;
boost::posix_time::time_duration td ( hour , minute , 0 ) ;
boost::local_time::local_date_time lt ( d , td , dyc ,
boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;
std::cout << "local time: " << lt << '\n' ;
ss.str( "" ) ;
ss << lt ;
boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;
boost::local_time::local_date_time ltlater = lt + td2 ;
boost::gregorian::date_facet *f2 =
new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ;
std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;
std::cout << "12 hours after " << ss.str( ) << " it is " << ltlater << " !\n" ;
boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ;
std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ;
std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ;
return 0 ;
}
| <?php
$time = new DateTime('March 7 2009 7:30pm EST');
$time->modify('+12 hours');
echo $time->format('c');
?>
|
Port the provided C++ code into PHP while preserving the original functionality. | #include <chrono>
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char* argv[]) {
std::vector<std::thread> threads;
for (int i = 1; i < argc; ++i) {
threads.emplace_back([i, &argv]() {
int arg = std::stoi(argv[i]);
std::this_thread::sleep_for(std::chrono::seconds(arg));
std::cout << argv[i] << std::endl;
});
}
for (auto& thread : threads) {
thread.join();
}
}
| <?php
$buffer = 1;
$pids = [];
for ($i = 1; $i < $argc; $i++) {
$pid = pcntl_fork();
if ($pid < 0) {
die("failed to start child process");
}
if ($pid === 0) {
sleep($argv[$i] + $buffer);
echo $argv[$i] . "\n";
exit();
}
$pids[] = $pid;
}
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
|
Convert this C++ block to PHP, preserving its control flow and logic. | #include<cstdlib>
#include<ctime>
#include<iostream>
using namespace std;
int main()
{
int arr[10][10];
srand(time(NULL));
for(auto& row: arr)
for(auto& col: row)
col = rand() % 20 + 1;
([&](){
for(auto& row : arr)
for(auto& col: row)
{
cout << col << endl;
if(col == 20)return;
}
})();
return 0;
}
| <?php
for ($i = 0; $i < 10; $i++)
for ($j = 0; $j < 10; $j++)
$a[$i][$j] = rand(1, 20);
foreach ($a as $row) {
foreach ($row as $element) {
echo " $element";
if ($element == 20)
break 2; // 2 is the number of loops we want to break out of
}
echo "\n";
}
echo "\n";
?>
|
Change the programming language of this snippet from C++ to PHP without modifying what it does. | #include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>
using namespace std;
auto CountTriplets(unsigned long long maxPerimeter)
{
unsigned long long totalCount = 0;
unsigned long long primitveCount = 0;
auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
for(unsigned long long m = 2; m < max_M; ++m)
{
for(unsigned long long n = 1 + m % 2; n < m; n+=2)
{
if(gcd(m,n) != 1)
{
continue;
}
auto a = m * m - n * n;
auto b = 2 * m * n;
auto c = m * m + n * n;
auto perimeter = a + b + c;
if(perimeter <= maxPerimeter)
{
primitveCount++;
totalCount+= maxPerimeter / perimeter;
}
}
}
return tuple(totalCount, primitveCount);
}
int main()
{
vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
1000'000, 10'000'000, 100'000'000, 1000'000'000,
10'000'000'000};
for(auto maxPerimeter : inputs)
{
auto [total, primitive] = CountTriplets(maxPerimeter);
cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
}
}
| <?php
function gcd($a, $b)
{
if ($a == 0)
return $b;
if ($b == 0)
return $a;
if($a == $b)
return $a;
if($a > $b)
return gcd($a-$b, $b);
return gcd($a, $b-$a);
}
$pytha = 0;
$prim = 0;
$max_p = 100;
for ($a = 1; $a <= $max_p / 3; $a++) {
$aa = $a**2;
for ($b = $a + 1; $b < $max_p/2; $b++) {
$bb = $b**2;
for ($c = $b + 1; $c < $max_p/2; $c++) {
$cc = $c**2;
if ($aa + $bb < $cc) break;
if ($a + $b + $c > $max_p) break;
if ($aa + $bb == $cc) {
$pytha++;
if (gcd($a, $b) == 1) $prim++;
}
}
}
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
|
Produce a language-to-language conversion: from C++ to PHP, same semantics. | #include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>
using namespace std;
auto CountTriplets(unsigned long long maxPerimeter)
{
unsigned long long totalCount = 0;
unsigned long long primitveCount = 0;
auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
for(unsigned long long m = 2; m < max_M; ++m)
{
for(unsigned long long n = 1 + m % 2; n < m; n+=2)
{
if(gcd(m,n) != 1)
{
continue;
}
auto a = m * m - n * n;
auto b = 2 * m * n;
auto c = m * m + n * n;
auto perimeter = a + b + c;
if(perimeter <= maxPerimeter)
{
primitveCount++;
totalCount+= maxPerimeter / perimeter;
}
}
}
return tuple(totalCount, primitveCount);
}
int main()
{
vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
1000'000, 10'000'000, 100'000'000, 1000'000'000,
10'000'000'000};
for(auto maxPerimeter : inputs)
{
auto [total, primitive] = CountTriplets(maxPerimeter);
cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
}
}
| <?php
function gcd($a, $b)
{
if ($a == 0)
return $b;
if ($b == 0)
return $a;
if($a == $b)
return $a;
if($a > $b)
return gcd($a-$b, $b);
return gcd($a, $b-$a);
}
$pytha = 0;
$prim = 0;
$max_p = 100;
for ($a = 1; $a <= $max_p / 3; $a++) {
$aa = $a**2;
for ($b = $a + 1; $b < $max_p/2; $b++) {
$bb = $b**2;
for ($c = $b + 1; $c < $max_p/2; $c++) {
$cc = $c**2;
if ($aa + $bb < $cc) break;
if ($a + $b + $c > $max_p) break;
if ($aa + $bb == $cc) {
$pytha++;
if (gcd($a, $b) == 1) $prim++;
}
}
}
}
echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
|
Convert the following code from C++ to PHP, ensuring the logic remains intact. | #include <set>
#include <iostream>
using namespace std;
int main() {
typedef set<int> TySet;
int data[] = {1, 2, 3, 2, 3, 4};
TySet unique_set(data, data + 6);
cout << "Set items:" << endl;
for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)
cout << *iter << " ";
cout << endl;
}
| $list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');
$unique_list = array_unique($list);
|
Transform the following C++ implementation into PHP, maintaining the same output and logic. | #include <iostream>
#include <sstream>
#include <string>
std::string lookandsay(const std::string& s)
{
std::ostringstream r;
for (std::size_t i = 0; i != s.length();) {
auto new_i = s.find_first_not_of(s[i], i + 1);
if (new_i == std::string::npos)
new_i = s.length();
r << new_i - i << s[i];
i = new_i;
}
return r.str();
}
int main()
{
std::string laf = "1";
std::cout << laf << '\n';
for (int i = 0; i < 10; ++i) {
laf = lookandsay(laf);
std::cout << laf << '\n';
}
}
| <?php
function lookAndSay($str) {
return preg_replace_callback('#(.)\1*#', function($matches) {
return strlen($matches[0]).$matches[1];
}, $str);
}
$num = "1";
foreach(range(1,10) as $i) {
echo $num."<br/>";
$num = lookAndSay($num);
}
?>
|
Please provide an equivalent version of this C++ code in PHP. | #include <stack>
| $stack = array();
empty( $stack ); // true
array_push( $stack, 1 ); // or $stack[] = 1;
array_push( $stack, 2 ); // or $stack[] = 2;
empty( $stack ); // false
echo array_pop( $stack ); // outputs "2"
echo array_pop( $stack ); // outputs "1"
|
Produce a functionally identical PHP code for the snippet given in C++. | template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;
template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>
{
typedef ThenType type;
};
template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>
{
typedef ElseType type;
};
ifthenelse<INT_MAX == 32767,
long int,
int>
::type myvar;
| <?php
$foo = 3;
if ($foo == 2)
if ($foo == 3)
else
if ($foo != 0)
{
}
else
{
}
?>
|
Produce a functionally identical PHP code for the snippet given in C++. | #include <iostream>
#include <time.h>
using namespace std;
class stooge
{
public:
void sort( int* arr, int start, int end )
{
if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );
int n = end - start; if( n > 2 )
{
n /= 3; sort( arr, start, end - n );
sort( arr, start + n, end ); sort( arr, start, end - n );
}
}
};
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80;
cout << "before:\n";
for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20; cout << a[x] << " "; }
s.sort( a, 0, m ); cout << "\n\nafter:\n";
for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n";
return system( "pause" );
}
| function stoogeSort(&$arr, $i, $j)
{
if($arr[$j] < $arr[$i])
{
list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);
}
if(($j - $i) > 1)
{
$t = ($j - $i + 1) / 3;
stoogesort($arr, $i, $j - $t);
stoogesort($arr, $i + $t, $j);
stoogesort($arr, $i, $j - $t);
}
}
|
Change the programming language of this snippet from C++ to PHP without modifying what it does. | #include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/case_conv.hpp>
using namespace std;
using namespace boost;
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
static const char_separator<char> sep(" ","#;,");
struct configs{
string fullname;
string favoritefruit;
bool needspelling;
bool seedsremoved;
vector<string> otherfamily;
} conf;
void parseLine(const string &line, configs &conf)
{
if (line[0] == '#' || line.empty())
return;
Tokenizer tokenizer(line, sep);
vector<string> tokens;
for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)
tokens.push_back(*iter);
if (tokens[0] == ";"){
algorithm::to_lower(tokens[1]);
if (tokens[1] == "needspeeling")
conf.needspelling = false;
if (tokens[1] == "seedsremoved")
conf.seedsremoved = false;
}
algorithm::to_lower(tokens[0]);
if (tokens[0] == "needspeeling")
conf.needspelling = true;
if (tokens[0] == "seedsremoved")
conf.seedsremoved = true;
if (tokens[0] == "fullname"){
for (unsigned int i=1; i<tokens.size(); i++)
conf.fullname += tokens[i] + " ";
conf.fullname.erase(conf.fullname.size() -1, 1);
}
if (tokens[0] == "favouritefruit")
for (unsigned int i=1; i<tokens.size(); i++)
conf.favoritefruit += tokens[i];
if (tokens[0] == "otherfamily"){
unsigned int i=1;
string tmp;
while (i<=tokens.size()){
if ( i == tokens.size() || tokens[i] ==","){
tmp.erase(tmp.size()-1, 1);
conf.otherfamily.push_back(tmp);
tmp = "";
i++;
}
else{
tmp += tokens[i];
tmp += " ";
i++;
}
}
}
}
int _tmain(int argc, TCHAR* argv[])
{
if (argc != 2)
{
wstring tmp = argv[0];
wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl;
return -1;
}
ifstream file (argv[1]);
if (file.is_open())
while(file.good())
{
char line[255];
file.getline(line, 255);
string linestring(line);
parseLine(linestring, conf);
}
else
{
cout << "Unable to open the file" << endl;
return -2;
}
cout << "Fullname= " << conf.fullname << endl;
cout << "Favorite Fruit= " << conf.favoritefruit << endl;
cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl;
cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl;
string otherFamily;
for (unsigned int i = 0; i < conf.otherfamily.size(); i++)
otherFamily += conf.otherfamily[i] + ", ";
otherFamily.erase(otherFamily.size()-2, 2);
cout << "Other Family= " << otherFamily << endl;
return 0;
}
| <?php
$conf = file_get_contents('parse-conf-file.txt');
$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);
$conf = preg_replace_callback(
'/^([a-z]+)\s*=((?=.*\,.*).*)$/mi',
function ($matches) {
$r = '';
foreach (explode(',', $matches[2]) AS $val) {
$r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;
}
return $r;
},
$conf
);
$conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf);
$ini = parse_ini_string($conf);
echo 'Full name = ', $ini['FULLNAME'], PHP_EOL;
echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;
echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;
echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;
echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
|
Produce a functionally identical PHP code for the snippet given in C++. | #include <algorithm>
#include <string>
#include <cctype>
struct icompare_char {
bool operator()(char c1, char c2) {
return std::toupper(c1) < std::toupper(c2);
}
};
struct compare {
bool operator()(std::string const& s1, std::string const& s2) {
if (s1.length() > s2.length())
return true;
if (s1.length() < s2.length())
return false;
return std::lexicographical_compare(s1.begin(), s1.end(),
s2.begin(), s2.end(),
icompare_char());
}
};
int main() {
std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};
std::sort(strings, strings+8, compare());
return 0;
}
| <?php
function mycmp($s1, $s2)
{
if ($d = strlen($s2) - strlen($s1))
return $d;
return strcasecmp($s1, $s2);
}
$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
?>
|
Write a version of this C++ function in PHP with identical behavior. | #include <algorithm>
#include <iterator>
#include <iostream>
template<typename ForwardIterator> void selection_sort(ForwardIterator begin,
ForwardIterator end) {
for(auto i = begin; i != end; ++i) {
std::iter_swap(i, std::min_element(i, end));
}
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
selection_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
| function selection_sort(&$arr) {
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
$min = $i;
for($j = $i + 1; $j < $n; $j++){
if($arr[$j] < $arr[$min]){
$min = $j;
}
}
list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
}
}
|
Can you help me rewrite this code in PHP instead of C++, keeping it the same logically? | #include <iostream>
#include <algorithm>
void print_square(int i) {
std::cout << i*i << " ";
}
int main() {
int ary[]={1,2,3,4,5};
std::for_each(ary,ary+5,print_square);
return 0;
}
| function cube($n)
{
return($n * $n * $n);
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
|
Produce a functionally identical PHP code for the snippet given in C++. | #include <stdexcept>
template <typename Self>
class singleton
{
protected:
static Self*
sentry;
public:
static Self&
instance()
{
return *sentry;
}
singleton()
{
if(sentry)
throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!");
sentry = (Self*)this;
}
virtual ~singleton()
{
if(sentry == this)
sentry = 0;
}
};
template <typename Self>
Self*
singleton<Self>::sentry = 0;
#include <iostream>
#include <string>
using namespace
std;
class controller : public singleton<controller>
{
public:
controller(string const& name)
: name(name)
{
trace("begin");
}
~controller()
{
trace("end");
}
void
work()
{
trace("doing stuff");
}
void
trace(string const& message)
{
cout << name << ": " << message << endl;
}
string
name;
};
int
main()
{
controller*
first = new controller("first");
controller::instance().work();
delete first;
controller
second("second");
controller::instance().work();
try
{
controller
goner("goner");
controller::instance().work();
}
catch(exception const& error)
{
cout << error.what() << endl;
}
controller::instance().work();
controller
goner("goner");
controller::instance().work();
}
| class Singleton {
protected static $instance = null;
public $test_var;
private function __construct(){
}
public static function getInstance(){
if (is_null(self::$instance)){
self::$instance = new self();
}
return self::$instance;
}
}
$foo = Singleton::getInstance();
$foo->test_var = 'One';
$bar = Singleton::getInstance();
echo $bar->test_var; //Prints 'One'
$fail = new Singleton(); //Fatal error
|
Keep all operations the same but rewrite the snippet in PHP. | #include <iostream>
#include <string>
using namespace std;
int main() {
string dog = "Benjamin", Dog = "Samba", DOG = "Bernie";
cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl;
}
| <?php
$dog = 'Benjamin';
$Dog = 'Samba';
$DOG = 'Bernie';
echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n";
function DOG() { return 'Bernie'; }
echo 'There is only 1 dog named ' . dog() . "\n";
|
Port the following code from C++ to PHP with equivalent syntax and logic. | for(int i = 10; i >= 0; --i)
std::cout << i << "\n";
| for ($i = 10; $i >= 0; $i--)
echo "$i\n";
|
Change the programming language of this snippet from C++ to PHP without modifying what it does. | #include <fstream>
using namespace std;
int main()
{
ofstream file("new.txt");
file << "this is a string";
file.close();
return 0;
}
| file_put_contents($filename, $data)
|
Maintain the same structure and functionality when rewriting this code in PHP. | for(int i = 0; i < 5; ++i) {
for(int j = 0; j < i; ++j)
std::cout.put('*');
std::cout.put('\n');
}
| for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo '*';
}
echo "\n";
}
|
Produce a language-to-language conversion: from C++ to PHP, same semantics. | #include <iostream>
#include <sstream>
typedef long long bigInt;
using namespace std;
class number
{
public:
number() { s = "0"; neg = false; }
number( bigInt a ) { set( a ); }
number( string a ) { set( a ); }
void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); }
void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); }
number operator * ( const number& b ) { return this->mul( b ); }
number& operator *= ( const number& b ) { *this = *this * b; return *this; }
number& operator = ( const number& b ) { s = b.s; return *this; }
friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; }
friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; }
private:
number mul( const number& b )
{
number a; bool neg = false;
string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' );
int xx, ss, rr, t, c, stp = 0;
string::reverse_iterator xi = bs.rbegin(), si, ri;
for( ; xi != bs.rend(); xi++ )
{
c = 0; ri = r.rbegin() + stp;
for( si = s.rbegin(); si != s.rend(); si++ )
{
xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48;
ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10;
( *ri++ ) = t + 48;
}
if( c > 0 ) ( *ri ) = c + 48;
stp++;
}
trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0;
if( t & 1 ) a.s = "-" + r;
else a.s = r;
return a;
}
void trimLeft( string& r )
{
if( r.length() < 2 ) return;
for( string::iterator x = r.begin(); x != ( r.end() - 1 ); )
{
if( ( *x ) != '0' ) return;
x = r.erase( x );
}
}
void clearStr()
{
for( string::iterator x = s.begin(); x != s.end(); )
{
if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x );
else x++;
}
}
string s;
bool neg;
};
int main( int argc, char* argv[] )
{
number a, b;
a.set( "18446744073709551616" ); b.set( "18446744073709551616" );
cout << a * b << endl << endl;
cout << "Factor 1 = "; cin >> a;
cout << "Factor 2 = "; cin >> b;
cout << "Product: = " << a * b << endl << endl;
return system( "pause" );
}
| <?php
function longMult($a, $b)
{
$as = (string) $a;
$bs = (string) $b;
for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)
{
for($p = 0; $p < $pi; $p++)
{
$regi[$ai][] = 0;
}
for($bi = strlen($bs) - 1; $bi >= 0; $bi--)
{
$regi[$ai][] = $as[$ai] * $bs[$bi];
}
}
return $regi;
}
function longAdd($arr)
{
$outer = count($arr);
$inner = count($arr[$outer-1]) + $outer;
for($i = 0; $i <= $inner; $i++)
{
for($o = 0; $o < $outer; $o++)
{
$val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;
@$sum[$i] += $val;
}
}
return $sum;
}
function carry($arr)
{
for($i = 0; $i < count($arr); $i++)
{
$s = (string) $arr[$i];
switch(strlen($s))
{
case 2:
$arr[$i] = $s{1};
@$arr[$i+1] += $s{0};
break;
case 3:
$arr[$i] = $s{2};
@$arr[$i+1] += $s{0}.$s{1};
break;
}
}
return ltrim(implode('',array_reverse($arr)),'0');
}
function lm($a,$b)
{
return carry(longAdd(longMult($a,$b)));
}
if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')
{
echo 'pass!';
}; // 2^64 * 2^64
|
Produce a language-to-language conversion: from C++ to PHP, same semantics. | #include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
bool contains_duplicates(std::string s)
{
std::sort(s.begin(), s.end());
return std::adjacent_find(s.begin(), s.end()) != s.end();
}
void game()
{
typedef std::string::size_type index;
std::string symbols = "0123456789";
unsigned int const selection_length = 4;
std::random_shuffle(symbols.begin(), symbols.end());
std::string selection = symbols.substr(0, selection_length);
std::string guess;
while (std::cout << "Your guess? ", std::getline(std::cin, guess))
{
if (guess.length() != selection_length
|| guess.find_first_not_of(symbols) != std::string::npos
|| contains_duplicates(guess))
{
std::cout << guess << " is not a valid guess!";
continue;
}
unsigned int bulls = 0;
unsigned int cows = 0;
for (index i = 0; i != selection_length; ++i)
{
index pos = selection.find(guess[i]);
if (pos == i)
++bulls;
else if (pos != std::string::npos)
++cows;
}
std::cout << bulls << " bulls, " << cows << " cows.\n";
if (bulls == selection_length)
{
std::cout << "Congratulations! You have won!\n";
return;
}
}
std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n";
std::exit(EXIT_FAILURE);
}
int main()
{
std::cout << "Welcome to bulls and cows!\nDo you want to play? ";
std::string answer;
while (true)
{
while (true)
{
if (!std::getline(std::cin, answer))
{
std::cout << "I can't get an answer. Exiting.\n";
return EXIT_FAILURE;
}
if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y")
break;
if (answer == "no" || answer == "No" || answer == "n" || answer == "N")
{
std::cout << "Ok. Goodbye.\n";
return EXIT_SUCCESS;
}
std::cout << "Please answer yes or no: ";
}
game();
std::cout << "Another game? ";
}
}
| <?php
$size = 4;
$chosen = implode(array_rand(array_flip(range(1,9)), $size));
echo "I've chosen a number from $size unique digits from 1 to 9; you need
to input $size unique digits to guess my number\n";
for ($guesses = 1; ; $guesses++) {
while (true) {
echo "\nNext guess [$guesses]: ";
$guess = rtrim(fgets(STDIN));
if (!checkguess($guess))
echo "$size digits, no repetition, no 0... retry\n";
else
break;
}
if ($guess == $chosen) {
echo "You did it in $guesses attempts!\n";
break;
} else {
$bulls = 0;
$cows = 0;
foreach (range(0, $size-1) as $i) {
if ($guess[$i] == $chosen[$i])
$bulls++;
else if (strpos($chosen, $guess[$i]) !== FALSE)
$cows++;
}
echo "$cows cows, $bulls bulls\n";
}
}
function checkguess($g)
{
global $size;
return count(array_unique(str_split($g))) == $size &&
preg_match("/^[1-9]{{$size}}$/", $g);
}
?>
|
Maintain the same structure and functionality when rewriting this code in PHP. | #include <algorithm>
#include <iostream>
#include <iterator>
template <typename RandomAccessIterator>
void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) {
bool swapped = true;
while (begin != end-- && swapped) {
swapped = false;
for (auto i = begin; i != end; ++i) {
if (*(i + 1) < *i) {
std::iter_swap(i, i + 1);
swapped = true;
}
}
}
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
bubble_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
| function bubbleSort(array $array){
foreach($array as $i => &$val){
foreach($array as $k => &$val2){
if($k <= $i)
continue;
if($val > $val2) {
list($val, $val2) = [$val2, $val];
break;
}
}
}
return $array;
}
|
Preserve the algorithm and functionality while converting the code from C++ to PHP. | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream input ( "input.txt" );
ofstream output ("output.txt");
if (output.is_open()) {
if (input.is_open()){
while (getline (input,line)) {
output << line << endl;
}
input.close();
}
else {
cout << "input.txt cannot be opened!\n";
}
output.close();
}
else {
cout << "output.txt cannot be written to!\n";
}
return 0;
}
| <?php
if (!$in = fopen('input.txt', 'r')) {
die('Could not open input file.');
}
if (!$out = fopen('output.txt', 'w')) {
die('Could not open output file.');
}
while (!feof($in)) {
$data = fread($in, 512);
fwrite($out, $data);
}
fclose($out);
fclose($in);
?>
|
Write the same code in PHP as shown below in C++. | #include <iostream>
int main()
{
int a, b;
std::cin >> a >> b;
std::cout << "a+b = " << a+b << "\n";
std::cout << "a-b = " << a-b << "\n";
std::cout << "a*b = " << a*b << "\n";
std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n";
return 0;
}
| <?php
$a = fgets(STDIN);
$b = fgets(STDIN);
echo
"sum: ", $a + $b, "\n",
"difference: ", $a - $b, "\n",
"product: ", $a * $b, "\n",
"truncating quotient: ", (int)($a / $b), "\n",
"flooring quotient: ", floor($a / $b), "\n",
"remainder: ", $a % $b, "\n",
"power: ", $a ** $b, "\n"; // PHP 5.6+ only
?>
|
Translate this program into PHP but keep the logic exactly as in C++. | #include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
int main()
{
using namespace boost::numeric::ublas;
matrix<double> m(3,3);
for(int i=0; i!=m.size1(); ++i)
for(int j=0; j!=m.size2(); ++j)
m(i,j)=3*i+j;
std::cout << trans(m) << std::endl;
}
| function transpose($m) {
if (count($m) == 0) // special case: empty matrix
return array();
else if (count($m) == 1) // special case: row matrix
return array_chunk($m[0], 1);
array_unshift($m, NULL); // the original matrix is not modified because it was passed by value
return call_user_func_array('array_map', $m);
}
|
Produce a functionally identical PHP code for the snippet given in C++. | #include <iostream>
#include <tr1/memory>
using std::tr1::shared_ptr;
using std::tr1::enable_shared_from_this;
struct Arg {
virtual int run() = 0;
virtual ~Arg() { };
};
int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>,
shared_ptr<Arg>, shared_ptr<Arg>);
class B : public Arg, public enable_shared_from_this<B> {
private:
int k;
const shared_ptr<Arg> x1, x2, x3, x4;
public:
B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3,
shared_ptr<Arg> _x4)
: k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { }
int run() {
return A(--k, shared_from_this(), x1, x2, x3, x4);
}
};
class Const : public Arg {
private:
const int x;
public:
Const(int _x) : x(_x) { }
int run () { return x; }
};
int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3,
shared_ptr<Arg> x4, shared_ptr<Arg> x5) {
if (k <= 0)
return x4->run() + x5->run();
else {
shared_ptr<Arg> b(new B(k, x1, x2, x3, x4));
return b->run();
}
}
int main() {
std::cout << A(10, shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(-1)),
shared_ptr<Arg>(new Const(1)),
shared_ptr<Arg>(new Const(0))) << std::endl;
return 0;
}
| <?php
function A($k,$x1,$x2,$x3,$x4,$x5) {
$b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {
return A(--$k,$b,$x1,$x2,$x3,$x4);
};
return $k <= 0 ? $x4() + $x5() : $b();
}
echo A(10, function () { return 1; },
function () { return -1; },
function () { return -1; },
function () { return 1; },
function () { return 0; }) . "\n";
?>
|
Can you help me rewrite this code in PHP instead of C++, keeping it the same logically? | #include <iostream>
void recurse(unsigned int i)
{
std::cout<<i<<"\n";
recurse(i+1);
}
int main()
{
recurse(0);
}
| <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a();
|
Generate a PHP translation of this C++ snippet without changing its computational steps. | #include <iostream>
void recurse(unsigned int i)
{
std::cout<<i<<"\n";
recurse(i+1);
}
int main()
{
recurse(0);
}
| <?php
function a() {
static $i = 0;
print ++$i . "\n";
a();
}
a();
|
Maintain the same structure and functionality when rewriting this code in PHP. | #include <iostream>
using namespace std ;
int divisor_sum( int number ) {
int sum = 0 ;
for ( int i = 1 ; i < number ; i++ )
if ( number % i == 0 )
sum += i ;
return sum;
}
int main( ) {
cout << "Perfect numbers from 1 to 33550337:\n" ;
for ( int num = 1 ; num < 33550337 ; num++ ) {
if (divisor_sum(num) == num)
cout << num << '\n' ;
}
return 0 ;
}
| function is_perfect($number)
{
$sum = 0;
for($i = 1; $i < $number; $i++)
{
if($number % $i == 0)
$sum += $i;
}
return $sum == $number;
}
echo "Perfect numbers from 1 to 33550337:" . PHP_EOL;
for($num = 1; $num < 33550337; $num++)
{
if(is_perfect($num))
echo $num . PHP_EOL;
}
|
Convert this C++ snippet to PHP and keep its semantics consistent. |
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
void distribute(int dist, vector<int> &List) {
if (dist > List.size() )
List.resize(dist);
for (int i=0; i < dist; i++)
List[i]++;
}
vector<int> beadSort(int *myints, int n) {
vector<int> list, list2, fifth (myints, myints + n);
cout << "#1 Beads falling down: ";
for (int i=0; i < fifth.size(); i++)
distribute (fifth[i], list);
cout << '\n';
cout << "\nBeads on their sides: ";
for (int i=0; i < list.size(); i++)
cout << " " << list[i];
cout << '\n';
cout << "#2 Beads right side up: ";
for (int i=0; i < list.size(); i++)
distribute (list[i], list2);
cout << '\n';
return list2;
}
int main() {
int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};
vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));
cout << "Sorted list/array: ";
for(unsigned int i=0; i<sorted.size(); i++)
cout << sorted[i] << ' ';
}
| <?php
function columns($arr) {
if (count($arr) == 0)
return array();
else if (count($arr) == 1)
return array_chunk($arr[0], 1);
array_unshift($arr, NULL);
$transpose = call_user_func_array('array_map', $arr);
return array_map('array_filter', $transpose);
}
function beadsort($arr) {
foreach ($arr as $e)
$poles []= array_fill(0, $e, 1);
return array_map('count', columns(columns($poles)));
}
print_r(beadsort(array(5,3,1,7,4,1,1)));
?>
|
Write the same code in PHP as shown below in C++. | #include <iostream>
#include <boost/multiprecision/gmp.hpp>
#include <string>
namespace mp = boost::multiprecision;
int main(int argc, char const *argv[])
{
uint64_t tmpres = mp::pow(mp::mpz_int(4)
, mp::pow(mp::mpz_int(3)
, 2).convert_to<uint64_t>()
).convert_to<uint64_t>();
mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres);
std::string s = res.str();
std::cout << s.substr(0, 20)
<< "..."
<< s.substr(s.length() - 20, 20) << std::endl;
return 0;
}
| <?php
$y = bcpow('5', bcpow('4', bcpow('3', '2')));
printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y));
?>
|
Produce a language-to-language conversion: from C++ to PHP, same semantics. | #include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
const std::string _CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.:-_/";
const size_t MAX_NODES = 41;
class node
{
public:
node() { clear(); }
node( char z ) { clear(); }
~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; }
void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; }
bool isWord;
std::vector<std::string> files;
node* next[MAX_NODES];
};
class index {
public:
void add( std::string s, std::string fileName ) {
std::transform( s.begin(), s.end(), s.begin(), tolower );
std::string h;
for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
if( *i == 32 ) {
pushFileName( addWord( h ), fileName );
h.clear();
continue;
}
h.append( 1, *i );
}
if( h.length() )
pushFileName( addWord( h ), fileName );
}
void findWord( std::string s ) {
std::vector<std::string> v = find( s );
if( !v.size() ) {
std::cout << s + " was not found!\n";
return;
}
std::cout << s << " found in:\n";
for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) {
std::cout << *i << "\n";
}
std::cout << "\n";
}
private:
void pushFileName( node* n, std::string fn ) {
std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn );
if( i == n->files.end() ) n->files.push_back( fn );
}
const std::vector<std::string>& find( std::string s ) {
size_t idx;
std::transform( s.begin(), s.end(), s.begin(), tolower );
node* rt = &root;
for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
idx = _CHARS.find( *i );
if( idx < MAX_NODES ) {
if( !rt->next[idx] ) return std::vector<std::string>();
rt = rt->next[idx];
}
}
if( rt->isWord ) return rt->files;
return std::vector<std::string>();
}
node* addWord( std::string s ) {
size_t idx;
node* rt = &root, *n;
for( std::string::iterator i = s.begin(); i != s.end(); i++ ) {
idx = _CHARS.find( *i );
if( idx < MAX_NODES ) {
n = rt->next[idx];
if( n ){
rt = n;
continue;
}
n = new node( *i );
rt->next[idx] = n;
rt = n;
}
}
rt->isWord = true;
return rt;
}
node root;
};
int main( int argc, char* argv[] ) {
index t;
std::string s;
std::string files[] = { "file1.txt", "f_text.txt", "text_1b.txt" };
for( int x = 0; x < 3; x++ ) {
std::ifstream f;
f.open( files[x].c_str(), std::ios::in );
if( f.good() ) {
while( !f.eof() ) {
f >> s;
t.add( s, files[x] );
s.clear();
}
f.close();
}
}
while( true ) {
std::cout << "Enter one word to search for, return to exit: ";
std::getline( std::cin, s );
if( !s.length() ) break;
t.findWord( s );
}
return 0;
}
| <?php
function buildInvertedIndex($filenames)
{
$invertedIndex = [];
foreach($filenames as $filename)
{
$data = file_get_contents($filename);
if($data === false) die('Unable to read file: ' . $filename);
preg_match_all('/(\w+)/', $data, $matches, PREG_SET_ORDER);
foreach($matches as $match)
{
$word = strtolower($match[0]);
if(!array_key_exists($word, $invertedIndex)) $invertedIndex[$word] = [];
if(!in_array($filename, $invertedIndex[$word], true)) $invertedIndex[$word][] = $filename;
}
}
return $invertedIndex;
}
function lookupWord($invertedIndex, $word)
{
return array_key_exists($word, $invertedIndex) ? $invertedIndex[$word] : false;
}
$invertedIndex = buildInvertedIndex2(['file1.txt', 'file2.txt', 'file3.txt']);
foreach(['cat', 'is', 'banana', 'it'] as $word)
{
$matches = lookupWord($invertedIndex, $word);
if($matches !== false)
{
echo "Found the word \"$word\" in the following files: " . implode(', ', $matches) . "\n";
}
else
{
echo "Unable to find the word \"$word\" in the index\n";
}
}
|
Write a version of this C++ function in PHP with identical behavior. | #include <boost/math/common_factor.hpp>
#include <iostream>
int main( ) {
std::cout << "The least common multiple of 12 and 18 is " <<
boost::math::lcm( 12 , 18 ) << " ,\n"
<< "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
return 0 ;
}
| echo lcm(12, 18) == 36;
function lcm($m, $n) {
if ($m == 0 || $n == 0) return 0;
$r = ($m * $n) / gcd($m, $n);
return abs($r);
}
function gcd($a, $b) {
while ($b != 0) {
$t = $b;
$b = $a % $b;
$a = $t;
}
return $a;
}
|
Produce a functionally identical PHP code for the snippet given in C++. | #include <boost/math/common_factor.hpp>
#include <iostream>
int main( ) {
std::cout << "The least common multiple of 12 and 18 is " <<
boost::math::lcm( 12 , 18 ) << " ,\n"
<< "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
return 0 ;
}
| echo lcm(12, 18) == 36;
function lcm($m, $n) {
if ($m == 0 || $n == 0) return 0;
$r = ($m * $n) / gcd($m, $n);
return abs($r);
}
function gcd($a, $b) {
while ($b != 0) {
$t = $b;
$b = $a % $b;
$a = $t;
}
return $a;
}
|
Write the same code in PHP as shown below in C++. | #include <iostream>
#include <ctime>
#include <cstdlib>
int main(){
srand(time(NULL));
while(true){
const int a = rand() % 20;
std::cout << a << std::endl;
if(a == 10)
break;
const int b = rand() % 20;
std::cout << b << std::endl;
}
return 0;
}
| while (true) {
$a = rand(0,19);
echo "$a\n";
if ($a == 10)
break;
$b = rand(0,19);
echo "$b\n";
}
|
Write the same algorithm in PHP as shown in this C++ implementation. | #include <iostream>
#include <fstream>
int main(){
std::ofstream lprFile;
lprFile.open( "/dev/lp0" );
lprFile << "Hello World!\n";
lprFile.close();
return 0;
}
| <?php
file_put_contents('/dev/lp0', 'Hello world!');
?>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.