Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert the following code from C to PHP, ensuring the logic remains intact.
#include <stdio.h> #include <stdlib.h> int main(void) { char str[BUFSIZ]; puts("Enter a string: "); fgets(str, sizeof(str), stdin); long num; char buf[BUFSIZ]; do { puts("Enter 75000: "); fgets(buf, sizeof(buf), stdin); num = strtol(buf, NULL, 10); } while (num != 75000); return EXIT_SUCCESS; }
#!/usr/bin/php <?php $string = fgets(STDIN); $integer = (int) fgets(STDIN);
Write the same code in PHP as shown below in C.
#include <stdio.h> #include <stdlib.h> typedef struct { char *name; int weight; int value; } item_t; item_t items[] = { {"map", 9, 150}, {"compass", 13, 35}, {"water", 153, 200}, {"sandwich", 50, 160}, {"glucose", 15, 60}, {"tin", 68, 45}, {"banana", 27, 60}, {"apple", 39, 40}, {"cheese", 23, 30}, {"beer", 52, 10}, {"suntan cream", 11, 70}, {"camera", 32, 30}, {"T-shirt", 24, 15}, {"trousers", 48, 10}, {"umbrella", 73, 40}, {"waterproof trousers", 42, 70}, {"waterproof overclothes", 43, 75}, {"note-case", 22, 80}, {"sunglasses", 7, 20}, {"towel", 18, 12}, {"socks", 4, 50}, {"book", 30, 10}, }; int *knapsack (item_t *items, int n, int w) { int i, j, a, b, *mm, **m, *s; mm = calloc((n + 1) * (w + 1), sizeof (int)); m = malloc((n + 1) * sizeof (int *)); m[0] = mm; for (i = 1; i <= n; i++) { m[i] = &mm[i * (w + 1)]; for (j = 0; j <= w; j++) { if (items[i - 1].weight > j) { m[i][j] = m[i - 1][j]; } else { a = m[i - 1][j]; b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value; m[i][j] = a > b ? a : b; } } } s = calloc(n, sizeof (int)); for (i = n, j = w; i > 0; i--) { if (m[i][j] > m[i - 1][j]) { s[i - 1] = 1; j -= items[i - 1].weight; } } free(mm); free(m); return s; } int main () { int i, n, tw = 0, tv = 0, *s; n = sizeof (items) / sizeof (item_t); s = knapsack(items, n, 400); for (i = 0; i < n; i++) { if (s[i]) { printf("%-22s %5d %5d\n", items[i].name, items[i].weight, items[i].value); tw += items[i].weight; tv += items[i].value; } } printf("%-22s %5d %5d\n", "totals:", tw, tv); return 0; }
######################################################### # 0-1 Knapsack Problem Solve with memoization optimize and index returns # $w = weight of item # $v = value of item # $i = index # $aW = Available Weight # $m = Memo items array # PHP Translation from Python, Memoization, # and index return functionality added by Brian Berneker # ######################################################### function knapSolveFast2($w, $v, $i, $aW, &$m) { global $numcalls; $numcalls ++; if (isset($m[$i][$aW])) { return array( $m[$i][$aW], $m['picked'][$i][$aW] ); } else { if ($i == 0) { if ($w[$i] <= $aW) { // Will this item fit? $m[$i][$aW] = $v[$i]; // Memo this item $m['picked'][$i][$aW] = array($i); // and the picked item return array($v[$i],array($i)); // Return the value of this item and add it to the picked list } else { $m[$i][$aW] = 0; // Memo zero $m['picked'][$i][$aW] = array(); // and a blank array entry... return array(0,array()); // Return nothing } } list ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m); if ($w[$i] > $aW) { // Does it return too many? $m[$i][$aW] = $without_i; // Memo without including this one $m['picked'][$i][$aW] = $without_PI; // and a blank array entry... return array($without_i, $without_PI); // and return it } else { list ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m); $with_i += $v[$i]; // ..and add the value of this one.. if ($with_i > $without_i) { $res = $with_i; $picked = $with_PI; array_push($picked,$i); } else { $res = $without_i; $picked = $without_PI; } $m[$i][$aW] = $res; // Store it in the memo $m['picked'][$i][$aW] = $picked; // and store the picked item return array ($res,$picked); // and then return it } } } $items4 = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese","beer","suntan cream","camera","t-shirt","trousers","umbrella","waterproof trousers","waterproof overclothes","note-case","sunglasses","towel","socks","book"); $w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30); $v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10); ## Initialize $numcalls = 0; $m = array(); $pickedItems = array(); ## Solve list ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m); # Display Result echo "<b>Items:</b><br>".join(", ",$items4)."<br>"; echo "<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>"; echo "<b>Array Indices:</b><br>".join(",",$pickedItems)."<br>"; echo "<b>Chosen Items:</b><br>"; echo "<table border cellspacing=0>"; echo "<tr><td>Item</td><td>Value</td><td>Weight</td></tr>"; $totalVal = $totalWt = 0; foreach($pickedItems as $key) { $totalVal += $v4[$key]; $totalWt += $w4[$key]; echo "<tr><td>".$items4[$key]."</td><td>".$v4[$key]."</td><td>".$w4[$key]."</td></tr>"; } echo "<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>"; echo "</table><hr>";
Preserve the algorithm and functionality while converting the code from C to PHP.
#include <stdlib.h> #include <stdio.h> #include <math.h> typedef double (*Class2Func)(double); double functionA( double v) { return v*v*v; } double functionB(double v) { return exp(log(v)/3); } double Function1( Class2Func f2, double val ) { return f2(val); } Class2Func WhichFunc( int idx) { return (idx < 4) ? &functionA : &functionB; } Class2Func funcListA[] = {&functionA, &sin, &cos, &tan }; Class2Func funcListB[] = {&functionB, &asin, &acos, &atan }; double InvokeComposed( Class2Func f1, Class2Func f2, double val ) { return f1(f2(val)); } typedef struct sComposition { Class2Func f1; Class2Func f2; } *Composition; Composition Compose( Class2Func f1, Class2Func f2) { Composition comp = malloc(sizeof(struct sComposition)); comp->f1 = f1; comp->f2 = f2; return comp; } double CallComposed( Composition comp, double val ) { return comp->f1( comp->f2(val) ); } int main(int argc, char *argv[]) { int ix; Composition c; printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0)); for (ix=0; ix<4; ix++) { c = Compose(funcListA[ix], funcListB[ix]); printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9)); } return 0; }
$compose = function ($f, $g) { return function ($x) use ($f, $g) { return $f($g($x)); }; }; $fn = array('sin', 'cos', function ($x) { return pow($x, 3); }); $inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); }); for ($i = 0; $i < 3; $i++) { $f = $compose($inv[$i], $fn[$i]); echo $f(0.5), PHP_EOL; }
Rewrite the snippet below in PHP so it works the same as the original C code.
#include <stdio.h> #include <stdbool.h> int proper_divisors(const int n, bool print_flag) { int count = 0; for (int i = 1; i < n; ++i) { if (n % i == 0) { count++; if (print_flag) printf("%d ", i); } } if (print_flag) printf("\n"); return count; } int main(void) { for (int i = 1; i <= 10; ++i) { printf("%d: ", i); proper_divisors(i, true); } int max = 0; int max_i = 1; for (int i = 1; i <= 20000; ++i) { int v = proper_divisors(i, false); if (v >= max) { max = v; max_i = i; } } printf("%d with %d divisors\n", max_i, max); return 0; }
<?php function ProperDivisors($n) { yield 1; $large_divisors = []; for ($i = 2; $i <= sqrt($n); $i++) { if ($n % $i == 0) { yield $i; if ($i*$i != $n) { $large_divisors[] = $n / $i; } } } foreach (array_reverse($large_divisors) as $i) { yield $i; } } assert([1, 2, 4, 5, 10, 20, 25, 50] == iterator_to_array(ProperDivisors(100))); foreach (range(1, 10) as $n) { echo "$n =>"; foreach (ProperDivisors($n) as $divisor) { echo " $divisor"; } echo "\n"; } $divisorsCount = []; for ($i = 1; $i < 20000; $i++) { $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i; } ksort($divisorsCount); echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n"; echo "They have ", key($divisorsCount), " divisors.\n";
Please provide an equivalent version of this C code in PHP.
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <regex.h> #include <string.h> int main() { regex_t preg; regmatch_t substmatch[1]; const char *tp = "string$"; const char *t1 = "this is a matching string"; const char *t2 = "this is not a matching string!"; const char *ss = "istyfied"; regcomp(&preg, "string$", REG_EXTENDED); printf("'%s' %smatched with '%s'\n", t1, (regexec(&preg, t1, 0, NULL, 0)==0) ? "" : "did not ", tp); printf("'%s' %smatched with '%s'\n", t2, (regexec(&preg, t2, 0, NULL, 0)==0) ? "" : "did not ", tp); regfree(&preg); regcomp(&preg, "a[a-z]+", REG_EXTENDED); if ( regexec(&preg, t1, 1, substmatch, 0) == 0 ) { char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) + (strlen(t1) - substmatch[0].rm_eo) + 2); memcpy(ns, t1, substmatch[0].rm_so+1); memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss)); memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo], strlen(&t1[substmatch[0].rm_eo])); ns[ substmatch[0].rm_so + strlen(ss) + strlen(&t1[substmatch[0].rm_eo]) ] = 0; printf("mod string: '%s'\n", ns); free(ns); } else { printf("the string '%s' is the same: no matching!\n", t1); } regfree(&preg); return 0; }
$string = 'I am a string'; # Test if (preg_match('/string$/', $string)) { echo "Ends with 'string'\n"; } # Replace $string = preg_replace('/\ba\b/', 'another', $string); echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";
Keep all operations the same but rewrite the snippet in PHP.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define KeyType const char * #define ValType int #define HASH_SIZE 4096 unsigned strhashkey( const char * key, int max) { unsigned h=0; unsigned hl, hr; while(*key) { h += *key; hl= 0x5C5 ^ (h&0xfff00000 )>>18; hr =(h&0x000fffff ); h = hl ^ hr ^ *key++; } return h % max; } typedef struct sHme { KeyType key; ValType value; struct sHme *link; } *MapEntry; typedef struct he { MapEntry first, last; } HashElement; HashElement hash[HASH_SIZE]; typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc); typedef void (*ValCopyF)(ValType *vdest, ValType vsrc); typedef unsigned (*KeyHashF)( KeyType key, int upperBound ); typedef int (*KeyCmprF)(KeyType key1, KeyType key2); void HashAddH( KeyType key, ValType value, KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { (*copyVal)(&m_ent->value, value); } else { MapEntry last; MapEntry hme = malloc(sizeof(struct sHme)); (*copyKey)(&hme->key, key); (*copyVal)(&hme->value, value); hme->link = NULL; last = hash[hix].last; if (last) { last->link = hme; } else hash[hix].first = hme; hash[hix].last = hme; } } int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame ) { unsigned hix = (*hashKey)(key, HASH_SIZE); MapEntry m_ent; for (m_ent= hash[hix].first; m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link); if (m_ent) { *val = m_ent->value; } return (m_ent != NULL); } void copyStr(const char**dest, const char *src) { *dest = strdup(src); } void copyInt( int *dest, int src) { *dest = src; } int strCompare( const char *key1, const char *key2) { return strcmp(key1, key2) == 0; } void HashAdd( KeyType key, ValType value ) { HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare); } int HashGet(ValType *val, KeyType key) { return HashGetH( val, key, &strhashkey, &strCompare); } int main() { static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" }; static int valuList[] = {1,43,640, 747, 42, 42}; int ix; for (ix=0; ix<6; ix++) { HashAdd(keyList[ix], valuList[ix]); } return 0; }
$keys = array('a', 'b', 'c'); $values = array(1, 2, 3); $hash = array_combine($keys, $values);
Produce a language-to-language conversion: from C to PHP, same semantics.
#include <SDL/SDL.h> #ifdef WITH_CAIRO #include <cairo.h> #else #include <SDL/sge.h> #endif #include <cairo.h> #include <stdlib.h> #include <time.h> #include <math.h> #ifdef WITH_CAIRO #define PI 3.1415926535 #endif #define SIZE 800 #define SCALE 5 #define BRANCHES 14 #define ROTATION_SCALE 0.75 #define INITIAL_LENGTH 50 double rand_fl(){ return (double)rand() / (double)RAND_MAX; } void draw_tree(SDL_Surface * surface, double offsetx, double offsety, double directionx, double directiony, double size, double rotation, int depth) { #ifdef WITH_CAIRO cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels, CAIRO_FORMAT_RGB24, surface->w, surface->h, surface->pitch ); cairo_t *ct = cairo_create(surf); cairo_set_line_width(ct, 1); cairo_set_source_rgba(ct, 0,0,0,1); cairo_move_to(ct, (int)offsetx, (int)offsety); cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size)); cairo_stroke(ct); #else sge_AALine(surface, (int)offsetx, (int)offsety, (int)(offsetx + directionx * size), (int)(offsety + directiony * size), SDL_MapRGB(surface->format, 0, 0, 0)); #endif if (depth > 0){ draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(rotation) + directiony * sin(rotation), directionx * -sin(rotation) + directiony * cos(rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); draw_tree(surface, offsetx + directionx * size, offsety + directiony * size, directionx * cos(-rotation) + directiony * sin(-rotation), directionx * -sin(-rotation) + directiony * cos(-rotation), size * rand_fl() / SCALE + size * (SCALE - 1) / SCALE, rotation * ROTATION_SCALE, depth - 1); } } void render(SDL_Surface * surface){ SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255)); draw_tree(surface, surface->w / 2.0, surface->h - 10.0, 0.0, -1.0, INITIAL_LENGTH, PI / 8, BRANCHES); SDL_UpdateRect(surface, 0, 0, 0, 0); } int main(){ SDL_Surface * screen; SDL_Event evt; SDL_Init(SDL_INIT_VIDEO); srand((unsigned)time(NULL)); screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE); render(screen); while(1){ if (SDL_PollEvent(&evt)){ if(evt.type == SDL_QUIT) break; } SDL_Delay(1); } SDL_Quit(); return 0; }
<?php header("Content-type: image/png"); $width = 512; $height = 512; $img = imagecreatetruecolor($width,$height); $bg = imagecolorallocate($img,255,255,255); imagefilledrectangle($img, 0, 0, $width, $width, $bg); $depth = 8; function drawTree($x1, $y1, $angle, $depth){ global $img; if ($depth != 0){ $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0); $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0); imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0)); drawTree($x2, $y2, $angle - 20, $depth - 1); drawTree($x2, $y2, $angle + 20, $depth - 1); } } drawTree($width/2, $height, -90, $depth); imagepng($img); imagedestroy($img); ?>
Produce a language-to-language conversion: from C to PHP, same semantics.
int gray_encode(int n) { return n ^ (n >> 1); } int gray_decode(int n) { int p = n; while (n >>= 1) p ^= n; return p; }
<?php function gray_encode($binary){ return $binary ^ ($binary >> 1); } function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; } for($i=0;$i<32;$i++){ $gray_encoded = gray_encode($i); printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); }
Change the following C code into PHP without altering its purpose.
int gray_encode(int n) { return n ^ (n >> 1); } int gray_decode(int n) { int p = n; while (n >>= 1) p ^= n; return p; }
<?php function gray_encode($binary){ return $binary ^ ($binary >> 1); } function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; } for($i=0;$i<32;$i++){ $gray_encoded = gray_encode($i); printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); }
Rewrite the snippet below in PHP so it works the same as the original C code.
#include <stdio.h> #include <stdlib.h> #include <locale.h> int locale_ok = 0; wchar_t s_suits[] = L"♠♥♦♣"; const char *s_suits_ascii[] = { "S", "H", "D", "C" }; const char *s_nums[] = { "WHAT", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "OVERFLOW" }; typedef struct { int suit, number, _s; } card_t, *card; typedef struct { int n; card_t cards[52]; } deck_t, *deck; void show_card(card c) { if (locale_ok) printf(" %lc%s", s_suits[c->suit], s_nums[c->number]); else printf(" %s%s", s_suits_ascii[c->suit], s_nums[c->number]); } deck new_deck() { int i, j, k; deck d = malloc(sizeof(deck_t)); d->n = 52; for (i = k = 0; i < 4; i++) for (j = 1; j <= 13; j++, k++) { d->cards[k].suit = i; d->cards[k].number = j; } return d; } void show_deck(deck d) { int i; printf("%d cards:", d->n); for (i = 0; i < d->n; i++) show_card(d->cards + i); printf("\n"); } int cmp_card(const void *a, const void *b) { int x = ((card)a)->_s, y = ((card)b)->_s; return x < y ? -1 : x > y; } card deal_card(deck d) { if (!d->n) return 0; return d->cards + --d->n; } void shuffle_deck(deck d) { int i; for (i = 0; i < d->n; i++) d->cards[i]._s = rand(); qsort(d->cards, d->n, sizeof(card_t), cmp_card); } int main() { int i, j; deck d = new_deck(); locale_ok = (0 != setlocale(LC_CTYPE, "")); printf("New deck, "); show_deck(d); printf("\nShuffle and deal to three players:\n"); shuffle_deck(d); for (i = 0; i < 3; i++) { for (j = 0; j < 5; j++) show_card(deal_card(d)); printf("\n"); } printf("Left in deck "); show_deck(d); return 0; }
class Card { protected static $suits = array( '♠', '♥', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __construct( $suit, $pip ) { if( !in_array( $suit, self::$suits ) ) { throw new InvalidArgumentException( 'Invalid suit' ); } if( !in_array( $pip, self::$pips ) ) { throw new InvalidArgumentException( 'Invalid pip' ); } $this->suit = $suit; $this->pip = $pip; } public function getSuit() { return $this->suit; } public function getPip() { return $this->pip; } public function getSuitOrder() { if( !isset( $this->suitOrder ) ) { $this->suitOrder = array_search( $this->suit, self::$suits ); } return $this->suitOrder; } public function getPipOrder() { if( !isset( $this->pipOrder ) ) { $this->pipOrder = array_search( $this->pip, self::$pips ); } return $this->pipOrder; } public function getOrder() { if( !isset( $this->order ) ) { $suitOrder = $this->getSuitOrder(); $pipOrder = $this->getPipOrder(); $this->order = $pipOrder * count( self::$suits ) + $suitOrder; } return $this->order; } public function compareSuit( Card $other ) { return $this->getSuitOrder() - $other->getSuitOrder(); } public function comparePip( Card $other ) { return $this->getPipOrder() - $other->getPipOrder(); } public function compare( Card $other ) { return $this->getOrder() - $other->getOrder(); } public function __toString() { return $this->suit . $this->pip; } public static function getSuits() { return self::$suits; } public static function getPips() { return self::$pips; } } class CardCollection implements Countable, Iterator { protected $cards = array(); protected function __construct( array $cards = array() ) { foreach( $cards as $card ) { $this->addCard( $card ); } } public function count() { return count( $this->cards ); } public function key() { return key( $this->cards ); } public function valid() { return null !== $this->key(); } public function next() { next( $this->cards ); } public function current() { return current( $this->cards ); } public function rewind() { reset( $this->cards ); } public function sort( $comparer = null ) { $comparer = $comparer ?: function( $a, $b ) { return $a->compare( $b ); }; if( !is_callable( $comparer ) ) { throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' ); } usort( $this->cards, $comparer ); return $this; } public function toString() { return implode( ' ', $this->cards ); } public function __toString() { return $this->toString(); } protected function addCard( Card $card ) { if( in_array( $card, $this->cards ) ) { throw new DomainException( 'Card is already present in this collection' ); } $this->cards[] = $card; } } class Deck extends CardCollection { public function __construct( $shuffled = false ) { foreach( Card::getSuits() as $suit ) { foreach( Card::getPips() as $pip ) { $this->addCard( new Card( $suit, $pip ) ); } } if( $shuffled ) { $this->shuffle(); } } public function deal( $amount = 1, CardCollection $cardCollection = null ) { if( !is_int( $amount ) || $amount < 1 ) { throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' ); } if( $amount > count( $this->cards ) ) { throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' ); } $cards = array_splice( $this->cards, 0, $amount ); $cardCollection = $cardCollection ?: new CardCollection; foreach( $cards as $card ) { $cardCollection->addCard( $card ); } return $cardCollection; } public function shuffle() { shuffle( $this->cards ); } } class Hand extends CardCollection { public function __construct() {} public function play( $position ) { if( !isset( $this->cards[ $position ] ) ) { throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' ); } $result = array_splice( $this->cards, $position, 1 ); return $result[ 0 ]; } }
Maintain the same structure and functionality when rewriting this code in PHP.
char foo() { char array[5] = {3,6,9,12,15}; return array[2]; }
$NumberArray = array(0, 1, 2, 3, 4, 5, 6); $LetterArray = array("a", "b", "c", "d", "e", "f"); $simpleForm = ['apple', 'orange'];
Convert this C snippet to PHP and keep its semantics consistent.
#include <stdio.h> int main() { int i, j, dim, d; int depth = 3; for (i = 0, dim = 1; i < depth; i++, dim *= 3); for (i = 0; i < dim; i++) { for (j = 0; j < dim; j++) { for (d = dim / 3; d; d /= 3) if ((i % (d * 3)) / d == 1 && (j % (d * 3)) / d == 1) break; printf(d ? " " : "##"); } printf("\n"); } return 0; }
<?php function isSierpinskiCarpetPixelFilled($x, $y) { while (($x > 0) or ($y > 0)) { if (($x % 3 == 1) and ($y % 3 == 1)) { return false; } $x /= 3; $y /= 3; } return true; } function sierpinskiCarpet($order) { $size = pow(3, $order); for ($y = 0 ; $y < $size ; $y++) { for ($x = 0 ; $x < $size ; $x++) { echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' '; } echo PHP_EOL; } } for ($order = 0 ; $order <= 3 ; $order++) { echo 'N=', $order, PHP_EOL; sierpinskiCarpet($order); echo PHP_EOL; }
Port the following code from C to PHP with equivalent syntax and logic.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> bool is_sorted(int *a, int n) { while ( --n >= 1 ) { if ( a[n] < a[n-1] ) return false; } return true; } void shuffle(int *a, int n) { int i, t, r; for(i=0; i < n; i++) { t = a[i]; r = rand() % n; a[i] = a[r]; a[r] = t; } } void bogosort(int *a, int n) { while ( !is_sorted(a, n) ) shuffle(a, n); } int main() { int numbers[] = { 1, 10, 9, 7, 3, 0 }; int i; bogosort(numbers, 6); for (i=0; i < 6; i++) printf("%d ", numbers[i]); printf("\n"); }
function bogosort($l) { while (!in_order($l)) shuffle($l); return $l; } function in_order($l) { for ($i = 1; $i < count($l); $i++) if ($l[$i] < $l[$i-1]) return FALSE; return TRUE; }
Write a version of this C function in PHP with identical behavior.
#include <math.h> #include <stdio.h> #include <assert.h> int nonsqr(int n) { return n + (int)(0.5 + sqrt(n)); } int main() { int i; for (i = 1; i < 23; i++) printf("%d ", nonsqr(i)); printf("\n"); for (i = 1; i < 1000000; i++) { double j = sqrt(nonsqr(i)); assert(j != floor(j)); } return 0; }
<?php for($i=1;$i<=22;$i++){ echo($i + floor(1/2 + sqrt($i)) . "\n"); } $found_square=False; for($i=1;$i<=1000000;$i++){ $non_square=$i + floor(1/2 + sqrt($i)); if(sqrt($non_square)==intval(sqrt($non_square))){ $found_square=True; } } echo("\n"); if($found_square){ echo("Found a square number, so the formula does not always work."); } else { echo("Up to 1000000, found no square number in the sequence!"); } ?>
Transform the following C implementation into PHP, maintaining the same output and logic.
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> void putm(char* string, size_t m) { while(*string && m--) putchar(*string++); } int main(void) { char string[] = "Programs for other encodings (such as 8-bit ASCII, or EUC-JP)." int n = 3; int m = 4; char knownCharacter = '('; char knownSubstring[] = "encodings"; putm(string+n-1, m ); putchar('\n'); puts(string+n+1); putchar('\n'); putm(string, strlen(string)-1); putchar('\n'); putm(strchr(string, knownCharacter), m ); putchar('\n'); putm(strstr(string, knownSubstring), m ); putchar('\n'); return EXIT_SUCCESS; }
<?php $str = 'abcdefgh'; $n = 2; $m = 3; echo substr($str, $n, $m), "\n"; //cde echo substr($str, $n), "\n"; //cdefgh echo substr($str, 0, -1), "\n"; //abcdefg echo substr($str, strpos($str, 'd'), $m), "\n"; //def echo substr($str, strpos($str, 'de'), $m), "\n"; //def ?>
Change the following C code into PHP without altering its purpose.
#include <stdio.h> int is_leap_year(unsigned year) { return !(year & (year % 100 ? 3 : 15)); } int main(void) { const unsigned test_case[] = { 1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100 }; const unsigned n = sizeof test_case / sizeof test_case[0]; for (unsigned i = 0; i != n; ++i) { unsigned year = test_case[i]; printf("%u is %sa leap year.\n", year, is_leap_year(year) ? "" : "not "); } return 0; }
<?php function isLeapYear($year) { if ($year % 100 == 0) { return ($year % 400 == 0); } return ($year % 4 == 0); }
Translate the given C code snippet into PHP without altering its behavior.
#include <stdio.h> #include <string.h> const char *ones[] = { 0, "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char *tens[] = { 0, "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; const char *llions[] = { 0, "thousand", "million", "billion", "trillion", }; const int maxillion = sizeof(llions) / sizeof(llions[0]) * 3 - 3; int say_hundred(const char *s, int len, int depth, int has_lead) { int c[3], i; for (i = -3; i < 0; i++) { if (len + i >= 0) c[i + 3] = s[len + i] - '0'; else c[i + 3] = 0; } if (!(c[0] + c[1] + c[2])) return 0; if (c[0]) { printf("%s hundred", ones[c[0]]); has_lead = 1; } if (has_lead && (c[1] || c[2])) printf((!depth || c[0]) && (!c[0] || !c[1]) ? "and " : c[0] ? " " : ""); if (c[1] < 2) { if (c[1] || c[2]) printf("%s", ones[c[1] * 10 + c[2]]); } else { if (c[1]) { printf("%s", tens[c[1]]); if (c[2]) putchar('-'); } if (c[2]) printf("%s", ones[c[2]]); } return 1; } int say_maxillion(const char *s, int len, int depth, int has_lead) { int n = len / 3, r = len % 3; if (!r) { n--; r = 3; } const char *e = s + r; do { if (say_hundred(s, r, n, has_lead) && n) { has_lead = 1; printf(" %s", llions[n]); if (!depth) printf(", "); else printf(" "); } s = e; e += 3; } while (r = 3, n--); return 1; } void say_number(const char *s) { int len, i, got_sign = 0; while (*s == ' ') s++; if (*s < '0' || *s > '9') { if (*s == '-') got_sign = -1; else if (*s == '+') got_sign = 1; else goto nan; s++; } else got_sign = 1; while (*s == '0') { s++; if (*s == '\0') { printf("zero\n"); return; } } len = strlen(s); if (!len) goto nan; for (i = 0; i < len; i++) { if (s[i] < '0' || s[i] > '9') { printf("(not a number)"); return; } } if (got_sign == -1) printf("minus "); int n = len / maxillion; int r = len % maxillion; if (!r) { r = maxillion; n--; } const char *end = s + len - n * maxillion; int has_lead = 0; do { if ((has_lead = say_maxillion(s, r, n, has_lead))) { for (i = 0; i < n; i++) printf(" %s", llions[maxillion / 3]); if (n) printf(", "); } n--; r = maxillion; s = end; end += r; } while (n >= 0); printf("\n"); return; nan: printf("not a number\n"); return; } int main() { say_number("-42"); say_number("1984"); say_number("10000"); say_number("1024"); say_number("1001001001001"); say_number("123456789012345678901234567890123456789012345678900000001"); return 0; }
$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,'); $smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'); $decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'); function NumberToEnglish($num, $count = 0){ global $orderOfMag, $smallNumbers, $decades; $isLast = true; $str = ''; if ($num < 0){ $str = 'Negative '; $num = abs($num); } (int) $thisPart = substr((string) $num, -3); if (strlen((string) $num) > 3){ $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1); $isLast = false; } if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative ')) $and = ''; else $and = ' and '; if ($thisPart > 99){ $str .= ($isLast ? '' : ' ') . "{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}"; if(($thisPart %= 100) == 0){ $str .= " {$orderOfMag[$count]}"; return $str; } $and = ' and '; // Set up our and string to the word "and" since there is something in the hundreds place of this chunk } if ($thisPart >= 20){ $str .= "{$and}{$decades[$thisPart /10]}"; $and = ' '; // Make sure we don't have any extranious "and"s if(($thisPart %= 10) == 0) return $str . ($count != 0 ? " {$orderOfMag[$count]}" : ''); } if ($thisPart < 20 && $thisPart > 0) return $str . "{$and}{$smallNumbers[(int) $thisPart]} " . ($count != 0 ? $orderOfMag[$count] : ''); elseif ($thisPart == 0 && strlen($thisPart) == 1) return $str . "{$smallNumbers[(int)$thisPart]}"; }
Generate an equivalent PHP version of this C code.
#include <stdio.h> #include <stdlib.h> #include <string.h> int cmp(const int* a, const int* b) { return *b - *a; } void compareAndReportStringsLength(const char* strings[], const int n) { if (n > 0) { char* has_length = "has length"; char* predicate_max = "and is the longest string"; char* predicate_min = "and is the shortest string"; char* predicate_ave = "and is neither the longest nor the shortest string"; int* si = malloc(2 * n * sizeof(int)); if (si != NULL) { for (int i = 0; i < n; i++) { si[2 * i] = strlen(strings[i]); si[2 * i + 1] = i; } qsort(si, n, 2 * sizeof(int), cmp); int max = si[0]; int min = si[2 * (n - 1)]; for (int i = 0; i < n; i++) { int length = si[2 * i]; char* string = strings[si[2 * i + 1]]; char* predicate; if (length == max) predicate = predicate_max; else if (length == min) predicate = predicate_min; else predicate = predicate_ave; printf("\"%s\" %s %d %s\n", string, has_length, length, predicate); } free(si); } else { fputs("unable allocate memory buffer", stderr); } } } int main(int argc, char* argv[]) { char* list[] = { "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(list, 4); return EXIT_SUCCESS; }
<?php function retrieveStrings() { if (isset($_POST['input'])) { $strings = explode("\n", $_POST['input']); } else { $strings = ['abcd', '123456789', 'abcdef', '1234567']; } return $strings; } function setInput() { echo join("\n", retrieveStrings()); } function setOutput() { $strings = retrieveStrings(); $strings = array_map('trim', $strings); $strings = array_filter($strings); if (!empty($strings)) { usort($strings, function ($a, $b) { return strlen($b) - strlen($a); }); $max_len = strlen($strings[0]); $min_len = strlen($strings[count($strings) - 1]); foreach ($strings as $s) { $length = strlen($s); if ($length == $max_len) { $predicate = "is the longest string"; } elseif ($length == $min_len) { $predicate = "is the shortest string"; } else { $predicate = "is neither the longest nor the shortest string"; } echo "$s has length $length and $predicate\n"; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <style> div { margin-top: 4ch; margin-bottom: 4ch; } label { display: block; margin-bottom: 1ch; } textarea { display: block; } input { display: block; margin-top: 4ch; margin-bottom: 4ch; } </style> </head> <body> <main> <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8"> <div> <label for="input">Input: </label> <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea> </label> </div> <input type="submit" value="press to compare strings"> </input> <div> <label for="Output">Output: </label> <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea> </div> </form> </main> </body> </html>
Write a version of this C function in PHP with identical behavior.
#include <stdio.h> void shell_sort (int *a, int n) { int h, i, j, t; for (h = n; h /= 2;) { for (i = h; i < n; i++) { t = a[i]; for (j = i; j >= h && t < a[j - h]; j -= h) { a[j] = a[j - h]; } a[j] = t; } } } int main (int ac, char **av) { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); shell_sort(a, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; }
function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $arr; }
Ensure the translated PHP code behaves exactly like the original C snippet.
int frequency[26]; int ch; FILE* txt_file = fopen ("a_text_file.txt", "rt"); for (ch = 0; ch < 26; ch++) frequency[ch] = 0; while (1) { ch = fgetc(txt_file); if (ch == EOF) break; if ('a' <= ch && ch <= 'z') frequency[ch-'a']++; else if ('A' <= ch && ch <= 'Z') frequency[ch-'A']++; }
<?php print_r(array_count_values(str_split(file_get_contents($argv[1])))); ?>
Port the provided C code into PHP while preserving the original functionality.
#include <stdio.h> #include <string.h> #include <stdlib.h> char * incr(char *s) { int i, begin, tail, len; int neg = (*s == '-'); char tgt = neg ? '0' : '9'; if (!strcmp(s, "-1")) { s[0] = '0', s[1] = '\0'; return s; } len = strlen(s); begin = (*s == '-' || *s == '+') ? 1 : 0; for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--); if (tail < begin && !neg) { if (!begin) s = realloc(s, len + 2); s[0] = '1'; for (i = 1; i <= len - begin; i++) s[i] = '0'; s[len + 1] = '\0'; } else if (tail == begin && neg && s[1] == '1') { for (i = 1; i < len - begin; i++) s[i] = '9'; s[len - 1] = '\0'; } else { for (i = len - 1; i > tail; i--) s[i] = neg ? '9' : '0'; s[tail] += neg ? -1 : 1; } return s; } void string_test(const char *s) { char *ret = malloc(strlen(s)); strcpy(ret, s); printf("text: %s\n", ret); printf(" ->: %s\n", ret = incr(ret)); free(ret); } int main() { string_test("+0"); string_test("-1"); string_test("-41"); string_test("+41"); string_test("999"); string_test("+999"); string_test("109999999999999999999999999999999999999999"); string_test("-100000000000000000000000000000000000000000000"); return 0; }
$s = "12345"; $s++;
Transform the following C implementation into PHP, maintaining the same output and logic.
#include <string.h> #include <stdio.h> #include <stdlib.h> char *strip_chars(const char *string, const char *chars) { char * newstr = malloc(strlen(string) + 1); int counter = 0; for ( ; *string; string++) { if (!strchr(chars, *string)) { newstr[ counter ] = *string; ++ counter; } } newstr[counter] = 0; return newstr; } int main(void) { char *new = strip_chars("She was a soul stripper. She took my heart!", "aei"); printf("%s\n", new); free(new); return 0; }
<?php function stripchars($s, $chars) { return str_replace(str_split($chars), "", $s); } echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n"; ?>
Convert this C block to PHP, preserving its control flow and logic.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int(*cmp_func)(const void*, const void*); void perm_sort(void *a, int n, size_t msize, cmp_func _cmp) { char *p, *q, *tmp = malloc(msize); # define A(i) ((char *)a + msize * (i)) # define swap(a, b) {\ memcpy(tmp, a, msize);\ memcpy(a, b, msize);\ memcpy(b, tmp, msize); } while (1) { for (p = A(n - 1); (void*)p > a; p = q) if (_cmp(q = p - msize, p) > 0) break; if ((void*)p <= a) break; for (p = A(n - 1); p > q; p-= msize) if (_cmp(q, p) > 0) break; swap(p, q); for (q += msize, p = A(n - 1); q < p; q += msize, p -= msize) swap(p, q); } free(tmp); } int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } int main() { int i; const char *strs[] = { "spqr", "abc", "giant squid", "stuff", "def" }; perm_sort(strs, 5, sizeof(*strs), scmp); for (i = 0; i < 5; i++) printf("%s\n", strs[i]); return 0; }
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; } function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); $res = permute($newitems, $newperms); if($res){ return $res; } } } } $arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4); $arr = permute($arr); echo implode(',',$arr);
Translate this program into PHP but keep the logic exactly as in C.
#include <stdio.h> double mean(double *v, int len) { double sum = 0; int i; for (i = 0; i < len; i++) sum += v[i]; return sum / len; } int main(void) { double v[] = {1, 2, 2.718, 3, 3.142}; int i, len; for (len = 5; len >= 0; len--) { printf("mean["); for (i = 0; i < len; i++) printf(i ? ", %g" : "%g", v[i]); printf("] = %g\n", mean(v, len)); } return 0; }
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
Rewrite this program in PHP while keeping its functionality equivalent to the C version.
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 100 int makehist(unsigned char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ unsigned char S[MAXLEN]; int len,*hist,histlen; double H; scanf("%[^\n]",S); len=strlen(S); hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
<?php function shannonEntropy($string) { $h = 0.0; $len = strlen($string); foreach (count_chars($string, 1) as $count) { $h -= (double) ($count / $len) * log((double) ($count / $len), 2); } return $h; } $strings = array( '1223334444', '1225554444', 'aaBBcccDDDD', '122333444455555', 'Rosetta Code', '1234567890abcdefghijklmnopqrstuvwxyz', ); foreach ($strings AS $string) { printf( '%36s : %s' . PHP_EOL, $string, number_format(shannonEntropy($string), 6) ); }
Convert this C++ snippet to PHP and keep its semantics consistent.
#include <iostream> void bitwise(int a, int b) { std::cout << "a and b: " << (a & b) << '\n'; std::cout << "a or b: " << (a | b) << '\n'; std::cout << "a xor b: " << (a ^ b) << '\n'; std::cout << "not a: " << ~a << '\n'; std::cout << "a shl b: " << (a << b) << '\n'; std::cout << "a shr b: " << (a >> b) << '\n'; unsigned int ua = a; std::cout << "a lsr b: " << (ua >> b) << '\n'; std::cout << "a rol b: " << std::rotl(ua, b) << '\n'; std::cout << "a ror b: " << std::rotr(ua, b) << '\n'; }
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Change the programming language of this snippet from C++ to PHP without modifying what it does.
#include <fstream> #include <string> #include <iostream> int main( int argc , char** argv ) { int linecount = 0 ; std::string line ; std::ifstream infile( argv[ 1 ] ) ; if ( infile ) { while ( getline( infile , line ) ) { std::cout << linecount << ": " << line << '\n' ; linecount++ ; } } infile.close( ) ; return 0 ; }
<?php $file = fopen(__FILE__, 'r'); // read current file while ($line = fgets($file)) { $line = rtrim($line); // removes linebreaks and spaces at end echo strrev($line) . "\n"; // reverse line and upload it }
Write the same code in PHP as shown below in C++.
#include <string> #include <cstdlib> #include <algorithm> #include <cassert> std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz"; std::string to_base(unsigned long num, int base) { if (num == 0) return "0"; std::string result; while (num > 0) { std::ldiv_t temp = std::div(num, (long)base); result += digits[temp.rem]; num = temp.quot; } std::reverse(result.begin(), result.end()); return result; } unsigned long from_base(std::string const& num_str, int base) { unsigned long result = 0; for (std::string::size_type pos = 0; pos < num_str.length(); ++pos) result = result * base + digits.find(num_str[pos]); return result; }
base_convert("26", 10, 16); // returns "1a"
Change the following C++ code into PHP without altering its purpose.
#include "boost/filesystem.hpp" #include "boost/regex.hpp" #include <iostream> using namespace boost::filesystem; int main() { path current_dir("."); boost::regex pattern("a.*"); for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) { std::string name = iter->path().filename().string(); if (regex_match(name, pattern)) std::cout << iter->path() << "\n"; } }
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Convert the following code from C++ to PHP, ensuring the logic remains intact.
#include <algorithm> #include <array> #include <cstdint> #include <numeric> #include <iomanip> #include <iostream> #include <string> std::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept { auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL}; struct byte_checksum { std::uint_fast32_t operator()() noexcept { auto checksum = static_cast<std::uint_fast32_t>(n++); for (auto i = 0; i < 8; ++i) checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0); return checksum; } unsigned n = 0; }; auto table = std::array<std::uint_fast32_t, 256>{}; std::generate(table.begin(), table.end(), byte_checksum{}); return table; } template <typename InputIterator> std::uint_fast32_t crc(InputIterator first, InputIterator last) { static auto const table = generate_crc_lookup_table(); return std::uint_fast32_t{0xFFFFFFFFuL} & ~std::accumulate(first, last, ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL}, [](std::uint_fast32_t checksum, std::uint_fast8_t value) { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); }); } int main() { auto const s = std::string{"The quick brown fox jumps over the lazy dog"}; std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\n'; }
printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));
Change the following C++ code into PHP without altering its purpose.
PRAGMA COMPILER g++ PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive OPTION PARSE FALSE '---The class does the declaring for you CLASS Books public: const char* title; const char* author; const char* subject; int book_id; END CLASS '---pointer to an object declaration (we use a class called Books) DECLARE Book1 TYPE Books '--- the correct syntax for class Book1 = Books() '--- initialize the strings const char* in c++ Book1.title = "C++ Programming to bacon " Book1.author = "anyone" Book1.subject ="RECORD Tutorial" Book1.book_id = 1234567 PRINT "Book title  : " ,Book1.title FORMAT "%s%s\n" PRINT "Book author  : ", Book1.author FORMAT "%s%s\n" PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n" PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"
class MyClass { public static $classVar; public $instanceVar; // can also initialize it here function __construct() { $this->instanceVar = 0; } function someMethod() { $this->instanceVar = 1; self::$classVar = 3; } } $myObj = new MyClass();
Generate an equivalent PHP version of this C++ code.
#include <vector> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <utility> long string2long( const std::string & s ) { long result ; std::istringstream( s ) >> result ; return result ; } bool isKaprekar( long number ) { long long squarenumber = ((long long)number) * number ; std::ostringstream numberbuf ; numberbuf << squarenumber ; std::string numberstring = numberbuf.str( ) ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) { std::string firstpart = numberstring.substr( 0 , i ) , secondpart = numberstring.substr( i ) ; if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) { return false ; } if ( string2long( firstpart ) + string2long( secondpart ) == number ) { return true ; } } return false ; } int main( ) { std::vector<long> kaprekarnumbers ; kaprekarnumbers.push_back( 1 ) ; for ( int i = 2 ; i < 1000001 ; i++ ) { if ( isKaprekar( i ) ) kaprekarnumbers.push_back( i ) ; } std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ; std::cout << "Kaprekar numbers up to 10000: \n" ; while ( *svi < 10000 ) { std::cout << *svi << " " ; svi++ ; } std::cout << '\n' ; std::cout << "All the Kaprekar numbers up to 1000000 :\n" ; std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) , std::ostream_iterator<long>( std::cout , "\n" ) ) ; std::cout << "There are " << kaprekarnumbers.size( ) << " Kaprekar numbers less than one million!\n" ; return 0 ; }
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
Produce a language-to-language conversion: from C++ to PHP, same semantics.
#include <vector> #include <string> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include <utility> long string2long( const std::string & s ) { long result ; std::istringstream( s ) >> result ; return result ; } bool isKaprekar( long number ) { long long squarenumber = ((long long)number) * number ; std::ostringstream numberbuf ; numberbuf << squarenumber ; std::string numberstring = numberbuf.str( ) ; for ( int i = 0 ; i < numberstring.length( ) ; i++ ) { std::string firstpart = numberstring.substr( 0 , i ) , secondpart = numberstring.substr( i ) ; if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) { return false ; } if ( string2long( firstpart ) + string2long( secondpart ) == number ) { return true ; } } return false ; } int main( ) { std::vector<long> kaprekarnumbers ; kaprekarnumbers.push_back( 1 ) ; for ( int i = 2 ; i < 1000001 ; i++ ) { if ( isKaprekar( i ) ) kaprekarnumbers.push_back( i ) ; } std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ; std::cout << "Kaprekar numbers up to 10000: \n" ; while ( *svi < 10000 ) { std::cout << *svi << " " ; svi++ ; } std::cout << '\n' ; std::cout << "All the Kaprekar numbers up to 1000000 :\n" ; std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) , std::ostream_iterator<long>( std::cout , "\n" ) ) ; std::cout << "There are " << kaprekarnumbers.size( ) << " Kaprekar numbers less than one million!\n" ; return 0 ; }
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
Maintain the same structure and functionality when rewriting this code in PHP.
#include <string> #include <map> template <typename Iterator> Iterator compress(const std::string &uncompressed, Iterator result) { int dictSize = 256; std::map<std::string,int> dictionary; for (int i = 0; i < 256; i++) dictionary[std::string(1, i)] = i; std::string w; for (std::string::const_iterator it = uncompressed.begin(); it != uncompressed.end(); ++it) { char c = *it; std::string wc = w + c; if (dictionary.count(wc)) w = wc; else { *result++ = dictionary[w]; dictionary[wc] = dictSize++; w = std::string(1, c); } } if (!w.empty()) *result++ = dictionary[w]; return result; } template <typename Iterator> std::string decompress(Iterator begin, Iterator end) { int dictSize = 256; std::map<int,std::string> dictionary; for (int i = 0; i < 256; i++) dictionary[i] = std::string(1, i); std::string w(1, *begin++); std::string result = w; std::string entry; for ( ; begin != end; begin++) { int k = *begin; if (dictionary.count(k)) entry = dictionary[k]; else if (k == dictSize) entry = w + w[0]; else throw "Bad compressed k"; result += entry; dictionary[dictSize++] = w + entry[0]; w = entry; } return result; } #include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> compressed; compress("TOBEORNOTTOBEORTOBEORNOT", std::back_inserter(compressed)); copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; std::string decompressed = decompress(compressed.begin(), compressed.end()); std::cout << decompressed << std::endl; return 0; }
class LZW { function compress($unc) { $i;$c;$wc; $w = ""; $dictionary = array(); $result = array(); $dictSize = 256; for ($i = 0; $i < 256; $i += 1) { $dictionary[chr($i)] = $i; } for ($i = 0; $i < strlen($unc); $i++) { $c = $unc[$i]; $wc = $w.$c; if (array_key_exists($w.$c, $dictionary)) { $w = $w.$c; } else { array_push($result,$dictionary[$w]); $dictionary[$wc] = $dictSize++; $w = (string)$c; } } if ($w !== "") { array_push($result,$dictionary[$w]); } return implode(",",$result); } function decompress($com) { $com = explode(",",$com); $i;$w;$k;$result; $dictionary = array(); $entry = ""; $dictSize = 256; for ($i = 0; $i < 256; $i++) { $dictionary[$i] = chr($i); } $w = chr($com[0]); $result = $w; for ($i = 1; $i < count($com);$i++) { $k = $com[$i]; if (isset($dictionary[$k])) { $entry = $dictionary[$k]; } else { if ($k === $dictSize) { $entry = $w.$w[0]; } else { return null; } } $result .= $entry; $dictionary[$dictSize++] = $w . $entry[0]; $w = $entry; } return $result; } } $str = 'TOBEORNOTTOBEORTOBEORNOT'; $lzw = new LZW(); $com = $lzw->compress($str); $dec = $lzw->decompress($com); echo $com . "<br>" . $dec;
Please provide an equivalent version of this C++ code in PHP.
double fib(double n) { if(n < 0) { throw "Invalid argument passed to fib"; } else { struct actual_fib { static double calc(double n) { if(n < 2) { return n; } else { return calc(n-1) + calc(n-2); } } }; return actual_fib::calc(n); } }
<?php function fib($n) { if ($n < 0) throw new Exception('Negative numbers not allowed'); $f = function($n) { // This function must be called using call_user_func() only if ($n < 2) return 1; else { $g = debug_backtrace()[1]['args'][0]; return call_user_func($g, $n-1) + call_user_func($g, $n-2); } }; return call_user_func($f, $n); } echo fib(8), "\n"; ?>
Keep all operations the same but rewrite the snippet in PHP.
#include <string> #include <iostream> int main( ) { std::string word( "Premier League" ) ; std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ; std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ; std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ; return 0 ; }
<?php echo substr("knight", 1), "\n"; // strip first character echo substr("socks", 0, -1), "\n"; // strip last character echo substr("brooms", 1, -1), "\n"; // strip both first and last characters ?>
Write the same algorithm in PHP as shown in this C++ implementation.
#include <string> #include <iostream> int main( ) { std::string word( "Premier League" ) ; std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ; std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ; std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ; return 0 ; }
<?php echo substr("knight", 1), "\n"; // strip first character echo substr("socks", 0, -1), "\n"; // strip last character echo substr("brooms", 1, -1), "\n"; // strip both first and last characters ?>
Rewrite the snippet below in PHP so it works the same as the original C++ code.
#include <iostream> #include <string.h> int main() { std::string longLine, longestLines, newLine; while (std::cin >> newLine) { auto isNewLineShorter = longLine.c_str(); auto isLongLineShorter = newLine.c_str(); while (*isNewLineShorter && *isLongLineShorter) { isNewLineShorter = &isNewLineShorter[1]; isLongLineShorter = &isLongLineShorter[1]; } if(*isNewLineShorter) continue; if(*isLongLineShorter) { longLine = newLine; longestLines = newLine; } else { longestLines+=newLine; } longestLines+="\n"; } std::cout << "\nLongest string:\n" << longestLines; }
<?php echo 'Enter strings (empty string to finish) :', PHP_EOL; $output = $previous = readline(); while ($current = readline()) { $p = $previous; $c = $current; while ($p and $c) { $p = substr($p, 1); $c = substr($c, 1); } if (!$p and !$c) { $output .= PHP_EOL . $current; } if ($c) { $output = $previous = $current; } } echo 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;
Can you help me rewrite this code in PHP instead of C++, keeping it the same logically?
#include <direct.h> #include <fstream> int main() { std::fstream f("output.txt", std::ios::out); f.close(); f.open("/output.txt", std::ios::out); f.close(); _mkdir("docs"); _mkdir("/docs"); return 0; }
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Translate this program into PHP but keep the logic exactly as in C++.
#include <list> template <typename T> std::list<T> strandSort(std::list<T> lst) { if (lst.size() <= 1) return lst; std::list<T> result; std::list<T> sorted; while (!lst.empty()) { sorted.push_back(lst.front()); lst.pop_front(); for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) { if (sorted.back() <= *it) { sorted.push_back(*it); it = lst.erase(it); } else it++; } result.merge(sorted); } return result; }
$lst = new SplDoublyLinkedList(); foreach (array(1,20,64,72,48,75,96,55,42,74) as $v) $lst->push($v); foreach (strandSort($lst) as $v) echo "$v "; function strandSort(SplDoublyLinkedList $lst) { $result = new SplDoublyLinkedList(); while (!$lst->isEmpty()) { $sorted = new SplDoublyLinkedList(); $remain = new SplDoublyLinkedList(); $sorted->push($lst->shift()); foreach ($lst as $item) { if ($sorted->top() <= $item) { $sorted->push($item); } else { $remain->push($item); } } $result = _merge($sorted, $result); $lst = $remain; } return $result; } function _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) { $res = new SplDoublyLinkedList(); while (!$left->isEmpty() && !$right->isEmpty()) { if ($left->bottom() <= $right->bottom()) { $res->push($left->shift()); } else { $res->push($right->shift()); } } foreach ($left as $v) $res->push($v); foreach ($right as $v) $res->push($v); return $res; }
Produce a functionally identical PHP code for the snippet given in C++.
#include <tr1/memory> #include <string> #include <iostream> #include <tr1/functional> using namespace std; using namespace std::tr1; using std::tr1::function; class IDelegate { public: virtual ~IDelegate() {} }; class IThing { public: virtual ~IThing() {} virtual std::string Thing() = 0; }; class DelegateA : virtual public IDelegate { }; class DelegateB : public IThing, public IDelegate { std::string Thing() { return "delegate implementation"; } }; class Delegator { public: std::string Operation() { if(Delegate) if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get())) return pThing->Thing(); return "default implementation"; } shared_ptr<IDelegate> Delegate; }; int main() { shared_ptr<DelegateA> delegateA(new DelegateA()); shared_ptr<DelegateB> delegateB(new DelegateB()); Delegator delegator; std::cout << delegator.Operation() << std::endl; delegator.Delegate = delegateA; std::cout << delegator.Operation() << std::endl; delegator.Delegate = delegateB; std::cout << delegator.Operation() << std::endl; }
class Delegator { function __construct() { $this->delegate = NULL ; } function operation() { if(method_exists($this->delegate, "thing")) return $this->delegate->thing() ; return 'default implementation' ; } } class Delegate { function thing() { return 'Delegate Implementation' ; } } $a = new Delegator() ; print "{$a->operation()}\n" ; $a->delegate = 'A delegate may be any object' ; print "{$a->operation()}\n" ; $a->delegate = new Delegate() ; print "{$a->operation()}\n" ;
Rewrite the snippet below in PHP so it works the same as the original C++ code.
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } size_t get_min_length(const std::string& str) { size_t len = 0, n = str.length(); while (len < n && std::isupper(static_cast<unsigned char>(str[len]))) ++len; return len; } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::vector<command> commands; std::istringstream is(table); std::string word; while (is >> word) { size_t len = get_min_length(word); uppercase(word); commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)]; } return $rs; }
Preserve the algorithm and functionality while converting the code from C++ to PHP.
#include <algorithm> #include <cctype> #include <iostream> #include <sstream> #include <string> #include <vector> const char* command_table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up"; class command { public: command(const std::string&, size_t); const std::string& cmd() const { return cmd_; } size_t min_length() const { return min_len_; } bool match(const std::string&) const; private: std::string cmd_; size_t min_len_; }; command::command(const std::string& cmd, size_t min_len) : cmd_(cmd), min_len_(min_len) {} bool command::match(const std::string& str) const { size_t olen = str.length(); return olen >= min_len_ && olen <= cmd_.length() && cmd_.compare(0, olen, str) == 0; } void uppercase(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) -> unsigned char { return std::toupper(c); }); } size_t get_min_length(const std::string& str) { size_t len = 0, n = str.length(); while (len < n && std::isupper(static_cast<unsigned char>(str[len]))) ++len; return len; } class command_list { public: explicit command_list(const char*); const command* find_command(const std::string&) const; private: std::vector<command> commands_; }; command_list::command_list(const char* table) { std::vector<command> commands; std::istringstream is(table); std::string word; while (is >> word) { size_t len = get_min_length(word); uppercase(word); commands_.push_back(command(word, len)); } } const command* command_list::find_command(const std::string& word) const { auto iter = std::find_if(commands_.begin(), commands_.end(), [&word](const command& cmd) { return cmd.match(word); }); return (iter != commands_.end()) ? &*iter : nullptr; } std::string test(const command_list& commands, const std::string& input) { std::string output; std::istringstream is(input); std::string word; while (is >> word) { if (!output.empty()) output += ' '; uppercase(word); const command* cmd_ptr = commands.find_command(word); if (cmd_ptr) output += cmd_ptr->cmd(); else output += "*error*"; } return output; } int main() { command_list commands(command_table); std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin"); std::string output(test(commands, input)); std::cout << " input: " << input << '\n'; std::cout << "output: " << output << '\n'; return 0; }
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)]; } return $rs; }
Keep all operations the same but rewrite the snippet in PHP.
#include <iostream> class MyOtherClass { public: const int m_x; MyOtherClass(const int initX = 0) : m_x(initX) { } }; int main() { MyOtherClass mocA, mocB(7); std::cout << mocA.m_x << std::endl; std::cout << mocB.m_x << std::endl; return 0; }
define("PI", 3.14159265358); define("MSG", "Hello World");
Maintain the same structure and functionality when rewriting this code in PHP.
#include <iostream> #include <span> #include <vector> struct vec2 { float x = 0.0f, y = 0.0f; constexpr vec2 operator+(vec2 other) const { return vec2{x + other.x, y + other.y}; } constexpr vec2 operator-(vec2 other) const { return vec2{x - other.x, y - other.y}; } }; constexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; } constexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; } constexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; } constexpr bool is_inside(vec2 point, vec2 a, vec2 b) { return (cross(a - b, point) + cross(b, a)) < 0.0f; } constexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) { return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) * (1.0f / cross(a1 - a2, b1 - b2)); } std::vector<vec2> suther_land_hodgman( std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) { if (clip_polygon.empty() || subject_polygon.empty()) { return {}; } std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()}; vec2 p1 = clip_polygon[clip_polygon.size() - 1]; std::vector<vec2> input; for (vec2 p2 : clip_polygon) { input.clear(); input.insert(input.end(), ring.begin(), ring.end()); vec2 s = input[input.size() - 1]; ring.clear(); for (vec2 e : input) { if (is_inside(e, p1, p2)) { if (!is_inside(s, p1, p2)) { ring.push_back(intersection(p1, p2, s, e)); } ring.push_back(e); } else if (is_inside(s, p1, p2)) { ring.push_back(intersection(p1, p2, s, e)); } s = e; } p1 = p2; } return ring; } int main(int argc, char **argv) { vec2 subject_polygon[] = {{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}; vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}}; std::vector<vec2> clipped_polygon = suther_land_hodgman(subject_polygon, clip_polygon); std::cout << "Clipped polygon points:" << std::endl; for (vec2 p : clipped_polygon) { std::cout << "(" << p.x << ", " << p.y << ")" << std::endl; } return EXIT_SUCCESS; }
<?php function clip ($subjectPolygon, $clipPolygon) { function inside ($p, $cp1, $cp2) { return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]); } function intersection ($cp1, $cp2, $e, $s) { $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ]; $dp = [ $s[0] - $e[0], $s[1] - $e[1] ]; $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0]; $n2 = $s[0] * $e[1] - $s[1] * $e[0]; $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]); return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3]; } $outputList = $subjectPolygon; $cp1 = end($clipPolygon); foreach ($clipPolygon as $cp2) { $inputList = $outputList; $outputList = []; $s = end($inputList); foreach ($inputList as $e) { if (inside($e, $cp1, $cp2)) { if (!inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $outputList[] = $e; } else if (inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $s = $e; } $cp1 = $cp2; } return $outputList; } $subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]]; $clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]]; $clippedPolygon = clip($subjectPolygon, $clipPolygon); echo json_encode($clippedPolygon); echo "\n"; ?>
Port the following code from C++ to PHP with equivalent syntax and logic.
FUNCTION MULTIPLY(X, Y) DOUBLE PRECISION MULTIPLY, X, Y
$ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll"); $cstr = $ffi->_strdup("success"); $str = FFI::string($cstr); echo $str; FFI::free($cstr);
Rewrite the snippet below in PHP so it works the same as the original C++ code.
#include <iostream> #include <functional> #include <vector> #include <cstdlib> #include <ctime> template <typename T> std::function<std::vector<T>(T)> s_of_n_creator(int n) { std::vector<T> sample; int i = 0; return [=](T item) mutable { i++; if (i <= n) { sample.push_back(item); } else if (std::rand() % i < n) { sample[std::rand() % n] = item; } return sample; }; } int main() { std::srand(std::time(NULL)); int bin[10] = {0}; for (int trial = 0; trial < 100000; trial++) { auto s_of_n = s_of_n_creator<int>(3); std::vector<int> sample; for (int i = 0; i < 10; i++) sample = s_of_n(i); for (int s : sample) bin[s]++; } for (int x : bin) std::cout << x << std::endl; return 0; }
<?php function s_of_n_creator($n) { $sample = array(); $i = 0; return function($item) use (&$sample, &$i, $n) { $i++; if ($i <= $n) { $sample[] = $item; } else if (rand(0, $i-1) < $n) { $sample[rand(0, $n-1)] = $item; } return $sample; }; } $items = range(0, 9); for ($trial = 0; $trial < 100000; $trial++) { $s_of_n = s_of_n_creator(3); foreach ($items as $item) $sample = $s_of_n($item); foreach ($sample as $s) $bin[$s]++; } print_r($bin); ?>
Change the programming language of this snippet from C++ to PHP without modifying what it does.
#include <iostream> #include <functional> #include <vector> #include <cstdlib> #include <ctime> template <typename T> std::function<std::vector<T>(T)> s_of_n_creator(int n) { std::vector<T> sample; int i = 0; return [=](T item) mutable { i++; if (i <= n) { sample.push_back(item); } else if (std::rand() % i < n) { sample[std::rand() % n] = item; } return sample; }; } int main() { std::srand(std::time(NULL)); int bin[10] = {0}; for (int trial = 0; trial < 100000; trial++) { auto s_of_n = s_of_n_creator<int>(3); std::vector<int> sample; for (int i = 0; i < 10; i++) sample = s_of_n(i); for (int s : sample) bin[s]++; } for (int x : bin) std::cout << x << std::endl; return 0; }
<?php function s_of_n_creator($n) { $sample = array(); $i = 0; return function($item) use (&$sample, &$i, $n) { $i++; if ($i <= $n) { $sample[] = $item; } else if (rand(0, $i-1) < $n) { $sample[rand(0, $n-1)] = $item; } return $sample; }; } $items = range(0, 9); for ($trial = 0; $trial < 100000; $trial++) { $s_of_n = s_of_n_creator(3); foreach ($items as $item) $sample = $s_of_n($item); foreach ($sample as $s) $bin[$s]++; } print_r($bin); ?>
Ensure the translated PHP code behaves exactly like the original C++ snippet.
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl; return 0; }
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
Preserve the algorithm and functionality while converting the code from C++ to PHP.
#include <iostream> int main(int argc, char* argv[]) { std::cout << "This program is named " << argv[0] << std::endl; std::cout << "There are " << argc-1 << " arguments given." << std::endl; for (int i = 1; i < argc; ++i) std::cout << "the argument #" << i << " is " << argv[i] << std::endl; return 0; }
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
Port the following code from C++ to PHP with equivalent syntax and logic.
#include <vector> #include <iostream> int main() { std::vector<int> a(3), b(4); a[0] = 11; a[1] = 12; a[2] = 13; b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24; a.insert(a.end(), b.begin(), b.end()); for (int i = 0; i < a.size(); ++i) std::cout << "a[" << i << "] = " << a[i] << "\n"; }
$arr1 = array(1, 2, 3); $arr2 = array(4, 5, 6); $arr3 = array_merge($arr1, $arr2);
Write the same algorithm in PHP as shown in this C++ implementation.
#include <iostream> #include <string> using namespace std; int main() { long int integer_input; string string_input; cout << "Enter an integer: "; cin >> integer_input; cout << "Enter a string: "; cin >> string_input; return 0; }
#!/usr/bin/php <?php $string = fgets(STDIN); $integer = (int) fgets(STDIN);
Keep all operations the same but rewrite the snippet in PHP.
#include <vector> #include <string> #include <iostream> #include <boost/tuple/tuple.hpp> #include <set> int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & , std::set<int> & , const int ) ; int main( ) { std::vector<boost::tuple<std::string , int , int> > items ; items.push_back( boost::make_tuple( "" , 0 , 0 ) ) ; items.push_back( boost::make_tuple( "map" , 9 , 150 ) ) ; items.push_back( boost::make_tuple( "compass" , 13 , 35 ) ) ; items.push_back( boost::make_tuple( "water" , 153 , 200 ) ) ; items.push_back( boost::make_tuple( "sandwich", 50 , 160 ) ) ; items.push_back( boost::make_tuple( "glucose" , 15 , 60 ) ) ; items.push_back( boost::make_tuple( "tin", 68 , 45 ) ) ; items.push_back( boost::make_tuple( "banana", 27 , 60 ) ) ; items.push_back( boost::make_tuple( "apple" , 39 , 40 ) ) ; items.push_back( boost::make_tuple( "cheese" , 23 , 30 ) ) ; items.push_back( boost::make_tuple( "beer" , 52 , 10 ) ) ; items.push_back( boost::make_tuple( "suntan creme" , 11 , 70 ) ) ; items.push_back( boost::make_tuple( "camera" , 32 , 30 ) ) ; items.push_back( boost::make_tuple( "T-shirt" , 24 , 15 ) ) ; items.push_back( boost::make_tuple( "trousers" , 48 , 10 ) ) ; items.push_back( boost::make_tuple( "umbrella" , 73 , 40 ) ) ; items.push_back( boost::make_tuple( "waterproof trousers" , 42 , 70 ) ) ; items.push_back( boost::make_tuple( "waterproof overclothes" , 43 , 75 ) ) ; items.push_back( boost::make_tuple( "note-case" , 22 , 80 ) ) ; items.push_back( boost::make_tuple( "sunglasses" , 7 , 20 ) ) ; items.push_back( boost::make_tuple( "towel" , 18 , 12 ) ) ; items.push_back( boost::make_tuple( "socks" , 4 , 50 ) ) ; items.push_back( boost::make_tuple( "book" , 30 , 10 ) ) ; const int maximumWeight = 400 ; std::set<int> bestItems ; int bestValue = findBestPack( items , bestItems , maximumWeight ) ; std::cout << "The best value that can be packed in the given knapsack is " << bestValue << " !\n" ; int totalweight = 0 ; std::cout << "The following items should be packed in the knapsack:\n" ; for ( std::set<int>::const_iterator si = bestItems.begin( ) ; si != bestItems.end( ) ; si++ ) { std::cout << (items.begin( ) + *si)->get<0>( ) << "\n" ; totalweight += (items.begin( ) + *si)->get<1>( ) ; } std::cout << "The total weight of all items is " << totalweight << " !\n" ; return 0 ; } int findBestPack( const std::vector<boost::tuple<std::string , int , int> > & items ,std::set<int> & bestItems , const int weightlimit ) { const int n = items.size( ) ; int bestValues [ n ][ weightlimit ] ; std::set<int> solutionSets[ n ][ weightlimit ] ; std::set<int> emptyset ; for ( int i = 0 ; i < n ; i++ ) { for ( int j = 0 ; j < weightlimit ; j++ ) { bestValues[ i ][ j ] = 0 ; solutionSets[ i ][ j ] = emptyset ; } } for ( int i = 0 ; i < n ; i++ ) { for ( int weight = 0 ; weight < weightlimit ; weight++ ) { if ( i == 0 ) bestValues[ i ][ weight ] = 0 ; else { int itemweight = (items.begin( ) + i)->get<1>( ) ; if ( weight < itemweight ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } else { if ( bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) > bestValues[ i - 1 ][ weight ] ) { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight - itemweight ] + (items.begin( ) + i)->get<2>( ) ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight - itemweight ] ; solutionSets[ i ][ weight ].insert( i ) ; } else { bestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ; solutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ; } } } } } bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ; return bestValues[ n - 1 ][ weightlimit - 1 ] ; }
######################################################### # 0-1 Knapsack Problem Solve with memoization optimize and index returns # $w = weight of item # $v = value of item # $i = index # $aW = Available Weight # $m = Memo items array # PHP Translation from Python, Memoization, # and index return functionality added by Brian Berneker # ######################################################### function knapSolveFast2($w, $v, $i, $aW, &$m) { global $numcalls; $numcalls ++; if (isset($m[$i][$aW])) { return array( $m[$i][$aW], $m['picked'][$i][$aW] ); } else { if ($i == 0) { if ($w[$i] <= $aW) { // Will this item fit? $m[$i][$aW] = $v[$i]; // Memo this item $m['picked'][$i][$aW] = array($i); // and the picked item return array($v[$i],array($i)); // Return the value of this item and add it to the picked list } else { $m[$i][$aW] = 0; // Memo zero $m['picked'][$i][$aW] = array(); // and a blank array entry... return array(0,array()); // Return nothing } } list ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m); if ($w[$i] > $aW) { // Does it return too many? $m[$i][$aW] = $without_i; // Memo without including this one $m['picked'][$i][$aW] = $without_PI; // and a blank array entry... return array($without_i, $without_PI); // and return it } else { list ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m); $with_i += $v[$i]; // ..and add the value of this one.. if ($with_i > $without_i) { $res = $with_i; $picked = $with_PI; array_push($picked,$i); } else { $res = $without_i; $picked = $without_PI; } $m[$i][$aW] = $res; // Store it in the memo $m['picked'][$i][$aW] = $picked; // and store the picked item return array ($res,$picked); // and then return it } } } $items4 = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese","beer","suntan cream","camera","t-shirt","trousers","umbrella","waterproof trousers","waterproof overclothes","note-case","sunglasses","towel","socks","book"); $w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30); $v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10); ## Initialize $numcalls = 0; $m = array(); $pickedItems = array(); ## Solve list ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m); # Display Result echo "<b>Items:</b><br>".join(", ",$items4)."<br>"; echo "<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>"; echo "<b>Array Indices:</b><br>".join(",",$pickedItems)."<br>"; echo "<b>Chosen Items:</b><br>"; echo "<table border cellspacing=0>"; echo "<tr><td>Item</td><td>Value</td><td>Weight</td></tr>"; $totalVal = $totalWt = 0; foreach($pickedItems as $key) { $totalVal += $v4[$key]; $totalWt += $w4[$key]; echo "<tr><td>".$items4[$key]."</td><td>".$v4[$key]."</td><td>".$w4[$key]."</td></tr>"; } echo "<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>"; echo "</table><hr>";
Write the same code in PHP as shown below in C++.
#include <functional> #include <algorithm> #include <iostream> #include <vector> #include <cmath> using std::cout; using std::endl; using std::vector; using std::function; using std::transform; using std::back_inserter; typedef function<double(double)> FunType; vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } }; vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } }; template <typename A, typename B, typename C> function<C(A)> compose(function<C(B)> f, function<B(A)> g) { return [f,g](A x) { return f(g(x)); }; } int main() { vector<FunType> composedFuns; auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0}; transform(B.begin(), B.end(), A.begin(), back_inserter(composedFuns), compose<double, double, double>); for (auto num: exNums) for (auto fun: composedFuns) cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl; return 0; }
$compose = function ($f, $g) { return function ($x) use ($f, $g) { return $f($g($x)); }; }; $fn = array('sin', 'cos', function ($x) { return pow($x, 3); }); $inv = array('asin', 'acos', function ($x) { return pow($x, 1/3); }); for ($i = 0; $i < 3; $i++) { $f = $compose($inv[$i], $fn[$i]); echo $f(0.5), PHP_EOL; }
Translate this program into PHP but keep the logic exactly as in C++.
#include <vector> #include <iostream> #include <algorithm> std::vector<int> properDivisors ( int number ) { std::vector<int> divisors ; for ( int i = 1 ; i < number / 2 + 1 ; i++ ) if ( number % i == 0 ) divisors.push_back( i ) ; return divisors ; } int main( ) { std::vector<int> divisors ; unsigned int maxdivisors = 0 ; int corresponding_number = 0 ; for ( int i = 1 ; i < 11 ; i++ ) { divisors = properDivisors ( i ) ; std::cout << "Proper divisors of " << i << ":\n" ; for ( int number : divisors ) { std::cout << number << " " ; } std::cout << std::endl ; divisors.clear( ) ; } for ( int i = 11 ; i < 20001 ; i++ ) { divisors = properDivisors ( i ) ; if ( divisors.size( ) > maxdivisors ) { maxdivisors = divisors.size( ) ; corresponding_number = i ; } divisors.clear( ) ; } std::cout << "Most divisors has " << corresponding_number << " , it has " << maxdivisors << " divisors!\n" ; return 0 ; }
<?php function ProperDivisors($n) { yield 1; $large_divisors = []; for ($i = 2; $i <= sqrt($n); $i++) { if ($n % $i == 0) { yield $i; if ($i*$i != $n) { $large_divisors[] = $n / $i; } } } foreach (array_reverse($large_divisors) as $i) { yield $i; } } assert([1, 2, 4, 5, 10, 20, 25, 50] == iterator_to_array(ProperDivisors(100))); foreach (range(1, 10) as $n) { echo "$n =>"; foreach (ProperDivisors($n) as $divisor) { echo " $divisor"; } echo "\n"; } $divisorsCount = []; for ($i = 1; $i < 20000; $i++) { $divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i; } ksort($divisorsCount); echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n"; echo "They have ", key($divisorsCount), " divisors.\n";
Keep all operations the same but rewrite the snippet in PHP.
#include <iostream> #include <string> #include <iterator> #include <regex> int main() { std::regex re(".* string$"); std::string s = "Hi, I am a string"; if (std::regex_match(s, re)) std::cout << "The string matches.\n"; else std::cout << "Oops - not found?\n"; std::regex re2(" a.*a"); std::smatch match; if (std::regex_search(s, match, re2)) { std::cout << "Matched " << match.length() << " characters starting at " << match.position() << ".\n"; std::cout << "Matched character sequence: \"" << match.str() << "\"\n"; } else { std::cout << "Oops - not found?\n"; } std::string dest_string; std::regex_replace(std::back_inserter(dest_string), s.begin(), s.end(), re2, "'m now a changed"); std::cout << dest_string << std::endl; }
$string = 'I am a string'; # Test if (preg_match('/string$/', $string)) { echo "Ends with 'string'\n"; } # Replace $string = preg_replace('/\ba\b/', 'another', $string); echo "Found 'a' and replace it with 'another', resulting in this string: $string\n";
Preserve the algorithm and functionality while converting the code from C++ to PHP.
#include <unordered_map> #include <string> int main() { std::string keys[] = { "1", "2", "3" }; std::string vals[] = { "a", "b", "c" }; std::unordered_map<std::string, std::string> hash; for( int i = 0 ; i < 3 ; i++ ) hash[ keys[i] ] = vals[i] ; }
$keys = array('a', 'b', 'c'); $values = array(1, 2, 3); $hash = array_combine($keys, $values);
Generate a PHP translation of this C++ snippet without changing its computational steps.
#include <windows.h> #include <string> #include <math.h> using namespace std; const float PI = 3.1415926536f; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; void *pBits; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD* dwpBits; DWORD wb; HANDLE file; GetObject( bmp, sizeof( bitmap ), &bitmap ); dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; infoheader.bmiHeader.biCompression = BI_RGB; infoheader.bmiHeader.biPlanes = 1; infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); infoheader.bmiHeader.biHeight = bitmap.bmHeight; infoheader.bmiHeader.biWidth = bitmap.bmWidth; infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); fileheader.bfType = 0x4D42; fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); CloseHandle( file ); delete [] dwpBits; } HDC getDC() { return hdc; } int getWidth() { return width; } int getHeight() { return height; } private: HBITMAP bmp; HDC hdc; HPEN pen; int width, height; }; class vector2 { public: vector2() { x = y = 0; } vector2( int a, int b ) { x = a; y = b; } void set( int a, int b ) { x = a; y = b; } void rotate( float angle_r ) { float _x = static_cast<float>( x ), _y = static_cast<float>( y ), s = sinf( angle_r ), c = cosf( angle_r ), a = _x * c - _y * s, b = _x * s + _y * c; x = static_cast<int>( a ); y = static_cast<int>( b ); } int x, y; }; class fractalTree { public: fractalTree() { _ang = DegToRadian( 24.0f ); } float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); } void create( myBitmap* bmp ) { _bmp = bmp; float line_len = 130.0f; vector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 ); MoveToEx( _bmp->getDC(), sp.x, sp.y, NULL ); sp.y -= static_cast<int>( line_len ); LineTo( _bmp->getDC(), sp.x, sp.y); drawRL( &sp, line_len, 0, true ); drawRL( &sp, line_len, 0, false ); } private: void drawRL( vector2* sp, float line_len, float a, bool rg ) { line_len *= .75f; if( line_len < 2.0f ) return; MoveToEx( _bmp->getDC(), sp->x, sp->y, NULL ); vector2 r( 0, static_cast<int>( line_len ) ); if( rg ) a -= _ang; else a += _ang; r.rotate( a ); r.x += sp->x; r.y = sp->y - r.y; LineTo( _bmp->getDC(), r.x, r.y ); drawRL( &r, line_len, a, true ); drawRL( &r, line_len, a, false ); } myBitmap* _bmp; float _ang; }; int main( int argc, char* argv[] ) { ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); myBitmap bmp; bmp.create( 640, 512 ); bmp.setPenColor( RGB( 255, 255, 0 ) ); fractalTree tree; tree.create( &bmp ); BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY ); bmp.saveBitmap( "f: system( "pause" ); return 0; }
<?php header("Content-type: image/png"); $width = 512; $height = 512; $img = imagecreatetruecolor($width,$height); $bg = imagecolorallocate($img,255,255,255); imagefilledrectangle($img, 0, 0, $width, $width, $bg); $depth = 8; function drawTree($x1, $y1, $angle, $depth){ global $img; if ($depth != 0){ $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0); $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0); imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0)); drawTree($x2, $y2, $angle - 20, $depth - 1); drawTree($x2, $y2, $angle + 20, $depth - 1); } } drawTree($width/2, $height, -90, $depth); imagepng($img); imagedestroy($img); ?>
Change the programming language of this snippet from C++ to PHP without modifying what it does.
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
<?php function gray_encode($binary){ return $binary ^ ($binary >> 1); } function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; } for($i=0;$i<32;$i++){ $gray_encoded = gray_encode($i); printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); }
Convert the following code from C++ to PHP, ensuring the logic remains intact.
#include <bitset> #include <iostream> #include <string> #include <assert.h> uint32_t gray_encode(uint32_t b) { return b ^ (b >> 1); } uint32_t gray_decode(uint32_t g) { for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1) { if (g & bit) g ^= bit >> 1; } return g; } std::string to_binary(int value) { const std::bitset<32> bs(value); const std::string str(bs.to_string()); const size_t pos(str.find('1')); return pos == std::string::npos ? "0" : str.substr(pos); } int main() { std::cout << "Number\tBinary\tGray\tDecoded\n"; for (uint32_t n = 0; n < 32; ++n) { uint32_t g = gray_encode(n); assert(gray_decode(g) == n); std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n"; } }
<?php function gray_encode($binary){ return $binary ^ ($binary >> 1); } function gray_decode($gray){ $binary = $gray; while($gray >>= 1) $binary ^= $gray; return $binary; } for($i=0;$i<32;$i++){ $gray_encoded = gray_encode($i); printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded)); }
Generate a PHP translation of this C++ snippet without changing its computational steps.
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; enum { unique_count = pip_count * suite_count }; card(suite_type s, pip_type p): value(s + suite_count * p) {} explicit card(unsigned char v = 0): value(v) {} pip_type pip() { return pip_type(value / suite_count); } suite_type suite() { return suite_type(value % suite_count); } private: unsigned char value; }; const char* const pip_names[] = { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace" }; std::ostream& operator<<(std::ostream& os, card::pip_type pip) { return os << pip_names[pip]; } const char* const suite_names[] = { "hearts", "spades", "diamonds", "clubs" }; std::ostream& operator<<(std::ostream& os, card::suite_type suite) { return os << suite_names[suite]; } std::ostream& operator<<(std::ostream& os, card c) { return os << c.pip() << " of " << c.suite(); } class deck { public: deck() { for (int i = 0; i < card::unique_count; ++i) { cards.push_back(card(i)); } } void shuffle() { std::random_shuffle(cards.begin(), cards.end()); } card deal() { card c = cards.front(); cards.pop_front(); return c; } typedef std::deque<card>::const_iterator const_iterator; const_iterator begin() const { return cards.cbegin(); } const_iterator end() const { return cards.cend(); } private: std::deque<card> cards; }; inline std::ostream& operator<<(std::ostream& os, const deck& d) { std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n")); return os; } }
class Card { protected static $suits = array( '♠', '♥', '♦', '♣' ); protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); protected $suit; protected $suitOrder; protected $pip; protected $pipOrder; protected $order; public function __construct( $suit, $pip ) { if( !in_array( $suit, self::$suits ) ) { throw new InvalidArgumentException( 'Invalid suit' ); } if( !in_array( $pip, self::$pips ) ) { throw new InvalidArgumentException( 'Invalid pip' ); } $this->suit = $suit; $this->pip = $pip; } public function getSuit() { return $this->suit; } public function getPip() { return $this->pip; } public function getSuitOrder() { if( !isset( $this->suitOrder ) ) { $this->suitOrder = array_search( $this->suit, self::$suits ); } return $this->suitOrder; } public function getPipOrder() { if( !isset( $this->pipOrder ) ) { $this->pipOrder = array_search( $this->pip, self::$pips ); } return $this->pipOrder; } public function getOrder() { if( !isset( $this->order ) ) { $suitOrder = $this->getSuitOrder(); $pipOrder = $this->getPipOrder(); $this->order = $pipOrder * count( self::$suits ) + $suitOrder; } return $this->order; } public function compareSuit( Card $other ) { return $this->getSuitOrder() - $other->getSuitOrder(); } public function comparePip( Card $other ) { return $this->getPipOrder() - $other->getPipOrder(); } public function compare( Card $other ) { return $this->getOrder() - $other->getOrder(); } public function __toString() { return $this->suit . $this->pip; } public static function getSuits() { return self::$suits; } public static function getPips() { return self::$pips; } } class CardCollection implements Countable, Iterator { protected $cards = array(); protected function __construct( array $cards = array() ) { foreach( $cards as $card ) { $this->addCard( $card ); } } public function count() { return count( $this->cards ); } public function key() { return key( $this->cards ); } public function valid() { return null !== $this->key(); } public function next() { next( $this->cards ); } public function current() { return current( $this->cards ); } public function rewind() { reset( $this->cards ); } public function sort( $comparer = null ) { $comparer = $comparer ?: function( $a, $b ) { return $a->compare( $b ); }; if( !is_callable( $comparer ) ) { throw new InvalidArgumentException( 'Invalid comparer; comparer should be callable' ); } usort( $this->cards, $comparer ); return $this; } public function toString() { return implode( ' ', $this->cards ); } public function __toString() { return $this->toString(); } protected function addCard( Card $card ) { if( in_array( $card, $this->cards ) ) { throw new DomainException( 'Card is already present in this collection' ); } $this->cards[] = $card; } } class Deck extends CardCollection { public function __construct( $shuffled = false ) { foreach( Card::getSuits() as $suit ) { foreach( Card::getPips() as $pip ) { $this->addCard( new Card( $suit, $pip ) ); } } if( $shuffled ) { $this->shuffle(); } } public function deal( $amount = 1, CardCollection $cardCollection = null ) { if( !is_int( $amount ) || $amount < 1 ) { throw new InvalidArgumentException( 'Invalid amount; amount should be an integer, larger than 0' ); } if( $amount > count( $this->cards ) ) { throw new RangeException( 'Invalid amount; requested amount is larger than the amount of available cards' ); } $cards = array_splice( $this->cards, 0, $amount ); $cardCollection = $cardCollection ?: new CardCollection; foreach( $cards as $card ) { $cardCollection->addCard( $card ); } return $cardCollection; } public function shuffle() { shuffle( $this->cards ); } } class Hand extends CardCollection { public function __construct() {} public function play( $position ) { if( !isset( $this->cards[ $position ] ) ) { throw new OutOfBoundsException( 'Invalid position; position is not present in this hand' ); } $result = array_splice( $this->cards, $position, 1 ); return $result[ 0 ]; } }
Translate this program into PHP but keep the logic exactly as in C++.
#include <array> #include <vector> #include <algorithm> #include <iostream> #include <iterator> #include <string> template <typename Array> void demonstrate(Array& array) { array[2] = "Three"; array.at(1) = "Two"; std::reverse(begin(array), end(array)); std::for_each(begin(array), end(array), [](typename Array::value_type const& element) { std::cout << element << ' '; }); std::cout << '\n'; } int main() { auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" }; auto dynamic_array = std::vector<std::string>{ "One", "Four" }; dynamic_array.push_back("Eight"); demonstrate(fixed_size_array); demonstrate(dynamic_array); }
$NumberArray = array(0, 1, 2, 3, 4, 5, 6); $LetterArray = array("a", "b", "c", "d", "e", "f"); $simpleForm = ['apple', 'orange'];
Translate the given C++ code snippet into PHP without altering its behavior.
#include <cstdint> #include <cstdlib> #include <cstdio> static constexpr int32_t bct_low_bits = 0x55555555; static int32_t bct_decrement(int32_t v) { --v; return v ^ (v & (v>>1) & bct_low_bits); } int main (int argc, char *argv[]) { const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3; if (n < 0 || 9 < n) { std::printf("N out of range (use 0..9): %ld\n", long(n)); return 1; } const int32_t size_bct = 1<<(n*2); int32_t y = size_bct; do { y = bct_decrement(y); int32_t x = size_bct; do { x = bct_decrement(x); std::putchar((x & y & bct_low_bits) ? ' ' : '#'); } while (0 < x); std::putchar('\n'); } while (0 < y); return 0; }
<?php function isSierpinskiCarpetPixelFilled($x, $y) { while (($x > 0) or ($y > 0)) { if (($x % 3 == 1) and ($y % 3 == 1)) { return false; } $x /= 3; $y /= 3; } return true; } function sierpinskiCarpet($order) { $size = pow(3, $order); for ($y = 0 ; $y < $size ; $y++) { for ($x = 0 ; $x < $size ; $x++) { echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' '; } echo PHP_EOL; } } for ($order = 0 ; $order <= 3 ; $order++) { echo 'N=', $order, PHP_EOL; sierpinskiCarpet($order); echo PHP_EOL; }
Change the following C++ code into PHP without altering its purpose.
#include <algorithm> #include <iostream> #include <iterator> #include <random> template <typename RandomAccessIterator, typename Predicate> void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end, Predicate p) { std::random_device rd; std::mt19937 generator(rd()); while (!std::is_sorted(begin, end, p)) { std::shuffle(begin, end, generator); } } template <typename RandomAccessIterator> void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) { bogo_sort( begin, end, std::less< typename std::iterator_traits<RandomAccessIterator>::value_type>()); } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bogo_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
function bogosort($l) { while (!in_order($l)) shuffle($l); return $l; } function in_order($l) { for ($i = 1; $i < count($l); $i++) if ($l[$i] < $l[$i-1]) return FALSE; return TRUE; }
Transform the following C++ implementation into PHP, maintaining the same output and logic.
#include <iostream> #include <algorithm> #include <vector> #include <cmath> #include <boost/bind.hpp> #include <iterator> double nextNumber( double number ) { return number + floor( 0.5 + sqrt( number ) ) ; } int main( ) { std::vector<double> non_squares ; typedef std::vector<double>::iterator SVI ; non_squares.reserve( 1000000 ) ; for ( double i = 1.0 ; i < 100001.0 ; i += 1 ) non_squares.push_back( nextNumber( i ) ) ; std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 , std::ostream_iterator<double>(std::cout, " " ) ) ; std::cout << '\n' ; SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) , boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ; if ( found != non_squares.end( ) ) { std::cout << "Found a square number in the sequence!\n" ; std::cout << "It is " << *found << " !\n" ; } else { std::cout << "Up to 1000000, found no square number in the sequence!\n" ; } return 0 ; }
<?php for($i=1;$i<=22;$i++){ echo($i + floor(1/2 + sqrt($i)) . "\n"); } $found_square=False; for($i=1;$i<=1000000;$i++){ $non_square=$i + floor(1/2 + sqrt($i)); if(sqrt($non_square)==intval(sqrt($non_square))){ $found_square=True; } } echo("\n"); if($found_square){ echo("Found a square number, so the formula does not always work."); } else { echo("Up to 1000000, found no square number in the sequence!"); } ?>
Ensure the translated PHP code behaves exactly like the original C++ snippet.
#include <iostream> #include <string> int main() { std::string s = "0123456789"; int const n = 3; int const m = 4; char const c = '2'; std::string const sub = "456"; std::cout << s.substr(n, m)<< "\n"; std::cout << s.substr(n) << "\n"; std::cout << s.substr(0, s.size()-1) << "\n"; std::cout << s.substr(s.find(c), m) << "\n"; std::cout << s.substr(s.find(sub), m) << "\n"; }
<?php $str = 'abcdefgh'; $n = 2; $m = 3; echo substr($str, $n, $m), "\n"; //cde echo substr($str, $n), "\n"; //cdefgh echo substr($str, 0, -1), "\n"; //abcdefg echo substr($str, strpos($str, 'd'), $m), "\n"; //def echo substr($str, strpos($str, 'de'), $m), "\n"; //def ?>
Preserve the algorithm and functionality while converting the code from C++ to PHP.
#include <iostream> bool is_leap_year(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } int main() { for (auto year : {1900, 1994, 1996, 1997, 2000}) { std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n"; } }
<?php function isLeapYear($year) { if ($year % 100 == 0) { return ($year % 400 == 0); } return ($year % 4 == 0); }
Change the following C++ code into PHP without altering its purpose.
#include <string> #include <iostream> using std::string; const char* smallNumbers[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; string spellHundreds(unsigned n) { string res; if (n > 99) { res = smallNumbers[n/100]; res += " hundred"; n %= 100; if (n) res += " and "; } if (n >= 20) { static const char* Decades[] = { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; res += Decades[n/10]; n %= 10; if (n) res += "-"; } if (n < 20 && n > 0) res += smallNumbers[n]; return res; } const char* thousandPowers[] = { " billion", " million", " thousand", "" }; typedef unsigned long Spellable; string spell(Spellable n) { if (n < 20) return smallNumbers[n]; string res; const char** pScaleName = thousandPowers; Spellable scaleFactor = 1000000000; while (scaleFactor > 0) { if (n >= scaleFactor) { Spellable h = n / scaleFactor; res += spellHundreds(h) + *pScaleName; n %= scaleFactor; if (n) res += ", "; } scaleFactor /= 1000; ++pScaleName; } return res; } int main() { #define SPELL_IT(x) std::cout << #x " " << spell(x) << std::endl; SPELL_IT( 99); SPELL_IT( 300); SPELL_IT( 310); SPELL_IT( 1501); SPELL_IT( 12609); SPELL_IT( 512609); SPELL_IT(43112609); SPELL_IT(1234567890); return 0; }
$orderOfMag = array('Hundred', 'Thousand,', 'Million,', 'Billion,', 'Trillion,'); $smallNumbers = array('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'); $decades = array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'); function NumberToEnglish($num, $count = 0){ global $orderOfMag, $smallNumbers, $decades; $isLast = true; $str = ''; if ($num < 0){ $str = 'Negative '; $num = abs($num); } (int) $thisPart = substr((string) $num, -3); if (strlen((string) $num) > 3){ $str .= NumberToEnglish((int) substr((string) $num, 0, strlen((string) $num) - 3), $count + 1); $isLast = false; } if (($count == 0 || $isLast) && ($str == '' || $str == 'Negative ')) $and = ''; else $and = ' and '; if ($thisPart > 99){ $str .= ($isLast ? '' : ' ') . "{$smallNumbers[$thisPart/100]} {$orderOfMag[0]}"; if(($thisPart %= 100) == 0){ $str .= " {$orderOfMag[$count]}"; return $str; } $and = ' and '; // Set up our and string to the word "and" since there is something in the hundreds place of this chunk } if ($thisPart >= 20){ $str .= "{$and}{$decades[$thisPart /10]}"; $and = ' '; // Make sure we don't have any extranious "and"s if(($thisPart %= 10) == 0) return $str . ($count != 0 ? " {$orderOfMag[$count]}" : ''); } if ($thisPart < 20 && $thisPart > 0) return $str . "{$and}{$smallNumbers[(int) $thisPart]} " . ($count != 0 ? $orderOfMag[$count] : ''); elseif ($thisPart == 0 && strlen($thisPart) == 1) return $str . "{$smallNumbers[(int)$thisPart]}"; }
Convert this C++ snippet to PHP and keep its semantics consistent.
#include <iostream> #include <algorithm> #include <string> #include <list> using namespace std; bool cmp(const string& a, const string& b) { return b.length() < a.length(); } void compareAndReportStringsLength(list<string> listOfStrings) { if (!listOfStrings.empty()) { char Q = '"'; string has_length(" has length "); string predicate_max(" and is the longest string"); string predicate_min(" and is the shortest string"); string predicate_ave(" and is neither the longest nor the shortest string"); list<string> ls(listOfStrings); ls.sort(cmp); int max = ls.front().length(); int min = ls.back().length(); for (list<string>::iterator s = ls.begin(); s != ls.end(); s++) { int length = s->length(); string* predicate; if (length == max) predicate = &predicate_max; else if (length == min) predicate = &predicate_min; else predicate = &predicate_ave; cout << Q << *s << Q << has_length << length << *predicate << endl; } } } int main(int argc, char* argv[]) { list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" }; compareAndReportStringsLength(listOfStrings); return EXIT_SUCCESS; }
<?php function retrieveStrings() { if (isset($_POST['input'])) { $strings = explode("\n", $_POST['input']); } else { $strings = ['abcd', '123456789', 'abcdef', '1234567']; } return $strings; } function setInput() { echo join("\n", retrieveStrings()); } function setOutput() { $strings = retrieveStrings(); $strings = array_map('trim', $strings); $strings = array_filter($strings); if (!empty($strings)) { usort($strings, function ($a, $b) { return strlen($b) - strlen($a); }); $max_len = strlen($strings[0]); $min_len = strlen($strings[count($strings) - 1]); foreach ($strings as $s) { $length = strlen($s); if ($length == $max_len) { $predicate = "is the longest string"; } elseif ($length == $min_len) { $predicate = "is the shortest string"; } else { $predicate = "is neither the longest nor the shortest string"; } echo "$s has length $length and $predicate\n"; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <style> div { margin-top: 4ch; margin-bottom: 4ch; } label { display: block; margin-bottom: 1ch; } textarea { display: block; } input { display: block; margin-top: 4ch; margin-bottom: 4ch; } </style> </head> <body> <main> <form action=<?php echo $_SERVER['SCRIPT_NAME'] ?> method="post" accept-charset="utf-8"> <div> <label for="input">Input: </label> <textarea rows='20' cols='80' name='input'><?php setInput(); ?></textarea> </label> </div> <input type="submit" value="press to compare strings"> </input> <div> <label for="Output">Output: </label> <textarea rows='20' cols='80' name='output'><?php setOutput(); ?></textarea> </div> </form> </main> </body> </html>
Ensure the translated PHP code behaves exactly like the original C++ snippet.
#include <time.h> #include <iostream> using namespace std; const int MAX = 126; class shell { public: shell() { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; } void sort( int* a, int count ) { _cnt = count; for( int x = 0; x < 9; x++ ) if( count > _gap[x] ) { _idx = x; break; } sortIt( a ); } private: void sortIt( int* arr ) { bool sorted = false; while( true ) { sorted = true; int st = 0; for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] ) { if( arr[st] > arr[x] ) { swap( arr[st], arr[x] ); sorted = false; } st = x; } if( ++_idx >= 8 ) _idx = 8; if( sorted && _idx == 8 ) break; } } void swap( int& a, int& b ) { int t = a; a = b; b = t; } int _gap[9], _idx, _cnt; }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX]; for( int x = 0; x < MAX; x++ ) arr[x] = rand() % MAX - rand() % MAX; cout << " Before: \n=========\n"; for( int x = 0; x < 7; x++ ) { for( int a = 0; a < 18; a++ ) { cout << arr[x * 18 + a] << " "; } cout << endl; } cout << endl; shell s; s.sort( arr, MAX ); cout << " After: \n========\n"; for( int x = 0; x < 7; x++ ) { for( int a = 0; a < 18; a++ ) { cout << arr[x * 18 + a] << " "; } cout << endl; } cout << endl << endl; return system( "pause" ); }
function shellSort($arr) { $inc = round(count($arr)/2); while($inc > 0) { for($i = $inc; $i < count($arr);$i++){ $temp = $arr[$i]; $j = $i; while($j >= $inc && $arr[$j-$inc] > $temp) { $arr[$j] = $arr[$j - $inc]; $j -= $inc; } $arr[$j] = $temp; } $inc = round($inc/2.2); } return $arr; }
Change the following C++ code into PHP without altering its purpose.
#include <fstream> #include <iostream> int main() { std::ifstream input("filename.txt", std::ios_base::binary); if (!input) { std::cerr << "error: can't open file\n"; return -1; } size_t count[256]; std::fill_n(count, 256, 0); for (char c; input.get(c); ++count[uint8_t(c)]) ; for (size_t i = 0; i < 256; ++i) { if (count[i] && isgraph(i)) { std::cout << char(i) << " = " << count[i] << '\n'; } } }
<?php print_r(array_count_values(str_split(file_get_contents($argv[1])))); ?>
Generate an equivalent PHP version of this C++ code.
#include <cstdlib> #include <string> #include <sstream> std::string s = "12345"; int i; std::istringstream(s) >> i; i++; std::ostringstream oss; if (oss << i) s = oss.str();
$s = "12345"; $s++;
Produce a functionally identical PHP code for the snippet given in C++.
#include <algorithm> #include <iostream> #include <string> std::string stripchars(std::string str, const std::string &chars) { str.erase( std::remove_if(str.begin(), str.end(), [&](char c){ return chars.find(c) != std::string::npos; }), str.end() ); return str; } int main() { std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n'; return 0; }
<?php function stripchars($s, $chars) { return str_replace(str_split($chars), "", $s); } echo stripchars("She was a soul stripper. She took my heart!", "aei"), "\n"; ?>
Transform the following C++ implementation into PHP, maintaining the same output and logic.
#include <algorithm> template<typename ForwardIterator> void permutation_sort(ForwardIterator begin, ForwardIterator end) { while (std::next_permutation(begin, end)) { } }
function inOrder($arr){ for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ return false; } } } return true; } function permute($items, $perms = array( )) { if (empty($items)) { if(inOrder($perms)){ return $perms; } } else { for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); $res = permute($newitems, $newperms); if($res){ return $res; } } } } $arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4); $arr = permute($arr); echo implode(',',$arr);
Port the following code from C++ to PHP with equivalent syntax and logic.
#include <vector> double mean(const std::vector<double>& numbers) { if (numbers.size() == 0) return 0; double sum = 0; for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++) sum += *i; return sum / numbers.size(); }
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
Translate the given C++ code snippet into PHP without altering its behavior.
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> double log2( double number ) { return log( number ) / log( 2 ) ; } int main( int argc , char *argv[ ] ) { std::string teststring( argv[ 1 ] ) ; std::map<char , int> frequencies ; for ( char c : teststring ) frequencies[ c ] ++ ; int numlen = teststring.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent -= freq * log2( freq ) ; } std::cout << "The information content of " << teststring << " is " << infocontent << std::endl ; return 0 ; }
<?php function shannonEntropy($string) { $h = 0.0; $len = strlen($string); foreach (count_chars($string, 1) as $count) { $h -= (double) ($count / $len) * log((double) ($count / $len), 2); } return $h; } $strings = array( '1223334444', '1225554444', 'aaBBcccDDDD', '122333444455555', 'Rosetta Code', '1234567890abcdefghijklmnopqrstuvwxyz', ); foreach ($strings AS $string) { printf( '%36s : %s' . PHP_EOL, $string, number_format(shannonEntropy($string), 6) ); }
Convert the following code from C++ to PHP, ensuring the logic remains intact.
#include <iostream> int main () { std::cout << "Hello world!" << std::endl; }
<?php echo "Hello world!\n"; ?>
Generate an equivalent PHP version of this C++ code.
#include <vector> #include <iterator> #include <algorithm> template<typename InputIterator, typename OutputIterator> OutputIterator forward_difference(InputIterator first, InputIterator last, OutputIterator dest) { if (first == last) return dest; typedef typename std::iterator_traits<InputIterator>::value_type value_type; value_type temp = *first++; while (first != last) { value_type temp2 = *first++; *dest++ = temp2 - temp; temp = temp2; } return dest; } template<typename InputIterator, typename OutputIterator> OutputIterator nth_forward_difference(int order, InputIterator first, InputIterator last, OutputIterator dest) { if (order == 0) return std::copy(first, last, dest); if (order == 1) return forward_difference(first, last, dest); typedef typename std::iterator_traits<InputIterator>::value_type value_type; std::vector<value_type> temp_storage; forward_difference(first, last, std::back_inserter(temp_storage)); typename std::vector<value_type>::iterator begin = temp_storage.begin(), end = temp_storage.end(); for (int i = 1; i < order-1; ++i) end = forward_difference(begin, end, begin); return forward_difference(begin, end, dest); } #include <iostream> int main() { double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 }; std::vector<double> dest; nth_forward_difference(1, array, array+10, std::back_inserter(dest)); std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; double* end = nth_forward_difference(3, array, array+10, array); for (double* p = array; p < end; ++p) std::cout << *p << " "; std::cout << std::endl; return 0; }
<?php function forwardDiff($anArray, $times = 1) { if ($times <= 0) { return $anArray; } for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { $accumilation[] = $anArray[$i] - $anArray[$i - 1]; } if ($times === 1) { return $accumilation; } return forwardDiff($accumilation, $times - 1); } class ForwardDiffExample extends PweExample { function _should_run_empty_array_for_single_elem() { $expected = array($this->rand()->int()); $this->spec(forwardDiff($expected))->shouldEqual(array()); } function _should_give_diff_of_two_elem_as_single_elem() { $twoNums = array($this->rand()->int(), $this->rand()->int()); $expected = array($twoNums[1] - $twoNums[0]); $this->spec(forwardDiff($twoNums))->shouldEqual($expected); } function _should_compute_correct_forward_diff_for_longer_arrays() { $diffInput = array(10, 2, 9, 6, 5); $expected = array(-8, 7, -3, -1); $this->spec(forwardDiff($diffInput))->shouldEqual($expected); } function _should_apply_more_than_once_if_specified() { $diffInput = array(4, 6, 9, 3, 4); $expectedAfter1 = array(2, 3, -6, 1); $expectedAfter2 = array(1, -9, 7); $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1); $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2); } function _should_return_array_unaltered_if_no_times() { $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected); } }
Please provide an equivalent version of this Python code in Java.
def bitwise_built_ins(width, a, b): mask = (1 << width) - 1 print(f) def rotr(width, a, n): "Rotate a, n times to the right" if n < 0: return rotl(width, a, -n) elif n == 0: return a else: mask = (1 << width) - 1 a, n = a & mask, n % width return ((a >> n) | ((a & ((1 << n) - 1)) << (width - n))) def rotl(width, a, n): "Rotate a, n times to the left" if n < 0: return rotr(width, a, -n) elif n == 0: return a else: mask = (1 << width) - 1 a, n = a & mask, n % width return (((a << n) & mask) | (a >> (width - n))) def asr(width, a, n): "Arithmetic shift a, n times to the right. (sign preserving)." mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1) if n < 0: return (a << -n) & mask elif n == 0: return a elif n >= width: return mask if a & top_bit_mask else 0 else: a = a & mask if a & top_bit_mask: signs = (1 << n) - 1 return a >> n | (signs << width - n) else: return a >> n def helper_funcs(width, a): mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1) aa = a | top_bit_mask print(f) if __name__ == '__main__': bitwise_built_ins(8, 27, 125) helper_funcs(8, 27)
module BitwiseOps { @Inject Console console; void run() { for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF]) { static String hex(Int64 n) { return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString(); } console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}): | {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)} | {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)} | {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)} | NOT {hex(n1)} = {hex(~n1)} | left shift {hex(n1)} by {n2} = {hex(n1 << n2)} | right shift {hex(n1)} by {n2} = {hex(n1 >> n2)} | right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)} | left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))} | right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))} | leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)} | rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)} | leading zero count of {hex(n1)} = {n1.leadingZeroCount} | trailing zero count of {hex(n1)} = {n1.trailingZeroCount} | bit count (aka "population") of {hex(n1)} = {n1.bitCount} | reversed bits of {hex(n1)} = {hex(n1.reverseBits())} | reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())} | ); } } }
Convert this Python snippet to Java and keep its semantics consistent.
l = 3 ints = 13 def setup(): size(700, 600) background(0, 0, 255) translate(150, 100) stroke(255) turn_left(l, ints) turn_right(l, ints) def turn_right(l, ints): if ints == 0: line(0, 0, 0, -l) translate(0, -l) else: turn_left(l, ints - 1) rotate(radians(90)) turn_right(l, ints - 1) def turn_left(l, ints): if ints == 0: line(0, 0, 0, -l) translate(0, -l) else: turn_left(l, ints - 1) rotate(radians(-90)) turn_right(l, ints - 1)
import java.awt.Color; import java.awt.Graphics; import java.util.*; import javax.swing.JFrame; public class DragonCurve extends JFrame { private List<Integer> turns; private double startingAngle, side; public DragonCurve(int iter) { super("Dragon Curve"); setBounds(100, 100, 800, 600); setDefaultCloseOperation(EXIT_ON_CLOSE); turns = getSequence(iter); startingAngle = -iter * (Math.PI / 4); side = 400 / Math.pow(2, iter / 2.); } public List<Integer> getSequence(int iterations) { List<Integer> turnSequence = new ArrayList<Integer>(); for (int i = 0; i < iterations; i++) { List<Integer> copy = new ArrayList<Integer>(turnSequence); Collections.reverse(copy); turnSequence.add(1); for (Integer turn : copy) { turnSequence.add(-turn); } } return turnSequence; } @Override public void paint(Graphics g) { g.setColor(Color.BLACK); double angle = startingAngle; int x1 = 230, y1 = 350; int x2 = x1 + (int) (Math.cos(angle) * side); int y2 = y1 + (int) (Math.sin(angle) * side); g.drawLine(x1, y1, x2, y2); x1 = x2; y1 = y2; for (Integer turn : turns) { angle += turn * (Math.PI / 2); x2 = x1 + (int) (Math.cos(angle) * side); y2 = y1 + (int) (Math.sin(angle) * side); g.drawLine(x1, y1, x2, y2); x1 = x2; y1 = y2; } } public static void main(String[] args) { new DragonCurve(14).setVisible(true); } }
Translate the given Python code snippet into Java without altering its behavior.
for line in lines open('input.txt'): print line
import java.io.BufferedReader; import java.io.FileReader; public class ReadFileByLines { private static void processLine(int lineNo, String line) { } public static void main(String[] args) { for (String filename : args) { BufferedReader br = null; FileReader fr = null; try { fr = new FileReader(filename); br = new BufferedReader(fr); String line; int lineNo = 0; while ((line = br.readLine()) != null) { processLine(++lineNo, line); } } catch (Exception x) { x.printStackTrace(); } finally { if (fr != null) { try {br.close();} catch (Exception ignoreMe) {} try {fr.close();} catch (Exception ignoreMe) {} } } } } }
Port the provided Python code into Java while preserving the original functionality.
def insert(anchor, new): new.next = anchor.next new.prev = anchor anchor.next.prev = new anchor.next = new
import java.util.LinkedList; @SuppressWarnings("serial") public class DoublyLinkedListInsertion<T> extends LinkedList<T> { public static void main(String[] args) { DoublyLinkedListInsertion<String> list = new DoublyLinkedListInsertion<String>(); list.addFirst("Add First 1"); list.addFirst("Add First 2"); list.addFirst("Add First 3"); list.addFirst("Add First 4"); list.addFirst("Add First 5"); traverseList(list); list.addAfter("Add First 3", "Add New"); traverseList(list); } public void addAfter(T after, T element) { int index = indexOf(after); if ( index >= 0 ) { add(index + 1, element); } else { addLast(element); } } private static void traverseList(LinkedList<String> list) { System.out.println("Traverse List:"); for ( int i = 0 ; i < list.size() ; i++ ) { System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i)); } System.out.println(); } }
Write a version of this Python function in Java with identical behavior.
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def digit_check(n): if len(str(n))<2: return True else: for digit in str(n): if not is_prime(int(digit)): return False return True def sequence(max_n=None): ii = 0 n = 0 while True: ii += 1 if is_prime(ii): if max_n is not None: if n>max_n: break if digit_check(ii): n += 1 yield ii if __name__ == '__main__': generator = sequence(100) for index, item in zip(range(1, 16), generator): print(index, item) for index, item in zip(range(16, 100), generator): pass print(100, generator.__next__())
public class SmarandachePrimeDigitalSequence { public static void main(String[] args) { long s = getNextSmarandache(7); System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 "); for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { System.out.printf("%d ", s); count++; } } System.out.printf("%n%n"); for (int i = 2 ; i <=5 ; i++ ) { long n = (long) Math.pow(10, i); System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n)); } } private static final long getSmarandachePrime(long n) { if ( n < 10 ) { switch ((int) n) { case 1: return 2; case 2: return 3; case 3: return 5; case 4: return 7; } } long s = getNextSmarandache(7); long result = 0; for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { count++; result = s; } } return result; } private static final boolean isPrime(long test) { if ( test % 2 == 0 ) return false; for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) { if ( test % i == 0 ) { return false; } } return true; } private static long getNextSmarandache(long n) { if ( n % 10 == 3 ) { return n+4; } long retVal = n-4; int k = 0; while ( n % 10 == 7 ) { k++; n /= 10; } long digit = n % 10; long coeff = (digit == 2 ? 1 : 2); retVal += coeff * Math.pow(10, k); while ( k > 1 ) { retVal -= 5 * Math.pow(10, k-1); k--; } return retVal; } }
Translate the given Python code snippet into Java without altering its behavior.
def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs)) def is_prime(n): return len(divisors(n)) == 2 def digit_check(n): if len(str(n))<2: return True else: for digit in str(n): if not is_prime(int(digit)): return False return True def sequence(max_n=None): ii = 0 n = 0 while True: ii += 1 if is_prime(ii): if max_n is not None: if n>max_n: break if digit_check(ii): n += 1 yield ii if __name__ == '__main__': generator = sequence(100) for index, item in zip(range(1, 16), generator): print(index, item) for index, item in zip(range(16, 100), generator): pass print(100, generator.__next__())
public class SmarandachePrimeDigitalSequence { public static void main(String[] args) { long s = getNextSmarandache(7); System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 "); for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { System.out.printf("%d ", s); count++; } } System.out.printf("%n%n"); for (int i = 2 ; i <=5 ; i++ ) { long n = (long) Math.pow(10, i); System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n)); } } private static final long getSmarandachePrime(long n) { if ( n < 10 ) { switch ((int) n) { case 1: return 2; case 2: return 3; case 3: return 5; case 4: return 7; } } long s = getNextSmarandache(7); long result = 0; for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) { if ( isPrime(s) ) { count++; result = s; } } return result; } private static final boolean isPrime(long test) { if ( test % 2 == 0 ) return false; for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) { if ( test % i == 0 ) { return false; } } return true; } private static long getNextSmarandache(long n) { if ( n % 10 == 3 ) { return n+4; } long retVal = n-4; int k = 0; while ( n % 10 == 7 ) { k++; n /= 10; } long digit = n % 10; long coeff = (digit == 2 ? 1 : 2); retVal += coeff * Math.pow(10, k); while ( k > 1 ) { retVal -= 5 * Math.pow(10, k-1); k--; } return retVal; } }
Convert this Python snippet to Java and keep its semantics consistent.
import random def partition(vector, left, right, pivotIndex): pivotValue = vector[pivotIndex] vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex] storeIndex = left for i in range(left, right): if vector[i] < pivotValue: vector[storeIndex], vector[i] = vector[i], vector[storeIndex] storeIndex += 1 vector[right], vector[storeIndex] = vector[storeIndex], vector[right] return storeIndex def _select(vector, left, right, k): "Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive." while True: pivotIndex = random.randint(left, right) pivotNewIndex = partition(vector, left, right, pivotIndex) pivotDist = pivotNewIndex - left if pivotDist == k: return vector[pivotNewIndex] elif k < pivotDist: right = pivotNewIndex - 1 else: k -= pivotDist + 1 left = pivotNewIndex + 1 def select(vector, k, left=None, right=None): if left is None: left = 0 lv1 = len(vector) - 1 if right is None: right = lv1 assert vector and k >= 0, "Either null vector or k < 0 " assert 0 <= left <= lv1, "left is out of range" assert left <= right <= lv1, "right is out of range" return _select(vector, left, right, k) if __name__ == '__main__': v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] print([select(v, i) for i in range(10)])
import java.util.Random; public class QuickSelect { private static <E extends Comparable<? super E>> int partition(E[] arr, int left, int right, int pivot) { E pivotVal = arr[pivot]; swap(arr, pivot, right); int storeIndex = left; for (int i = left; i < right; i++) { if (arr[i].compareTo(pivotVal) < 0) { swap(arr, i, storeIndex); storeIndex++; } } swap(arr, right, storeIndex); return storeIndex; } private static <E extends Comparable<? super E>> E select(E[] arr, int n) { int left = 0; int right = arr.length - 1; Random rand = new Random(); while (right >= left) { int pivotIndex = partition(arr, left, right, rand.nextInt(right - left + 1) + left); if (pivotIndex == n) { return arr[pivotIndex]; } else if (pivotIndex < n) { left = pivotIndex + 1; } else { right = pivotIndex - 1; } } return null; } private static void swap(Object[] arr, int i1, int i2) { if (i1 != i2) { Object temp = arr[i1]; arr[i1] = arr[i2]; arr[i2] = temp; } } public static void main(String[] args) { for (int i = 0; i < 10; i++) { Integer[] input = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; System.out.print(select(input, i)); if (i < 9) System.out.print(", "); } System.out.println(); } }
Ensure the translated Java code behaves exactly like the original Python snippet.
i = int('1a',16)
public static long backToTen(String num, int oldBase){ return Long.parseLong(num, oldBase); } public static String tenToBase(long num, int newBase){ return Long.toString(num, newBase); }
Port the following code from Python to Java with equivalent syntax and logic.
from pathlib import Path for path in Path('.').rglob('*.*'): print(path)
import java.io.File; public class MainEntry { public static void main(String[] args) { walkin(new File("/home/user")); } public static void walkin(File dir) { String pattern = ".mp3"; File listFile[] = dir.listFiles(); if (listFile != null) { for (int i=0; i<listFile.length; i++) { if (listFile[i].isDirectory()) { walkin(listFile[i]); } else { if (listFile[i].getName().endsWith(pattern)) { System.out.println(listFile[i].getPath()); } } } } } }
Produce a functionally identical Java code for the snippet given in Python.
from collections import defaultdict states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", ] states = sorted(set(states)) smap = defaultdict(list) for i, s1 in enumerate(states[:-1]): for s2 in states[i + 1:]: smap["".join(sorted(s1 + s2))].append(s1 + " + " + s2) for pairs in sorted(smap.itervalues()): if len(pairs) > 1: print " = ".join(pairs)
import java.util.*; import java.util.stream.*; public class StateNamePuzzle { static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory",}; public static void main(String[] args) { solve(Arrays.asList(states)); } static void solve(List<String> input) { Map<String, String> orig = input.stream().collect(Collectors.toMap( s -> s.replaceAll("\\s", "").toLowerCase(), s -> s, (s, a) -> s)); input = new ArrayList<>(orig.keySet()); Map<String, List<String[]>> map = new HashMap<>(); for (int i = 0; i < input.size() - 1; i++) { String pair0 = input.get(i); for (int j = i + 1; j < input.size(); j++) { String[] pair = {pair0, input.get(j)}; String s = pair0 + pair[1]; String key = Arrays.toString(s.chars().sorted().toArray()); List<String[]> val = map.getOrDefault(key, new ArrayList<>()); val.add(pair); map.put(key, val); } } map.forEach((key, list) -> { for (int i = 0; i < list.size() - 1; i++) { String[] a = list.get(i); for (int j = i + 1; j < list.size(); j++) { String[] b = list.get(j); if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4) continue; System.out.printf("%s + %s = %s + %s %n", orig.get(a[0]), orig.get(a[1]), orig.get(b[0]), orig.get(b[1])); } } }); } }
Convert this Python block to Java, preserving its control flow and logic.
>>> s = 'The quick brown fox jumps over the lazy dog' >>> import zlib >>> hex(zlib.crc32(s)) '0x414fa339' >>> import binascii >>> hex(binascii.crc32(s)) '0x414fa339'
import java.util.zip.* ; public class CRCMaker { public static void main( String[ ] args ) { String toBeEncoded = new String( "The quick brown fox jumps over the lazy dog" ) ; CRC32 myCRC = new CRC32( ) ; myCRC.update( toBeEncoded.getBytes( ) ) ; System.out.println( "The CRC-32 value is : " + Long.toHexString( myCRC.getValue( ) ) + " !" ) ; } }
Produce a functionally identical Java code for the snippet given in Python.
csvtxt = from cgi import escape def _row2tr(row, attr=None): cols = escape(row).split(',') return ('<TR>' + ''.join('<TD>%s</TD>' % data for data in cols) + '</TR>') def csv2html(txt): htmltxt = '<TABLE summary="csv2html program output">\n' for rownum, row in enumerate(txt.split('\n')): htmlrow = _row2tr(row) htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow htmltxt += htmlrow htmltxt += '</TABLE>\n' return htmltxt htmltxt = csv2html(csvtxt) print(htmltxt)
grammar csv2html; dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ; header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");}; body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");}; row : field ',' field '\r'? '\n'; field : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");}; Field : ~[,\n\r]+;
Write a version of this Python function in Java with identical behavior.
csvtxt = from cgi import escape def _row2tr(row, attr=None): cols = escape(row).split(',') return ('<TR>' + ''.join('<TD>%s</TD>' % data for data in cols) + '</TR>') def csv2html(txt): htmltxt = '<TABLE summary="csv2html program output">\n' for rownum, row in enumerate(txt.split('\n')): htmlrow = _row2tr(row) htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow htmltxt += htmlrow htmltxt += '</TABLE>\n' return htmltxt htmltxt = csv2html(csvtxt) print(htmltxt)
grammar csv2html; dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ; header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");}; body : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");}; row : field ',' field '\r'? '\n'; field : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");}; Field : ~[,\n\r]+;
Produce a language-to-language conversion: from Python to Java, same semantics.
class MyClass: name2 = 2 def __init__(self): self.name1 = 0 def someMethod(self): self.name1 = 1 MyClass.name2 = 3 myclass = MyClass() class MyOtherClass: count = 0 def __init__(self, name, gender="Male", age=None): MyOtherClass.count += 1 self.name = name self.gender = gender if age is not None: self.age = age def __del__(self): MyOtherClass.count -= 1 person1 = MyOtherClass("John") print person1.name, person1.gender print person1.age person2 = MyOtherClass("Jane", "Female", 23) print person2.name, person2.gender, person2.age
public class MyClass{ private int variable; public MyClass(){ } public void someMethod(){ this.variable = 1; } }
Convert this Python block to Java, preserving its control flow and logic.
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
public class Kaprekar { private static String[] splitAt(String str, int idx){ String[] ans = new String[2]; ans[0] = str.substring(0, idx); if(ans[0].equals("")) ans[0] = "0"; ans[1] = str.substring(idx); return ans; } public static void main(String[] args){ int count = 0; int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10; for(long i = 1; i <= 1000000; i++){ String sqrStr = Long.toString(i * i, base); for(int j = 0; j < sqrStr.length() / 2 + 1; j++){ String[] parts = splitAt(sqrStr, j); long firstNum = Long.parseLong(parts[0], base); long secNum = Long.parseLong(parts[1], base); if(secNum == 0) break; if(firstNum + secNum == i){ System.out.println(i + "\t" + Long.toString(i, base) + "\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]); count++; break; } } } System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base); } }
Port the following code from Python to Java with equivalent syntax and logic.
>>> def k(n): n2 = str(n**2) for i in range(len(n2)): a, b = int(n2[:i] or 0), int(n2[i:]) if b and a + b == n: return n >>> [x for x in range(1,10000) if k(x)] [1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999] >>> len([x for x in range(1,1000000) if k(x)]) 54 >>>
public class Kaprekar { private static String[] splitAt(String str, int idx){ String[] ans = new String[2]; ans[0] = str.substring(0, idx); if(ans[0].equals("")) ans[0] = "0"; ans[1] = str.substring(idx); return ans; } public static void main(String[] args){ int count = 0; int base = (args.length > 0) ? Integer.parseInt(args[0]) : 10; for(long i = 1; i <= 1000000; i++){ String sqrStr = Long.toString(i * i, base); for(int j = 0; j < sqrStr.length() / 2 + 1; j++){ String[] parts = splitAt(sqrStr, j); long firstNum = Long.parseLong(parts[0], base); long secNum = Long.parseLong(parts[1], base); if(secNum == 0) break; if(firstNum + secNum == i){ System.out.println(i + "\t" + Long.toString(i, base) + "\t" + sqrStr + "\t" + parts[0] + " + " + parts[1]); count++; break; } } } System.out.println(count + " Kaprekar numbers < 1000000 (base 10) in base "+base); } }
Change the following Python code into Java without altering its purpose.
def compress(uncompressed): dict_size = 256 dictionary = dict((chr(i), i) for i in range(dict_size)) w = "" result = [] for c in uncompressed: wc = w + c if wc in dictionary: w = wc else: result.append(dictionary[w]) dictionary[wc] = dict_size dict_size += 1 w = c if w: result.append(dictionary[w]) return result def decompress(compressed): from io import StringIO dict_size = 256 dictionary = dict((i, chr(i)) for i in range(dict_size)) result = StringIO() w = chr(compressed.pop(0)) result.write(w) for k in compressed: if k in dictionary: entry = dictionary[k] elif k == dict_size: entry = w + w[0] else: raise ValueError('Bad compressed k: %s' % k) result.write(entry) dictionary[dict_size] = w + entry[0] dict_size += 1 w = entry return result.getvalue() compressed = compress('TOBEORNOTTOBEORTOBEORNOT') print (compressed) decompressed = decompress(compressed) print (decompressed)
import java.util.*; public class LZW { public static List<Integer> compress(String uncompressed) { int dictSize = 256; Map<String,Integer> dictionary = new HashMap<String,Integer>(); for (int i = 0; i < 256; i++) dictionary.put("" + (char)i, i); String w = ""; List<Integer> result = new ArrayList<Integer>(); for (char c : uncompressed.toCharArray()) { String wc = w + c; if (dictionary.containsKey(wc)) w = wc; else { result.add(dictionary.get(w)); dictionary.put(wc, dictSize++); w = "" + c; } } if (!w.equals("")) result.add(dictionary.get(w)); return result; } public static String decompress(List<Integer> compressed) { int dictSize = 256; Map<Integer,String> dictionary = new HashMap<Integer,String>(); for (int i = 0; i < 256; i++) dictionary.put(i, "" + (char)i); String w = "" + (char)(int)compressed.remove(0); StringBuffer result = new StringBuffer(w); for (int k : compressed) { String entry; if (dictionary.containsKey(k)) entry = dictionary.get(k); else if (k == dictSize) entry = w + w.charAt(0); else throw new IllegalArgumentException("Bad compressed k: " + k); result.append(entry); dictionary.put(dictSize++, w + entry.charAt(0)); w = entry; } return result.toString(); } public static void main(String[] args) { List<Integer> compressed = compress("TOBEORNOTTOBEORTOBEORNOT"); System.out.println(compressed); String decompressed = decompress(compressed); System.out.println(decompressed); } }
Port the provided Python code into Java while preserving the original functionality.
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
import java.util.*; class Hofstadter { private static List<Integer> getSequence(int rlistSize, int slistSize) { List<Integer> rlist = new ArrayList<Integer>(); List<Integer> slist = new ArrayList<Integer>(); Collections.addAll(rlist, 1, 3, 7); Collections.addAll(slist, 2, 4, 5, 6); List<Integer> list = (rlistSize > 0) ? rlist : slist; int targetSize = (rlistSize > 0) ? rlistSize : slistSize; while (list.size() > targetSize) list.remove(list.size() - 1); while (list.size() < targetSize) { int lastIndex = rlist.size() - 1; int lastr = rlist.get(lastIndex).intValue(); int r = lastr + slist.get(lastIndex).intValue(); rlist.add(Integer.valueOf(r)); for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++) slist.add(Integer.valueOf(s)); } return list; } public static int ffr(int n) { return getSequence(n, 0).get(n - 1).intValue(); } public static int ffs(int n) { return getSequence(0, n).get(n - 1).intValue(); } public static void main(String[] args) { System.out.print("R():"); for (int n = 1; n <= 10; n++) System.out.print(" " + ffr(n)); System.out.println(); Set<Integer> first40R = new HashSet<Integer>(); for (int n = 1; n <= 40; n++) first40R.add(Integer.valueOf(ffr(n))); Set<Integer> first960S = new HashSet<Integer>(); for (int n = 1; n <= 960; n++) first960S.add(Integer.valueOf(ffs(n))); for (int i = 1; i <= 1000; i++) { Integer n = Integer.valueOf(i); if (first40R.contains(n) == first960S.contains(n)) System.out.println("Integer " + i + " either in both or neither set"); } System.out.println("Done"); } }
Port the following code from Python to Java with equivalent syntax and logic.
def ffr(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffr.r[n] except IndexError: r, s = ffr.r, ffs.s ffr_n_1 = ffr(n-1) lastr = r[-1] s += list(range(s[-1] + 1, lastr)) if s[-1] < lastr: s += [lastr + 1] len_s = len(s) ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1] ans = ffr_n_1 + ffs_n_1 r.append(ans) return ans ffr.r = [None, 1] def ffs(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return ffs.s[n] except IndexError: r, s = ffr.r, ffs.s for i in range(len(r), n+2): ffr(i) if len(s) > n: return s[n] raise Exception("Whoops!") ffs.s = [None, 2] if __name__ == '__main__': first10 = [ffr(i) for i in range(1,11)] assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)" print("ffr(n) for n = [1..10] is", first10) bin = [None] + [0]*1000 for i in range(40, 0, -1): bin[ffr(i)] += 1 for i in range(960, 0, -1): bin[ffs(i)] += 1 if all(b == 1 for b in bin[1:1000]): print("All Integers 1..1000 found OK") else: print("All Integers 1..1000 NOT found only once: ERROR")
import java.util.*; class Hofstadter { private static List<Integer> getSequence(int rlistSize, int slistSize) { List<Integer> rlist = new ArrayList<Integer>(); List<Integer> slist = new ArrayList<Integer>(); Collections.addAll(rlist, 1, 3, 7); Collections.addAll(slist, 2, 4, 5, 6); List<Integer> list = (rlistSize > 0) ? rlist : slist; int targetSize = (rlistSize > 0) ? rlistSize : slistSize; while (list.size() > targetSize) list.remove(list.size() - 1); while (list.size() < targetSize) { int lastIndex = rlist.size() - 1; int lastr = rlist.get(lastIndex).intValue(); int r = lastr + slist.get(lastIndex).intValue(); rlist.add(Integer.valueOf(r)); for (int s = lastr + 1; (s < r) && (list.size() < targetSize); s++) slist.add(Integer.valueOf(s)); } return list; } public static int ffr(int n) { return getSequence(n, 0).get(n - 1).intValue(); } public static int ffs(int n) { return getSequence(0, n).get(n - 1).intValue(); } public static void main(String[] args) { System.out.print("R():"); for (int n = 1; n <= 10; n++) System.out.print(" " + ffr(n)); System.out.println(); Set<Integer> first40R = new HashSet<Integer>(); for (int n = 1; n <= 40; n++) first40R.add(Integer.valueOf(ffr(n))); Set<Integer> first960S = new HashSet<Integer>(); for (int n = 1; n <= 960; n++) first960S.add(Integer.valueOf(ffs(n))); for (int i = 1; i <= 1000; i++) { Integer n = Integer.valueOf(i); if (first40R.contains(n) == first960S.contains(n)) System.out.println("Integer " + i + " either in both or neither set"); } System.out.println("Done"); } }
Rewrite the snippet below in Java so it works the same as the original Python code.
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
public class MagicSquare { public static void main(String[] args) { int n = 5; for (int[] row : magicSquareOdd(n)) { for (int x : row) System.out.format("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int base) { if (base % 2 == 0 || base < 3) throw new IllegalArgumentException("base must be odd and > 2"); int[][] grid = new int[base][base]; int r = 0, number = 0; int size = base * base; int c = base / 2; while (number++ < size) { grid[r][c] = number; if (r == 0) { if (c == base - 1) { r++; } else { r = base - 1; c++; } } else { if (c == base - 1) { r--; c = 0; } else { if (grid[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } } } return grid; } }
Port the provided Python code into Java while preserving the original functionality.
>>> def magic(n): for row in range(1, n + 1): print(' '.join('%*i' % (len(str(n**2)), cell) for cell in (n * ((row + col - 1 + n // 2) % n) + ((row + 2 * col - 2) % n) + 1 for col in range(1, n + 1)))) print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2)) >>> for n in (5, 3, 7): print('\nOrder %i\n=======' % n) magic(n) Order 5 ======= 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 All sum to magic number 65 Order 3 ======= 8 1 6 3 5 7 4 9 2 All sum to magic number 15 Order 7 ======= 30 39 48 1 10 19 28 38 47 7 9 18 27 29 46 6 8 17 26 35 37 5 14 16 25 34 36 45 13 15 24 33 42 44 4 21 23 32 41 43 3 12 22 31 40 49 2 11 20 All sum to magic number 175 >>>
public class MagicSquare { public static void main(String[] args) { int n = 5; for (int[] row : magicSquareOdd(n)) { for (int x : row) System.out.format("%2s ", x); System.out.println(); } System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2); } public static int[][] magicSquareOdd(final int base) { if (base % 2 == 0 || base < 3) throw new IllegalArgumentException("base must be odd and > 2"); int[][] grid = new int[base][base]; int r = 0, number = 0; int size = base * base; int c = base / 2; while (number++ < size) { grid[r][c] = number; if (r == 0) { if (c == base - 1) { r++; } else { r = base - 1; c++; } } else { if (c == base - 1) { r--; c = 0; } else { if (grid[r - 1][c + 1] == 0) { r--; c++; } else { r++; } } } } return grid; } }
Translate this program into Java but keep the logic exactly as in Python.
from itertools import chain, count, islice from operator import itemgetter from math import gcd from matplotlib import pyplot def yellowstone(): def relativelyPrime(a): return lambda b: 1 == gcd(a, b) def nextWindow(triple): p2, p1, rest = triple [rp2, rp1] = map(relativelyPrime, [p2, p1]) def match(xxs): x, xs = uncons(xxs)['Just'] return (x, xs) if rp1(x) and not rp2(x) else ( second(cons(x))( match(xs) ) ) n, residue = match(rest) return (p1, n, residue) return chain( range(1, 3), map( itemgetter(1), iterate(nextWindow)( (2, 3, count(4)) ) ) ) def main(): print(showList( take(30)(yellowstone()) )) pyplot.plot( take(100)(yellowstone()) ) pyplot.xlabel(main.__doc__) pyplot.show() def Just(x): return {'type': 'Maybe', 'Nothing': False, 'Just': x} def Nothing(): return {'type': 'Maybe', 'Nothing': True} def cons(x): return lambda xs: [x] + xs if ( isinstance(xs, list) ) else x + xs if ( isinstance(xs, str) ) else chain([x], xs) def iterate(f): def go(x): v = x while True: yield v v = f(v) return go def second(f): return lambda xy: (xy[0], f(xy[1])) def showList(xs): return '[' + ','.join(repr(x) for x in xs) + ']' def take(n): return lambda xs: ( xs[0:n] if isinstance(xs, (list, tuple)) else list(islice(xs, n)) ) def uncons(xs): if isinstance(xs, list): return Just((xs[0], xs[1:])) if xs else Nothing() else: nxt = take(1)(xs) return Just((nxt[0], xs)) if nxt else Nothing() if __name__ == '__main__': main()
import java.util.ArrayList; import java.util.List; public class YellowstoneSequence { public static void main(String[] args) { System.out.printf("First 30 values in the yellowstone sequence:%n%s%n", yellowstoneSequence(30)); } private static List<Integer> yellowstoneSequence(int sequenceCount) { List<Integer> yellowstoneList = new ArrayList<Integer>(); yellowstoneList.add(1); yellowstoneList.add(2); yellowstoneList.add(3); int num = 4; List<Integer> notYellowstoneList = new ArrayList<Integer>(); int yellowSize = 3; while ( yellowSize < sequenceCount ) { int found = -1; for ( int index = 0 ; index < notYellowstoneList.size() ; index++ ) { int test = notYellowstoneList.get(index); if ( gcd(yellowstoneList.get(yellowSize-2), test) > 1 && gcd(yellowstoneList.get(yellowSize-1), test) == 1 ) { found = index; break; } } if ( found >= 0 ) { yellowstoneList.add(notYellowstoneList.remove(found)); yellowSize++; } else { while ( true ) { if ( gcd(yellowstoneList.get(yellowSize-2), num) > 1 && gcd(yellowstoneList.get(yellowSize-1), num) == 1 ) { yellowstoneList.add(num); yellowSize++; num++; break; } notYellowstoneList.add(num); num++; } } } return yellowstoneList; } private static final int gcd(int a, int b) { if ( b == 0 ) { return a; } return gcd(b, a%b); } }