Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert the following code from PHP to Python, ensuring the logic remains intact.
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
Rewrite this program in Python while keeping its functionality equivalent to the PHP version.
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
Convert this PHP block to Python, preserving its control flow and logic.
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
from math import fsum def average(x): return fsum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
Rewrite this program in Python while keeping its functionality equivalent to the PHP version.
<?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) ); }
from __future__ import division import math def hist(source): hist = {}; l = 0; for e in source: l += 1 if e not in hist: hist[e] = 0 hist[e] += 1 return (l,hist) def entropy(hist,l): elist = [] for v in hist.values(): c = v / l elist.append(-c * math.log(c ,2)) return sum(elist) def printHist(h): flip = lambda (k,v) : (v,k) h = sorted(h.iteritems(), key = flip) print 'Sym\thi\tfi\tInf' for (k,v) in h: print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) source = "1223334444" (l,h) = hist(source); print '.[Results].' print 'Length',l print 'Entropy:', entropy(h, l) printHist(h)
Write the same code in Python as shown below in PHP.
<?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) ); }
from __future__ import division import math def hist(source): hist = {}; l = 0; for e in source: l += 1 if e not in hist: hist[e] = 0 hist[e] += 1 return (l,hist) def entropy(hist,l): elist = [] for v in hist.values(): c = v / l elist.append(-c * math.log(c ,2)) return sum(elist) def printHist(h): flip = lambda (k,v) : (v,k) h = sorted(h.iteritems(), key = flip) print 'Sym\thi\tfi\tInf' for (k,v) in h: print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) source = "1223334444" (l,h) = hist(source); print '.[Results].' print 'Length',l print 'Entropy:', entropy(h, l) printHist(h)
Port the following code from PHP to Python with equivalent syntax and logic.
<?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) ); }
from __future__ import division import math def hist(source): hist = {}; l = 0; for e in source: l += 1 if e not in hist: hist[e] = 0 hist[e] += 1 return (l,hist) def entropy(hist,l): elist = [] for v in hist.values(): c = v / l elist.append(-c * math.log(c ,2)) return sum(elist) def printHist(h): flip = lambda (k,v) : (v,k) h = sorted(h.iteritems(), key = flip) print 'Sym\thi\tfi\tInf' for (k,v) in h: print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) source = "1223334444" (l,h) = hist(source); print '.[Results].' print 'Length',l print 'Entropy:', entropy(h, l) printHist(h)
Preserve the algorithm and functionality while converting the code from PHP to Python.
<?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); } }
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
Port the provided PHP code into Python while preserving the original functionality.
<?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); } }
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
Generate an equivalent Python version of this PHP code.
<?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); } }
>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])] >>> >>> difn = lambda s, n: difn(dif(s), n-1) if n else s >>> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 0) [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] >>> difn(s, 1) [-43, 11, -29, -7, 10, 23, -50, 50, 18] >>> difn(s, 2) [54, -40, 22, 17, 13, -73, 100, -32] >>> from pprint import pprint >>> pprint( [difn(s, i) for i in xrange(10)] ) [[90, 47, 58, 29, 22, 32, 55, 5, 55, 73], [-43, 11, -29, -7, 10, 23, -50, 50, 18], [54, -40, 22, 17, 13, -73, 100, -32], [-94, 62, -5, -4, -86, 173, -132], [156, -67, 1, -82, 259, -305], [-223, 68, -83, 341, -564], [291, -151, 424, -905], [-442, 575, -1329], [1017, -1904], [-2921]]
Keep all operations the same but rewrite the snippet in Python.
<?php function prime($a) { if (($a % 2 == 0 && $a != 2) || $a < 2) return false; $limit = sqrt($a); for ($i = 2; $i <= $limit; $i++) if ($a % $i == 0) return false; return true; } foreach (range(1, 100) as $x) if (prime($x)) echo "$x\n"; ?>
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Write the same algorithm in Python as shown in this PHP implementation.
<?php function prime($a) { if (($a % 2 == 0 && $a != 2) || $a < 2) return false; $limit = sqrt($a); for ($i = 2; $i <= $limit; $i++) if ($a % $i == 0) return false; return true; } foreach (range(1, 100) as $x) if (prime($x)) echo "$x\n"; ?>
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Write a version of this PHP function in Python with identical behavior.
<?php function prime($a) { if (($a % 2 == 0 && $a != 2) || $a < 2) return false; $limit = sqrt($a); for ($i = 2; $i <= $limit; $i++) if ($a % $i == 0) return false; return true; } foreach (range(1, 100) as $x) if (prime($x)) echo "$x\n"; ?>
def prime(a): return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1)))
Write a version of this PHP function in Python with identical behavior.
<?php $n=5; $k=3; function factorial($val){ for($f=2;$val-1>1;$f*=$val--); return $f; } $binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k)); echo $binomial_coefficient; ?>
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
Can you help me rewrite this code in Python instead of PHP, keeping it the same logically?
<?php $n=5; $k=3; function factorial($val){ for($f=2;$val-1>1;$f*=$val--); return $f; } $binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k)); echo $binomial_coefficient; ?>
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
Can you help me rewrite this code in Python instead of PHP, keeping it the same logically?
<?php $n=5; $k=3; function factorial($val){ for($f=2;$val-1>1;$f*=$val--); return $f; } $binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k)); echo $binomial_coefficient; ?>
def binomialCoeff(n, k): result = 1 for i in range(1, k+1): result = result * (n-i+1) / i return result if __name__ == "__main__": print(binomialCoeff(5, 3))
Write the same algorithm in Python as shown in this PHP implementation.
<?php $a = array(); # add elements "at the end" array_push($a, 55, 10, 20); print_r($a); # using an explicit key $a['one'] = 1; $a['two'] = 2; print_r($a); ?>
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
Preserve the algorithm and functionality while converting the code from PHP to Python.
<?php $a = array(); # add elements "at the end" array_push($a, 55, 10, 20); print_r($a); # using an explicit key $a['one'] = 1; $a['two'] = 2; print_r($a); ?>
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
Rewrite the snippet below in Python so it works the same as the original PHP code.
<?php $a = array(); # add elements "at the end" array_push($a, 55, 10, 20); print_r($a); # using an explicit key $a['one'] = 1; $a['two'] = 2; print_r($a); ?>
collection = [0, '1'] x = collection[0] collection.append(2) collection.insert(0, '-1') y = collection[0] collection.extend([2,'3']) collection += [2,'3'] collection[2:6] len(collection) collection = (0, 1) collection[:] collection[-4:-1] collection[::2] collection="some string" x = collection[::-1] collection[::2] == "some string"[::2] collection.__getitem__(slice(0,len(collection),2)) collection = {0: "zero", 1: "one"} collection['zero'] = 2 collection = set([0, '1'])
Change the programming language of this snippet from PHP to Python without modifying what it does.
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){ if (is_null($w)) $w = $this->w; if (is_null($h)) $h = $this->h; $w += $x; $h += $y; for ($i = $y; $i < $h; $i++){ for ($j = $x; $j < $w; $j++){ $this->setPixel($j, $i, $color); } } } public function setPixel($x, $y, $color = array(0,0,0)){ if ($x >= $this->w) return false; if ($x < 0) return false; if ($y >= $this->h) return false; if ($y < 0) return false; $this->data[$y][$x] = $color; } public function getPixel($x, $y){ return $this->data[$y][$x]; } public function writeP6($filename){ $fh = fopen($filename, 'w'); if (!$fh) return false; fputs($fh, "P6 {$this->w} {$this->h} 255\n"); foreach ($this->data as $row){ foreach($row as $pixel){ fputs($fh, pack('C', $pixel[0])); fputs($fh, pack('C', $pixel[1])); fputs($fh, pack('C', $pixel[2])); } } fclose($fh); } } $b = new Bitmap(16,16); $b->fill(); $b->fill(2, 2, 18, 18, array(240,240,240)); $b->setPixel(0, 15, array(255,0,0)); $b->writeP6('p6.ppm');
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Ensure the translated Python code behaves exactly like the original PHP snippet.
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){ if (is_null($w)) $w = $this->w; if (is_null($h)) $h = $this->h; $w += $x; $h += $y; for ($i = $y; $i < $h; $i++){ for ($j = $x; $j < $w; $j++){ $this->setPixel($j, $i, $color); } } } public function setPixel($x, $y, $color = array(0,0,0)){ if ($x >= $this->w) return false; if ($x < 0) return false; if ($y >= $this->h) return false; if ($y < 0) return false; $this->data[$y][$x] = $color; } public function getPixel($x, $y){ return $this->data[$y][$x]; } public function writeP6($filename){ $fh = fopen($filename, 'w'); if (!$fh) return false; fputs($fh, "P6 {$this->w} {$this->h} 255\n"); foreach ($this->data as $row){ foreach($row as $pixel){ fputs($fh, pack('C', $pixel[0])); fputs($fh, pack('C', $pixel[1])); fputs($fh, pack('C', $pixel[2])); } } fclose($fh); } } $b = new Bitmap(16,16); $b->fill(); $b->fill(2, 2, 18, 18, array(240,240,240)); $b->setPixel(0, 15, array(255,0,0)); $b->writeP6('p6.ppm');
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Generate an equivalent Python version of this PHP code.
class Bitmap { public $data; public $w; public $h; public function __construct($w = 16, $h = 16){ $white = array_fill(0, $w, array(255,255,255)); $this->data = array_fill(0, $h, $white); $this->w = $w; $this->h = $h; } public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){ if (is_null($w)) $w = $this->w; if (is_null($h)) $h = $this->h; $w += $x; $h += $y; for ($i = $y; $i < $h; $i++){ for ($j = $x; $j < $w; $j++){ $this->setPixel($j, $i, $color); } } } public function setPixel($x, $y, $color = array(0,0,0)){ if ($x >= $this->w) return false; if ($x < 0) return false; if ($y >= $this->h) return false; if ($y < 0) return false; $this->data[$y][$x] = $color; } public function getPixel($x, $y){ return $this->data[$y][$x]; } public function writeP6($filename){ $fh = fopen($filename, 'w'); if (!$fh) return false; fputs($fh, "P6 {$this->w} {$this->h} 255\n"); foreach ($this->data as $row){ foreach($row as $pixel){ fputs($fh, pack('C', $pixel[0])); fputs($fh, pack('C', $pixel[1])); fputs($fh, pack('C', $pixel[2])); } } fclose($fh); } } $b = new Bitmap(16,16); $b->fill(); $b->fill(2, 2, 18, 18, array(240,240,240)); $b->setPixel(0, 15, array(255,0,0)); $b->writeP6('p6.ppm');
import io ppmfileout = io.StringIO('') def writeppmp3(self, f): self.writeppm(f, ppmformat='P3') def writeppm(self, f, ppmformat='P6'): assert ppmformat in ['P3', 'P6'], 'Format wrong' magic = ppmformat + '\n' comment = ' maxval = max(max(max(bit) for bit in row) for row in self.map) assert ppmformat == 'P3' or 0 <= maxval < 256, 'R,G,B must fit in a byte' if ppmformat == 'P6': fwrite = lambda s: f.write(bytes(s, 'UTF-8')) maxval = 255 else: fwrite = f.write numsize=len(str(maxval)) fwrite(magic) fwrite(comment) fwrite('%i %i\n%i\n' % (self.width, self.height, maxval)) for h in range(self.height-1, -1, -1): for w in range(self.width): r, g, b = self.get(w, h) if ppmformat == 'P3': fwrite(' %*i %*i %*i' % (numsize, r, numsize, g, numsize, b)) else: fwrite('%c%c%c' % (r, g, b)) if ppmformat == 'P3': fwrite('\n') Bitmap.writeppmp3 = writeppmp3 Bitmap.writeppm = writeppm bitmap = Bitmap(4, 4, black) bitmap.fillrect(1, 0, 1, 2, white) bitmap.set(3, 3, Colour(127, 0, 63)) bitmap.writeppmp3(ppmfileout) print(ppmfileout.getvalue()) ppmfileout = open('tmp.ppm', 'wb') bitmap.writeppm(ppmfileout) ppmfileout.close()
Translate the given PHP code snippet into Python without altering its behavior.
<?php unlink('input.txt'); unlink('/input.txt'); rmdir('docs'); rmdir('/docs'); ?>
import os os.remove("output.txt") os.rmdir("docs") os.remove("/output.txt") os.rmdir("/docs")
Change the programming language of this snippet from PHP to Python without modifying what it does.
<?php unlink('input.txt'); unlink('/input.txt'); rmdir('docs'); rmdir('/docs'); ?>
import os os.remove("output.txt") os.rmdir("docs") os.remove("/output.txt") os.rmdir("/docs")
Port the following code from PHP to Python with equivalent syntax and logic.
<?php unlink('input.txt'); unlink('/input.txt'); rmdir('docs'); rmdir('/docs'); ?>
import os os.remove("output.txt") os.rmdir("docs") os.remove("/output.txt") os.rmdir("/docs")
Translate this program into Python but keep the logic exactly as in PHP.
<?php $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31); $MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath"); $DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle"); $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th'); $Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay"); $Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux"); $edate = explode(" ",date('Y m j L')); $usery = $edate[0]; $userm = $edate[1]; $userd = $edate[2]; $IsLeap = $edate[3]; if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { $usery = $_GET['y']; $userm = $_GET['m']; $userd = $_GET['d']; $IsLeap = 0; if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; if ($usery%400 == 0) $IsLeap = 1; } $userdays = 0; $i = 0; while ($i < ($userm-1)) { $userdays = $userdays + $Anerisia[$i]; $i = $i +1; } $userdays = $userdays + $userd; $IsHolyday = 0; $dyear = $usery + 1166; $dmonth = $MONTHS[$userdays/73.2]; $dday = $userdays%73; if (0 == $dday) $dday = 73; $Dname = $DAYS[$userdays%5]; $Holyday = "St. Tibs Day"; if ($dday == 5) { $Holyday = $Holy5[$userdays/73.2]; $IsHolyday =1; } if ($dday == 50) { $Holyday = $Holy50[$userdays/73.2]; $IsHolyday =1; } if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2; $suff = $Dsuff[$dday%10] ; if ((11 <= $dday) && (19 >= $dday)) $suff='th'; if ($IsHolyday ==2) echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear; if ($IsHolyday ==1) echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday; if ($IsHolyday == 0) echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear; ?>
import datetime, calendar DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return "St. Tib's Day, YOLD " + (year + 1166) day_of_year = today.timetuple().tm_yday - 1 if is_leap_year and day_of_year >= 60: day_of_year -= 1 season, dday = divmod(day_of_year, 73) return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
Produce a language-to-language conversion: from PHP to Python, same semantics.
<?php $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31); $MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath"); $DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle"); $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th'); $Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay"); $Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux"); $edate = explode(" ",date('Y m j L')); $usery = $edate[0]; $userm = $edate[1]; $userd = $edate[2]; $IsLeap = $edate[3]; if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { $usery = $_GET['y']; $userm = $_GET['m']; $userd = $_GET['d']; $IsLeap = 0; if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; if ($usery%400 == 0) $IsLeap = 1; } $userdays = 0; $i = 0; while ($i < ($userm-1)) { $userdays = $userdays + $Anerisia[$i]; $i = $i +1; } $userdays = $userdays + $userd; $IsHolyday = 0; $dyear = $usery + 1166; $dmonth = $MONTHS[$userdays/73.2]; $dday = $userdays%73; if (0 == $dday) $dday = 73; $Dname = $DAYS[$userdays%5]; $Holyday = "St. Tibs Day"; if ($dday == 5) { $Holyday = $Holy5[$userdays/73.2]; $IsHolyday =1; } if ($dday == 50) { $Holyday = $Holy50[$userdays/73.2]; $IsHolyday =1; } if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2; $suff = $Dsuff[$dday%10] ; if ((11 <= $dday) && (19 >= $dday)) $suff='th'; if ($IsHolyday ==2) echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear; if ($IsHolyday ==1) echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday; if ($IsHolyday == 0) echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear; ?>
import datetime, calendar DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return "St. Tib's Day, YOLD " + (year + 1166) day_of_year = today.timetuple().tm_yday - 1 if is_leap_year and day_of_year >= 60: day_of_year -= 1 season, dday = divmod(day_of_year, 73) return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
Translate the given PHP code snippet into Python without altering its behavior.
<?php $Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31); $MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath"); $DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle"); $Dsuff = array('th','st','nd','rd','th','th','th','th','th','th'); $Holy5 = array("Mungday","MojoDay","Syaday","Zaraday","Maladay"); $Holy50 = array("Chaoflux","Discoflux","Confuflux","Bureflux","Afflux"); $edate = explode(" ",date('Y m j L')); $usery = $edate[0]; $userm = $edate[1]; $userd = $edate[2]; $IsLeap = $edate[3]; if (isset($_GET['y']) && isset($_GET['m']) && isset($_GET['d'])) { $usery = $_GET['y']; $userm = $_GET['m']; $userd = $_GET['d']; $IsLeap = 0; if (($usery%4 == 0) && ($usery%100 >0)) $IsLeap =1; if ($usery%400 == 0) $IsLeap = 1; } $userdays = 0; $i = 0; while ($i < ($userm-1)) { $userdays = $userdays + $Anerisia[$i]; $i = $i +1; } $userdays = $userdays + $userd; $IsHolyday = 0; $dyear = $usery + 1166; $dmonth = $MONTHS[$userdays/73.2]; $dday = $userdays%73; if (0 == $dday) $dday = 73; $Dname = $DAYS[$userdays%5]; $Holyday = "St. Tibs Day"; if ($dday == 5) { $Holyday = $Holy5[$userdays/73.2]; $IsHolyday =1; } if ($dday == 50) { $Holyday = $Holy50[$userdays/73.2]; $IsHolyday =1; } if (($IsLeap ==1) && ($userd ==29) and ($userm ==2)) $IsHolyday = 2; $suff = $Dsuff[$dday%10] ; if ((11 <= $dday) && (19 >= $dday)) $suff='th'; if ($IsHolyday ==2) echo "</br>Celeberate ",$Holyday," ",$dmonth," YOLD ",$dyear; if ($IsHolyday ==1) echo "</br>Celeberate for today ", $Dname , " The ", $dday,"<sup>",$suff,"</sup>", " day of ", $dmonth , " YOLD " , $dyear , " is the holy day of " , $Holyday; if ($IsHolyday == 0) echo "</br>Today is " , $Dname , " the " , $dday ,"<sup>",$suff, "</sup> day of " , $dmonth , " YOLD " , $dyear; ?>
import datetime, calendar DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return "St. Tib's Day, YOLD " + (year + 1166) day_of_year = today.timetuple().tm_yday - 1 if is_leap_year and day_of_year >= 60: day_of_year -= 1 season, dday = divmod(day_of_year, 73) return "%s %d, YOLD %d" % (DISCORDIAN_SEASONS[season], dday + 1, year + 1166)
Write the same algorithm in Python as shown in this PHP implementation.
<?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?>
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
Produce a functionally identical Python code for the snippet given in PHP.
<?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?>
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
Keep all operations the same but rewrite the snippet in Python.
<?php $extra = 'little'; echo "Mary had a $extra lamb.\n"; printf("Mary had a %s lamb.\n", $extra); ?>
>>> original = 'Mary had a %s lamb.' >>> extra = 'little' >>> original % extra 'Mary had a little lamb.'
Port the following code from PHP to Python with equivalent syntax and logic.
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } } function patience_sort(&$n) { $piles = array(); foreach ($n as $x) { $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); } $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); } $a = array(4, 65, 2, -31, 0, 99, 83, 782, 1); patience_sort($a); print_r($a); ?>
from functools import total_ordering from bisect import bisect_left from heapq import merge @total_ordering class Pile(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(n): piles = [] for x in n: new_pile = Pile([x]) i = bisect_left(piles, new_pile) if i != len(piles): piles[i].append(x) else: piles.append(new_pile) n[:] = merge(*[reversed(pile) for pile in piles]) if __name__ == "__main__": a = [4, 65, 2, -31, 0, 99, 83, 782, 1] patience_sort(a) print a
Convert this PHP block to Python, preserving its control flow and logic.
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } } function patience_sort(&$n) { $piles = array(); foreach ($n as $x) { $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); } $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); } $a = array(4, 65, 2, -31, 0, 99, 83, 782, 1); patience_sort($a); print_r($a); ?>
from functools import total_ordering from bisect import bisect_left from heapq import merge @total_ordering class Pile(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(n): piles = [] for x in n: new_pile = Pile([x]) i = bisect_left(piles, new_pile) if i != len(piles): piles[i].append(x) else: piles.append(new_pile) n[:] = merge(*[reversed(pile) for pile in piles]) if __name__ == "__main__": a = [4, 65, 2, -31, 0, 99, 83, 782, 1] patience_sort(a) print a
Produce a language-to-language conversion: from PHP to Python, same semantics.
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } } function patience_sort(&$n) { $piles = array(); foreach ($n as $x) { $low = 0; $high = count($piles)-1; while ($low <= $high) { $mid = (int)(($low + $high) / 2); if ($piles[$mid]->top() >= $x) $high = $mid - 1; else $low = $mid + 1; } $i = $low; if ($i == count($piles)) $piles[] = new SplStack(); $piles[$i]->push($x); } $heap = new PilesHeap(); foreach ($piles as $pile) $heap->insert($pile); for ($c = 0; $c < count($n); $c++) { $smallPile = $heap->extract(); $n[$c] = $smallPile->pop(); if (!$smallPile->isEmpty()) $heap->insert($smallPile); } assert($heap->isEmpty()); } $a = array(4, 65, 2, -31, 0, 99, 83, 782, 1); patience_sort($a); print_r($a); ?>
from functools import total_ordering from bisect import bisect_left from heapq import merge @total_ordering class Pile(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(n): piles = [] for x in n: new_pile = Pile([x]) i = bisect_left(piles, new_pile) if i != len(piles): piles[i].append(x) else: piles.append(new_pile) n[:] = merge(*[reversed(pile) for pile in piles]) if __name__ == "__main__": a = [4, 65, 2, -31, 0, 99, 83, 782, 1] patience_sort(a) print a
Write a version of this PHP function in Python with identical behavior.
$desc = 'tH......... . . ........ . . Ht.. ...... .. tH.... ....... .. .. tH..... ...... ..'; $steps = 30; $world = array(array()); $row = 0; $col = 0; foreach(str_split($desc) as $i){ switch($i){ case "\n": $row++; $col = 0; $world[] = array(); break; case '.': $world[$row][$col] = 1;//conductor $col++; break; case 'H': $world[$row][$col] = 2;//head $col++; break; case 't': $world[$row][$col] = 3;//tail $col++; break; default: $world[$row][$col] = 0;//insulator/air $col++; break; }; }; function draw_world($world){ foreach($world as $rowc){ foreach($rowc as $cell){ switch($cell){ case 0: echo ' '; break; case 1: echo '.'; break; case 2: echo 'H'; break; case 3: echo 't'; }; }; echo "\n"; }; }; echo "Original world:\n"; draw_world($world); for($i = 0; $i < $steps; $i++){ $old_world = $world; //backup to look up where was an electron head foreach($world as $row => &$rowc){ foreach($rowc as $col => &$cell){ switch($cell){ case 2: $cell = 3; break; case 3: $cell = 1; break; case 1: $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col] == 2; if($neigh_heads == 1 || $neigh_heads == 2){ $cell = 2; }; }; }; unset($cell); //just to be safe }; unset($rowc); //just to be safe echo "\nStep " . ($i + 1) . ":\n"; draw_world($world); };
from io import StringIO from collections import namedtuple from pprint import pprint as pp import copy WW = namedtuple('WW', 'world, w, h') head, tail, conductor, empty = allstates = 'Ht. ' infile = StringIO() def readfile(f): world = [row.rstrip('\r\n') for row in f] height = len(world) width = max(len(row) for row in world) nonrow = [ " %*s " % (-width, "") ] world = nonrow + \ [ " %*s " % (-width, row) for row in world ] + \ nonrow world = [list(row) for row in world] return WW(world, width, height) def newcell(currentworld, x, y): istate = currentworld[y][x] assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate if istate == head: ostate = tail elif istate == tail: ostate = conductor elif istate == empty: ostate = empty else: n = sum( currentworld[y+dy][x+dx] == head for dx,dy in ( (-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1), (+1,-1), (+1,+0), (+1,+1) ) ) ostate = head if 1 <= n <= 2 else conductor return ostate def nextgen(ww): 'compute next generation of wireworld' world, width, height = ww newworld = copy.deepcopy(world) for x in range(1, width+1): for y in range(1, height+1): newworld[y][x] = newcell(world, x, y) return WW(newworld, width, height) def world2string(ww): return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] ) ww = readfile(infile) infile.close() for gen in range(10): print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' ) print ( world2string(ww) ) ww = nextgen(ww)
Write a version of this PHP function in Python with identical behavior.
$desc = 'tH......... . . ........ . . Ht.. ...... .. tH.... ....... .. .. tH..... ...... ..'; $steps = 30; $world = array(array()); $row = 0; $col = 0; foreach(str_split($desc) as $i){ switch($i){ case "\n": $row++; $col = 0; $world[] = array(); break; case '.': $world[$row][$col] = 1;//conductor $col++; break; case 'H': $world[$row][$col] = 2;//head $col++; break; case 't': $world[$row][$col] = 3;//tail $col++; break; default: $world[$row][$col] = 0;//insulator/air $col++; break; }; }; function draw_world($world){ foreach($world as $rowc){ foreach($rowc as $cell){ switch($cell){ case 0: echo ' '; break; case 1: echo '.'; break; case 2: echo 'H'; break; case 3: echo 't'; }; }; echo "\n"; }; }; echo "Original world:\n"; draw_world($world); for($i = 0; $i < $steps; $i++){ $old_world = $world; //backup to look up where was an electron head foreach($world as $row => &$rowc){ foreach($rowc as $col => &$cell){ switch($cell){ case 2: $cell = 3; break; case 3: $cell = 1; break; case 1: $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col] == 2; if($neigh_heads == 1 || $neigh_heads == 2){ $cell = 2; }; }; }; unset($cell); //just to be safe }; unset($rowc); //just to be safe echo "\nStep " . ($i + 1) . ":\n"; draw_world($world); };
from io import StringIO from collections import namedtuple from pprint import pprint as pp import copy WW = namedtuple('WW', 'world, w, h') head, tail, conductor, empty = allstates = 'Ht. ' infile = StringIO() def readfile(f): world = [row.rstrip('\r\n') for row in f] height = len(world) width = max(len(row) for row in world) nonrow = [ " %*s " % (-width, "") ] world = nonrow + \ [ " %*s " % (-width, row) for row in world ] + \ nonrow world = [list(row) for row in world] return WW(world, width, height) def newcell(currentworld, x, y): istate = currentworld[y][x] assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate if istate == head: ostate = tail elif istate == tail: ostate = conductor elif istate == empty: ostate = empty else: n = sum( currentworld[y+dy][x+dx] == head for dx,dy in ( (-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1), (+1,-1), (+1,+0), (+1,+1) ) ) ostate = head if 1 <= n <= 2 else conductor return ostate def nextgen(ww): 'compute next generation of wireworld' world, width, height = ww newworld = copy.deepcopy(world) for x in range(1, width+1): for y in range(1, height+1): newworld[y][x] = newcell(world, x, y) return WW(newworld, width, height) def world2string(ww): return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] ) ww = readfile(infile) infile.close() for gen in range(10): print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' ) print ( world2string(ww) ) ww = nextgen(ww)
Transform the following PHP implementation into Python, maintaining the same output and logic.
$desc = 'tH......... . . ........ . . Ht.. ...... .. tH.... ....... .. .. tH..... ...... ..'; $steps = 30; $world = array(array()); $row = 0; $col = 0; foreach(str_split($desc) as $i){ switch($i){ case "\n": $row++; $col = 0; $world[] = array(); break; case '.': $world[$row][$col] = 1;//conductor $col++; break; case 'H': $world[$row][$col] = 2;//head $col++; break; case 't': $world[$row][$col] = 3;//tail $col++; break; default: $world[$row][$col] = 0;//insulator/air $col++; break; }; }; function draw_world($world){ foreach($world as $rowc){ foreach($rowc as $cell){ switch($cell){ case 0: echo ' '; break; case 1: echo '.'; break; case 2: echo 'H'; break; case 3: echo 't'; }; }; echo "\n"; }; }; echo "Original world:\n"; draw_world($world); for($i = 0; $i < $steps; $i++){ $old_world = $world; //backup to look up where was an electron head foreach($world as $row => &$rowc){ foreach($rowc as $col => &$cell){ switch($cell){ case 2: $cell = 3; break; case 3: $cell = 1; break; case 1: $neigh_heads = (int) @$old_world[$row - 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col] == 2; $neigh_heads += (int) @$old_world[$row - 1][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row][$col + 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col - 1] == 2; $neigh_heads += (int) @$old_world[$row + 1][$col] == 2; if($neigh_heads == 1 || $neigh_heads == 2){ $cell = 2; }; }; }; unset($cell); //just to be safe }; unset($rowc); //just to be safe echo "\nStep " . ($i + 1) . ":\n"; draw_world($world); };
from io import StringIO from collections import namedtuple from pprint import pprint as pp import copy WW = namedtuple('WW', 'world, w, h') head, tail, conductor, empty = allstates = 'Ht. ' infile = StringIO() def readfile(f): world = [row.rstrip('\r\n') for row in f] height = len(world) width = max(len(row) for row in world) nonrow = [ " %*s " % (-width, "") ] world = nonrow + \ [ " %*s " % (-width, row) for row in world ] + \ nonrow world = [list(row) for row in world] return WW(world, width, height) def newcell(currentworld, x, y): istate = currentworld[y][x] assert istate in allstates, 'Wireworld cell set to unknown value "%s"' % istate if istate == head: ostate = tail elif istate == tail: ostate = conductor elif istate == empty: ostate = empty else: n = sum( currentworld[y+dy][x+dx] == head for dx,dy in ( (-1,-1), (-1,+0), (-1,+1), (+0,-1), (+0,+1), (+1,-1), (+1,+0), (+1,+1) ) ) ostate = head if 1 <= n <= 2 else conductor return ostate def nextgen(ww): 'compute next generation of wireworld' world, width, height = ww newworld = copy.deepcopy(world) for x in range(1, width+1): for y in range(1, height+1): newworld[y][x] = newcell(world, x, y) return WW(newworld, width, height) def world2string(ww): return '\n'.join( ''.join(row[1:-1]).rstrip() for row in ww.world[1:-1] ) ww = readfile(infile) infile.close() for gen in range(10): print ( ("\n%3i " % gen) + '=' * (ww.w-4) + '\n' ) print ( world2string(ww) ) ww = nextgen(ww)
Convert this PHP block to Python, preserving its control flow and logic.
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
Write the same algorithm in Python as shown in this PHP implementation.
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
Translate the given PHP code snippet into Python without altering its behavior.
<?php function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; } return $count % 2; } function west($A, $B, $x, $y) { if ($A['y'] <= $B['y']) { if ($y <= $A['y'] || $y > $B['y'] || $x >= $A['x'] && $x >= $B['x']) { return false; } if ($x < $A['x'] && $x < $B['x']) { return true; } if ($x == $A['x']) { if ($y == $A['y']) { $result1 = NAN; } else { $result1 = INF; } } else { $result1 = ($y - $A['y']) / ($x - $A['x']); } if ($B['x'] == $A['x']) { if ($B['y'] == $A['y']) { $result2 = NAN; } else { $result2 = INF; } } else { $result2 = ($B['y'] - $A['y']) / ($B['x'] - $A['x']); } return $result1 > $result2; } return west($B, $A, $x, $y); } $square = [ 'name' => 'square', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20]] ]; $squareHole = [ 'name' => 'squareHole', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 20, 'y' => 0], ['x' => 20, 'y' => 20], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 5], ['x' => 15, 'y' => 5], ['x' => 15, 'y' => 15], ['x' => 5, 'y' => 15]] ]; $strange = [ 'name' => 'strange', 'bounds' => [['x' => 0, 'y' => 0], ['x' => 5, 'y' => 5], ['x' => 0, 'y' => 20], ['x' => 5, 'y' => 15], ['x' => 15, 'y' => 15], ['x' => 20, 'y' => 20], ['x' => 20, 'y' => 0]] ]; $hexagon = [ 'name' => 'hexagon', 'bounds' => [['x' => 6, 'y' => 0], ['x' => 14, 'y' => 0], ['x' => 20, 'y' => 10], ['x' => 14, 'y' => 20], ['x' => 6, 'y' => 20], ['x' => 0, 'y' => 10]] ]; $shapes = [$square, $squareHole, $strange, $hexagon]; $testPoints = [ ['lng' => 10, 'lat' => 10], ['lng' => 10, 'lat' => 16], ['lng' => -20, 'lat' => 10], ['lng' => 0, 'lat' => 10], ['lng' => 20, 'lat' => 10], ['lng' => 16, 'lat' => 10], ['lng' => 20, 'lat' => 20] ]; for ($s = 0; $s < count($shapes); $s++) { $shape = $shapes[$s]; for ($tp = 0; $tp < count($testPoints); $tp++) { $testPoint = $testPoints[$tp]; echo json_encode($testPoint) . "\tin " . $shape['name'] . "\t" . contains($shape['bounds'], $testPoint['lat'], $testPoint['lng']) . PHP_EOL; } }
from collections import namedtuple from pprint import pprint as pp import sys Pt = namedtuple('Pt', 'x, y') Edge = namedtuple('Edge', 'a, b') Poly = namedtuple('Poly', 'name, edges') _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_info.min def rayintersectseg(p, edge): a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps) intersect = False if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect def _odd(x): return x%2 == 1 def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges )) def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
Keep all operations the same but rewrite the snippet in Python.
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2
Port the provided PHP code into Python while preserving the original functionality.
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2
Rewrite the snippet below in Python so it works the same as the original PHP code.
<?php echo substr_count("the three truths", "th"), PHP_EOL; // prints "3" echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2
Keep all operations the same but rewrite the snippet in Python.
#!/usr/bin/php <?php if ($argc > 1) file_put_contents( 'notes.txt', date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", FILE_APPEND ); else @readfile('notes.txt');
import sys, datetime, shutil if len(sys.argv) == 1: try: with open("notes.txt", "r") as f: shutil.copyfileobj(f, sys.stdout) except IOError: pass else: with open("notes.txt", "a") as f: f.write(datetime.datetime.now().isoformat() + "\n") f.write("\t%s\n" % ' '.join(sys.argv[1:]))
Port the following code from PHP to Python with equivalent syntax and logic.
#!/usr/bin/php <?php if ($argc > 1) file_put_contents( 'notes.txt', date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", FILE_APPEND ); else @readfile('notes.txt');
import sys, datetime, shutil if len(sys.argv) == 1: try: with open("notes.txt", "r") as f: shutil.copyfileobj(f, sys.stdout) except IOError: pass else: with open("notes.txt", "a") as f: f.write(datetime.datetime.now().isoformat() + "\n") f.write("\t%s\n" % ' '.join(sys.argv[1:]))
Change the programming language of this snippet from PHP to VB without modifying what it does.
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 }
Debug.Print Hex(&HF0F0 And &HFF00) Debug.Print Hex(&HF0F0 Or &HFF00) Debug.Print Hex(&HF0F0 Xor &HFF00) Debug.Print Hex(Not &HF0F0) Debug.Print Hex(&HF0F0 Eqv &HFF00) Debug.Print Hex(&HF0F0 Imp &HFF00)
Write a version of this PHP function in VB with identical behavior.
<?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 }
$Include "Rapidq.inc" dim file as qfilestream if file.open("c:\A Test.txt", fmOpenRead) then while not File.eof print File.readline wend else print "Cannot read file" end if input "Press enter to exit: ";a$
Write the same code in VB as shown below in PHP.
base_convert("26", 10, 16); // returns "1a"
Private Function to_base(ByVal number As Long, base As Integer) As String Dim digits As String, result As String Dim i As Integer, digit As Integer digits = "0123456789abcdefghijklmnopqrstuvwxyz" Do While number > 0 digit = number Mod base result = Mid(digits, digit + 1, 1) & result number = number \ base Loop to_base = result End Function Private Function from_base(number As String, base As Integer) As Long Dim digits As String, result As Long Dim i As Integer digits = "0123456789abcdefghijklmnopqrstuvwxyz" result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1) For i = 2 To Len(number) result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1) Next i from_base = result End Function Public Sub Non_decimal_radices_Convert() Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16) End Sub
Write the same algorithm in VB as shown in this PHP implementation.
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$/');
Sub printFiles(parentDir As FolderItem, pattern As String) For i As Integer = 1 To parentDir.Count If parentDir.Item(i).Directory Then printFiles(parentDir.Item(i), pattern) Else Dim rg as New RegEx Dim myMatch as RegExMatch rg.SearchPattern = pattern myMatch = rg.search(parentDir.Item(i).Name) If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath) End If Next End Sub
Transform the following PHP implementation into VB, maintaining the same output and logic.
printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));
dim crctbl(255) const crcc =&hEDB88320 sub gencrctable for i= 0 to 255 k=i for j=1 to 8 if k and 1 then k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) k=k xor crcc else k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) end if next crctbl(i)=k next end sub function crc32 (buf) dim r,r1,i r=&hffffffff for i=1 to len(buf) r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0) r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) next crc32=r xor &hffffffff end function gencrctable wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))
Rewrite the snippet below in VB so it works the same as the original PHP code.
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();
Class NumberContainer Private TheNumber As Integer Sub Constructor(InitialNumber As Integer) TheNumber = InitialNumber End Sub Function Number() As Integer Return TheNumber End Function Sub Number(Assigns NewNumber As Integer) TheNumber = NewNumber End Sub End Class
Convert the following code from PHP to VB, ensuring the logic remains intact.
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; }
Module Module1 ReadOnly max As ULong = 1000000 Function Kaprekar(n As ULong) As Boolean If n = 1 Then Return True Dim sq = n * n Dim sq_str = Str(sq) Dim l = Len(sq_str) For x = l - 1 To 1 Step -1 If sq_str(x) = "0" Then l = l - 1 Else Exit For End If Next For x = 1 To l - 1 Dim p2 = Val(Mid(sq_str, x + 1)) If p2 > n Then Continue For End If Dim p1 = Val(Left(sq_str, x)) If p1 > n Then Return False If (p1 + p2) = n Then Return True Next Return False End Function Sub Main() Dim count = 0 Console.WriteLine("Kaprekar numbers below 10000") For n = 1 To max - 1 If Kaprekar(n) Then count = count + 1 If n < 10000 Then Console.WriteLine("{0,2} {1,4}", count, n) End If End If Next Console.WriteLine() Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max) End Sub End Module
Maintain the same structure and functionality when rewriting this code in VB.
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; }
Module Module1 ReadOnly max As ULong = 1000000 Function Kaprekar(n As ULong) As Boolean If n = 1 Then Return True Dim sq = n * n Dim sq_str = Str(sq) Dim l = Len(sq_str) For x = l - 1 To 1 Step -1 If sq_str(x) = "0" Then l = l - 1 Else Exit For End If Next For x = 1 To l - 1 Dim p2 = Val(Mid(sq_str, x + 1)) If p2 > n Then Continue For End If Dim p1 = Val(Left(sq_str, x)) If p1 > n Then Return False If (p1 + p2) = n Then Return True Next Return False End Function Sub Main() Dim count = 0 Console.WriteLine("Kaprekar numbers below 10000") For n = 1 To max - 1 If Kaprekar(n) Then count = count + 1 If n < 10000 Then Console.WriteLine("{0,2} {1,4}", count, n) End If End If Next Console.WriteLine() Console.WriteLine("{0} numbers below {1} are kaprekar numbers", count, max) End Sub End Module
Produce a language-to-language conversion: from PHP to VB, same semantics.
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;
Option Explicit Const numchars=127 Function LZWCompress(si) Dim oDict, intMaxCode, i,z,ii,ss,strCurrent,strNext,j Set oDict = CreateObject("Scripting.Dictionary") ReDim a(Len(si)) intMaxCode = numchars For i = 0 To numchars oDict.Add Chr(i), i Next strCurrent = Left(si,1) j=0 For ii=2 To Len(si) strNext = Mid(si,ii,1) ss=strCurrent & strNext If oDict.Exists(ss) Then strCurrent = ss Else a(j)=oDict.Item(strCurrent) :j=j+1 intMaxCode = intMaxCode + 1 oDict.Add ss, intMaxCode strCurrent = strNext End If Next a(j)=oDict.Item(strCurrent) ReDim preserve a(j) LZWCompress=a Set oDict = Nothing End Function Function lzwUncompress(sc) Dim intNext, intCurrent, intMaxCode, i,ss,istr,s,j s="" reDim dict(1000) intMaxCode = numchars For i = 0 To numchars : dict(i)= Chr(i) : Next intCurrent=sc(0) For j=1 To UBound(sc) ss=dict(intCurrent) s= s & ss intMaxCode = intMaxCode + 1 intnext=sc(j) If intNext<intMaxCode Then dict(intMaxCode)=ss & Left(dict(intNext), 1) Else dict(intMaxCode)=ss & Left(ss, 1) End If intCurrent = intNext Next s= s & dict(intCurrent) lzwUncompress=s End function Sub printvec(a) Dim s,i,x s="(" For i=0 To UBound (a) s=s & x & a(i) x=", " Next WScript.echo s &")" End sub Dim a,b b="TOBEORNOTTOBEORTOBEORNOT" WScript.Echo b a=LZWCompress (b) printvec(a) WScript.echo lzwUncompress (a ) wscript.quit 1
Produce a functionally identical VB code for the snippet given in PHP.
<?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"; ?>
Sub Main() Debug.Print F(-10) Debug.Print F(10) End Sub Private Function F(N As Long) As Variant If N < 0 Then F = "Error. Negative argument" ElseIf N <= 1 Then F = N Else F = F(N - 1) + F(N - 2) End If End Function
Produce a functionally identical VB code for the snippet given in PHP.
<?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 ?>
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
Maintain the same structure and functionality when rewriting this code in VB.
<?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 ?>
string = "Small Basic" TextWindow.WriteLine(Text.GetSubTextToEnd(string, 2)) TextWindow.WriteLine(Text.GetSubText(string, 1, Text.GetLength(string) - 1)) TextWindow.WriteLine(Text.GetSubText(string, 2, Text.GetLength(string) - 2))
Write the same code in VB as shown below in PHP.
<?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;
Set objfso = CreateObject("Scripting.FileSystemObject") Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\input.txt",1) list = "" previous_line = "" l = Len(previous_line) Do Until objfile.AtEndOfStream current_line = objfile.ReadLine If Mid(current_line,l+1,1) <> "" Then list = current_line & vbCrLf previous_line = current_line l = Len(previous_line) ElseIf Mid(current_line,l,1) <> "" And Mid(current_line,(l+1),1) = "" Then list = list & current_line & vbCrLf End If Loop WScript.Echo list objfile.Close Set objfso = Nothing
Please provide an equivalent version of this PHP code in VB.
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Public Sub create_file() Dim FileNumber As Integer FileNumber = FreeFile MkDir "docs" Open "docs\output.txt" For Output As #FreeFile Close #FreeFile MkDir "C:\docs" Open "C:\docs\output.txt" For Output As #FreeFile Close #FreeFile End Sub
Convert this PHP block to VB, preserving its control flow and logic.
$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; }
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " commandtable = Split(s, " ") Dim i As Integer For Each word In commandtable If Len(word) > 0 Then i = 1 Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z" i = i + 1 Loop command_table.Add Key:=word, Item:=i - 1 End If Next word For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
Translate the given PHP code snippet into VB without altering its behavior.
$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; }
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbreviations.CompareMode = TextCompare Dim commandtable() As String Dim commands As String s = s & "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " s = s & "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " s = s & "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " s = s & "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " s = s & "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " s = s & "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " s = s & "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " commandtable = Split(s, " ") Dim i As Integer For Each word In commandtable If Len(word) > 0 Then i = 1 Do While Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z" i = i + 1 Loop command_table.Add Key:=word, Item:=i - 1 End If Next word For Each word In command_table For i = command_table(word) To Len(word) On Error Resume Next abbreviations.Add Key:=Left(word, i), Item:=UCase(word) Next i Next word user_words() = Split(userstring, " ") For Each word In user_words If Len(word) > 0 Then If abbreviations.exists(word) Then commands = commands & abbreviations(word) & " " Else commands = commands & "*error* " End If End If Next word ValidateUserWords = commands End Function Public Sub program() Dim guserstring As String guserstring = "riG rePEAT copies put mo rest types fup. 6 poweRin" Debug.Print "user words:", guserstring Debug.Print "full words:", ValidateUserWords(guserstring) End Sub
Write the same algorithm in VB as shown in this PHP implementation.
$ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll"); $cstr = $ffi->_strdup("success"); $str = FFI::string($cstr); echo $str; FFI::free($cstr);
Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _ CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr, numOfBytes As Integer, ByRef numOfBytesWritten As Integer, _ overlapped As Ptr) As Boolean Declare Function GetLastError Lib "Kernel32" () As Integer Declare Function CloseHandle Lib "kernel32" (hObject As Integer) As Boolean Const FILE_SHARE_READ = &h00000001 Const FILE_SHARE_WRITE = &h00000002 Const OPEN_EXISTING = 3 Dim fHandle As Integer = CreateFileW("C:\foo.txt", 0, FILE_SHARE_READ Or FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0) If fHandle > 0 Then Dim mb As MemoryBlock = "Hello, World!" Dim bytesWritten As Integer If Not WriteFile(fHandle, mb, mb.Size, bytesWritten, Nil) Then MsgBox("Error Number: " + Str(GetLastError)) End If Call CloseHandle(fHandle) Else MsgBox("Error Number: " + Str(GetLastError)) End If
Convert this PHP block to VB, preserving its control flow and logic.
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
Change the programming language of this snippet from PHP to VB without modifying what it does.
<?php $program_name = $argv[0]; $second_arg = $argv[2]; $all_args_without_program_name = array_shift($argv);
Function Run(args() as String) As Integer For each arg As String In args Stdout.WriteLine(arg) Next End Function
Generate an equivalent VB version of this PHP code.
$arr1 = array(1, 2, 3); $arr2 = array(4, 5, 6); $arr3 = array_merge($arr1, $arr2);
DEFINT A(1 to 4) = {1, 2, 3, 4} DEFINT B(1 to 4) = {10, 20, 30, 40} Redim A(1 to 8) as integer MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
Write the same code in VB as shown below in PHP.
#!/usr/bin/php <?php $string = fgets(STDIN); $integer = (int) fgets(STDIN);
Public Sub text() Debug.Print InputBox("Input a string") Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long") End Sub
Write a version of this PHP function in VB with identical behavior.
######################################################### # 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>";
Option Explicit Const maxWeight = 400 Dim DataList As Variant Dim xList(64, 3) As Variant Dim nItems As Integer Dim s As String, xss As String Dim xwei As Integer, xval As Integer, nn As Integer Sub Main() Dim i As Integer, j As Integer DataList = Array("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, "book", 30, 10, _ "waterproof trousers", 42, 70, "waterproof overclothes", 43, 75, _ "note-case", 22, 80, "sunglasses", 7, 20, "towel", 18, 12, "socks", 4, 50) nItems = (UBound(DataList) + 1) / 3 j = 0 For i = 1 To nItems xList(i, 1) = DataList(j) xList(i, 2) = DataList(j + 1) xList(i, 3) = DataList(j + 2) j = j + 3 Next i s = "" For i = 1 To nItems s = s & Chr(i) Next nn = 0 Call ChoiceBin(1, "") For i = 1 To Len(xss) j = Asc(Mid(xss, i, 1)) Debug.Print xList(j, 1) Next i Debug.Print "count=" & Len(xss), "weight=" & xwei, "value=" & xval End Sub Private Sub ChoiceBin(n As String, ss As String) Dim r As String Dim i As Integer, j As Integer, iwei As Integer, ival As Integer Dim ipct As Integer If n = Len(s) + 1 Then iwei = 0: ival = 0 For i = 1 To Len(ss) j = Asc(Mid(ss, i, 1)) iwei = iwei + xList(j, 2) ival = ival + xList(j, 3) Next If iwei <= maxWeight And ival > xval Then xss = ss: xwei = iwei: xval = ival End If Else r = Mid(s, n, 1) Call ChoiceBin(n + 1, ss & r) Call ChoiceBin(n + 1, ss) End If End Sub
Rewrite this program in VB while keeping its functionality equivalent to the PHP version.
<?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";
dim _proper_divisors(100) sub proper_divisors(n) dim i dim _proper_divisors_count = 0 if n <> 1 then for i = 1 to (n \ 2) if n %% i = 0 then _proper_divisors_count = _proper_divisors_count + 1 _proper_divisors(_proper_divisors_count) = i end if next end if return _proper_divisors_count end sub sub show_proper_divisors(n, tabbed) dim cnt = proper_divisors(n) print str$(n) + ":"; tab(4);"(" + str$(cnt) + " items) "; dim j for j = 1 to cnt if tabbed then print str$(_proper_divisors(j)), else print str$(_proper_divisors(j)); end if if (j < cnt) then print ","; next print end sub dim i for i = 1 to 10 show_proper_divisors(i, false) next dim c dim maxindex = 0 dim maxlength = 0 for t = 1 to 20000 c = proper_divisors(t) if c > maxlength then maxindex = t maxlength = c end if next print "A maximum at "; show_proper_divisors(maxindex, false)
Rewrite the snippet below in VB so it works the same as the original PHP code.
$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";
text = "I need more coffee!!!" Set regex = New RegExp regex.Global = True regex.Pattern = "\s" If regex.Test(text) Then WScript.StdOut.Write regex.Replace(text,vbCrLf) Else WScript.StdOut.Write "No matching pattern" End If
Produce a functionally identical VB code for the snippet given in PHP.
$keys = array('a', 'b', 'c'); $values = array(1, 2, 3); $hash = array_combine($keys, $values);
Set dict = CreateObject("Scripting.Dictionary") os = Array("Windows", "Linux", "MacOS") owner = Array("Microsoft", "Linus Torvalds", "Apple") For n = 0 To 2 dict.Add os(n), owner(n) Next MsgBox dict.Item("Linux") MsgBox dict.Item("MacOS") MsgBox dict.Item("Windows")
Generate a VB translation of this PHP snippet without changing its computational steps.
<?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)); }
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
Translate this program into VB but keep the logic exactly as in PHP.
<?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)); }
Function Encoder(ByVal n) Encoder = n Xor (n \ 2) End Function Function Decoder(ByVal n) Dim g : g = 0 Do While n > 0 g = g Xor n n = n \ 2 Loop Decoder = g End Function Function Dec2bin(ByVal n, ByVal length) Dim i, strbin : strbin = "" For i = 1 to 5 strbin = (n Mod 2) & strbin n = n \ 2 Next Dec2Bin = strbin End Function WScript.StdOut.WriteLine("Binary -> Gray Code -> Binary") For i = 0 to 31 encoded = Encoder(i) decoded = Decoder(encoded) WScript.StdOut.WriteLine(Dec2Bin(i, 5) & " -> " & Dec2Bin(encoded, 5) & " -> " & Dec2Bin(decoded, 5)) Next
Change the programming language of this snippet from PHP to VB without modifying what it does.
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 ]; } }
suite$ = "CDHS" #Club, Diamond, Heart, Spade card$ = "A23456789TJQK" #Cards Ace to King card = 0 dim n(55) #make ordered deck for i = 1 to 52 # of 52 cards n[i] = i next i for i = 1 to 52 * 3 #shuffle deck 3 times i1 = int(rand * 52) + 1 i2 = int(rand * 52) + 1 h2 = n[i1] n[i1] = n[i2] n[i2] = h2 next i for hand = 1 to 4 #4 hands for deal = 1 to 13 #deal each 13 cards card += 1 #next card in deck s = (n[card] mod 4) + 1 #determine suite c = (n[card] mod 13) + 1 #determine card print mid(card$,c,1);mid(suite$,s,1);" "; #show the card next deal print next hand end function word$(sr$, wn, delim$) j = wn if j = 0 then j += 1 res$ = "" : s$ = sr$ : d$ = delim$ if d$ = "" then d$ = " " sd = length(d$) : sl = length(s$) while true n = instr(s$,d$) : j -= 1 if j = 0 then if n=0 then res$=s$ else res$=mid(s$,1,n-1) return res$ end if if n = 0 then return res$ if n = sl - sd then res$ = "" : return res$ sl2 = sl-n : s$ = mid(s$,n+1,sl2) : sl = sl2 end while return res$ end function
Generate an equivalent VB version of this PHP code.
$NumberArray = array(0, 1, 2, 3, 4, 5, 6); $LetterArray = array("a", "b", "c", "d", "e", "f"); $simpleForm = ['apple', 'orange'];
Option Base {0|1}
Can you help me rewrite this code in VB instead of PHP, keeping it the same logically?
<?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; }
Const Order = 4 Function InCarpet(ByVal x As Integer, ByVal y As Integer) Do While x <> 0 And y <> 0 If x Mod 3 = 1 And y Mod 3 = 1 Then InCarpet = " " Exit Function End If x = x \ 3 y = y \ 3 Loop InCarpet = "#" End Function Public Sub sierpinski_carpet() Dim i As Integer, j As Integer For i = 0 To 3 ^ Order - 1 For j = 0 To 3 ^ Order - 1 Debug.Print InCarpet(i, j); Next j Debug.Print Next i End Sub
Write the same algorithm in VB as shown in this PHP implementation.
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; }
Private Function Knuth(a As Variant) As Variant Dim t As Variant, i As Integer If Not IsMissing(a) Then For i = UBound(a) To LBound(a) + 1 Step -1 j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a)) t = a(i) a(i) = a(j) a(j) = t Next i End If Knuth = a End Function Private Function inOrder(s As Variant) i = 2 Do While i <= UBound(s) If s(i) < s(i - 1) Then inOrder = False Exit Function End If i = i + 1 Loop inOrder = True End Function Private Function bogosort(ByVal s As Variant) As Variant Do While Not inOrder(s) Debug.Print Join(s, ", ") s = Knuth(s) Loop bogosort = s End Function Public Sub main() Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), ", ") End Sub
Translate the given PHP code snippet into VB without altering its behavior.
<?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!"); } ?>
Sub Main() Dim i&, c&, j#, s$ Const N& = 1000000 s = "values for n in the range 1 to 22 : " For i = 1 To 22 s = s & ns(i) & ", " Next For i = 1 To N j = Sqr(ns(i)) If j = CInt(j) Then c = c + 1 Next Debug.Print s Debug.Print c & " squares less than " & N End Sub Private Function ns(l As Long) As Long ns = l + Int(1 / 2 + Sqr(l)) End Function
Translate this program into VB but keep the logic exactly as in PHP.
<?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 ?>
Public Sub substring() sentence = "the last thing the man said was the" n = 10: m = 5 Debug.Print Mid(sentence, n, 5) Debug.Print Right(sentence, Len(sentence) - n + 1) Debug.Print Left(sentence, Len(sentence) - 1) k = InStr(1, sentence, "m") Debug.Print Mid(sentence, k, 5) k = InStr(1, sentence, "aid") Debug.Print Mid(sentence, k, 5) End Sub
Produce a language-to-language conversion: from PHP to VB, same semantics.
<?php function isLeapYear($year) { if ($year % 100 == 0) { return ($year % 400 == 0); } return ($year % 4 == 0); }
Public Function Leap_year(year As Integer) As Boolean Leap_year = (Month(DateSerial(year, 2, 29)) = 2) End Function
Preserve the algorithm and functionality while converting the code from PHP to VB.
$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]}"; }
Public twenties As Variant Public decades As Variant Public orders As Variant Private Sub init() twenties = [{"zero","one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}] decades = [{"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}] orders = [{1E15,"quadrillion"; 1E12,"trillion"; 1E9,"billion"; 1E6,"million"; 1E3,"thousand"}] End Sub Private Function Twenty(N As Variant) Twenty = twenties(N Mod 20 + 1) End Function Private Function Decade(N As Variant) Decade = decades(N Mod 10 - 1) End Function Private Function Hundred(N As Variant) If N < 20 Then Hundred = Twenty(N) Exit Function Else If N Mod 10 = 0 Then Hundred = Decade((N \ 10) Mod 10) Exit Function End If End If Hundred = Decade(N \ 10) & "-" & Twenty(N Mod 10) End Function Private Function Thousand(N As Variant, withand As String) If N < 100 Then Thousand = withand & Hundred(N) Exit Function Else If N Mod 100 = 0 Then Thousand = withand & Twenty(WorksheetFunction.Floor_Precise(N / 100)) & " hundred" Exit Function End If End If Thousand = Twenty(N \ 100) & " hundred and " & Hundred(N Mod 100) End Function Private Function Triplet(N As Variant) Dim Order, High As Variant, Low As Variant Dim Name As String, res As String For i = 1 To UBound(orders) Order = orders(i, 1) Name = orders(i, 2) High = WorksheetFunction.Floor_Precise(N / Order) Low = N - High * Order If High <> 0 Then res = res & Thousand(High, "") & " " & Name End If N = Low If Low = 0 Then Exit For If Len(res) And High <> 0 Then res = res & ", " End If Next i If N <> 0 Or res = "" Then res = res & Thousand(WorksheetFunction.Floor_Precise(N), IIf(res = "", "", "and ")) N = N - Int(N) If N > 0.000001 Then res = res & " point" For i = 1 To 10 n_ = WorksheetFunction.Floor_Precise(N * 10.0000001) res = res & " " & twenties(n_ + 1) N = N * 10 - n_ If Abs(N) < 0.000001 Then Exit For Next i End If End If Triplet = res End Function Private Function spell(N As Variant) Dim res As String If N < 0 Then res = "minus " N = -N End If res = res & Triplet(N) spell = res End Function Private Function smartp(N As Variant) Dim res As String If N = WorksheetFunction.Floor_Precise(N) Then smartp = CStr(N) Exit Function End If res = CStr(N) If InStr(1, res, ".") Then res = Left(res, InStr(1, res, ".")) End If smartp = res End Function Sub Main() Dim si As Variant init Samples1 = [{99, 300, 310, 417, 1501, 12609, 200000000000100, 999999999999999, -123456787654321,102003000400005,1020030004,102003,102,1,0,-1,-99, -1501,1234,12.34}] Samples2 = [{10000001.2,1E-3,-2.7182818, 201021002001,-20102100200,2010210020,-201021002,20102100,-2010210, 201021,-20102,2010,-201,20,-2}] For i = 1 To UBound(Samples1) si = Samples1(i) Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si) Next i For i = 1 To UBound(Samples2) si = Samples2(i) Debug.Print Format(smartp(si), "@@@@@@@@@@@@@@@@"); " "; spell(si) Next i End Sub
Change the following PHP code into VB without altering its purpose.
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; }
Sub arrShellSort(ByVal arrData As Variant) Dim lngHold, lngGap As Long Dim lngCount, lngMin, lngMax As Long Dim varItem As Variant lngMin = LBound(arrData) lngMax = UBound(arrData) lngGap = lngMin Do While (lngGap < lngMax) lngGap = 3 * lngGap + 1 Loop Do While (lngGap > 1) lngGap = lngGap \ 3 For lngCount = lngGap + lngMin To lngMax varItem = arrData(lngCount) lngHold = lngCount Do While ((arrData(lngHold - lngGap) > varItem)) arrData(lngHold) = arrData(lngHold - lngGap) lngHold = lngHold - lngGap If (lngHold < lngMin + lngGap) Then Exit Do Loop arrData(lngHold) = varItem Next Loop arrShellSort = arrData End Sub
Convert this PHP block to VB, preserving its control flow and logic.
<?php print_r(array_count_values(str_split(file_get_contents($argv[1])))); ?>
TYPE regChar Character AS STRING * 3 Count AS LONG END TYPE DIM iChar AS INTEGER DIM iCL AS INTEGER DIM iCountChars AS INTEGER DIM iFile AS INTEGER DIM i AS INTEGER DIM lMUC AS LONG DIM iMUI AS INTEGER DIM lLUC AS LONG DIM iLUI AS INTEGER DIM iMaxIdx AS INTEGER DIM iP AS INTEGER DIM iPause AS INTEGER DIM iPMI AS INTEGER DIM iPrint AS INTEGER DIM lHowMany AS LONG DIM lTotChars AS LONG DIM sTime AS SINGLE DIM strFile AS STRING DIM strTxt AS STRING DIM strDate AS STRING DIM strTime AS STRING DIM strKey AS STRING CONST LngReg = 256 CONST Letters = 1 CONST FALSE = 0 CONST TRUE = NOT FALSE strDate = DATE$ strTime = TIME$ iFile = FREEFILE DO CLS PRINT "This program counts letters or characters in a text file." PRINT INPUT "File to open: ", strFile OPEN strFile FOR BINARY AS #iFile IF LOF(iFile) > 0 THEN PRINT "Count: 1) Letters 2) Characters (1 or 2)"; DO strKey = INKEY$ LOOP UNTIL strKey = "1" OR strKey = "2" PRINT ". Option selected: "; strKey iCL = VAL(strKey) sTime = TIMER iP = POS(0) lHowMany = LOF(iFile) strTxt = SPACE$(LngReg) IF iCL = Letters THEN iMaxIdx = 26 ELSE iMaxIdx = 255 END IF IF iMaxIdx <> iPMI THEN iPMI = iMaxIdx REDIM rChar(0 TO iMaxIdx) AS regChar FOR i = 0 TO iMaxIdx IF iCL = Letters THEN strTxt = CHR$(i + 65) IF i = 26 THEN strTxt = CHR$(165) ELSE SELECT CASE i CASE 0: strTxt = "nul" CASE 7: strTxt = "bel" CASE 9: strTxt = "tab" CASE 10: strTxt = "lf" CASE 11: strTxt = "vt" CASE 12: strTxt = "ff" CASE 13: strTxt = "cr" CASE 28: strTxt = "fs" CASE 29: strTxt = "gs" CASE 30: strTxt = "rs" CASE 31: strTxt = "us" CASE 32: strTxt = "sp" CASE ELSE: strTxt = CHR$(i) END SELECT END IF rChar(i).Character = strTxt NEXT i ELSE FOR i = 0 TO iMaxIdx rChar(i).Count = 0 NEXT i END IF PRINT "Looking for "; IF iCL = Letters THEN PRINT "letters."; ELSE PRINT "characters."; PRINT " File is"; STR$(lHowMany); " in size. Working"; : COLOR 23: PRINT "..."; : COLOR (7) DO WHILE LOC(iFile) < LOF(iFile) IF LOC(iFile) + LngReg > LOF(iFile) THEN strTxt = SPACE$(LOF(iFile) - LOC(iFile)) END IF GET #iFile, , strTxt FOR i = 1 TO LEN(strTxt) IF iCL = Letters THEN iChar = ASC(UCASE$(MID$(strTxt, i, 1))) SELECT CASE iChar CASE 164: iChar = 165 CASE 160: iChar = 65 CASE 130, 144: iChar = 69 CASE 161: iChar = 73 CASE 162: iChar = 79 CASE 163, 129: iChar = 85 END SELECT iChar = iChar - 65 IF iChar >= 0 AND iChar <= 25 THEN rChar(iChar).Count = rChar(iChar).Count + 1 ELSEIF iChar = 100 THEN rChar(iMaxIdx).Count = rChar(iMaxIdx).Count + 1 END IF ELSE iChar = ASC(MID$(strTxt, i, 1)) rChar(iChar).Count = rChar(iChar).Count + 1 END IF NEXT i LOOP CLOSE #iFile lMUC = 0 iMUI = 0 lLUC = 2147483647 iLUI = 0 iPrint = FALSE lTotChars = 0 iCountChars = 0 iPause = FALSE CLS IF iCL = Letters THEN PRINT "Letters found: "; ELSE PRINT "Characters found: "; FOR i = 0 TO iMaxIdx IF lMUC < rChar(i).Count THEN lMUC = rChar(i).Count iMUI = i END IF IF rChar(i).Count > 0 THEN strTxt = "" IF iPrint THEN strTxt = ", " ELSE iPrint = TRUE strTxt = strTxt + LTRIM$(RTRIM$(rChar(i).Character)) strTxt = strTxt + "=" + LTRIM$(STR$(rChar(i).Count)) iP = POS(0) IF iP + LEN(strTxt) + 1 >= 80 AND iPrint THEN PRINT "," IF CSRLIN >= 23 AND NOT iPause THEN iPause = TRUE PRINT "Press a key to continue..." DO strKey = INKEY$ LOOP UNTIL strKey <> "" END IF strTxt = MID$(strTxt, 3) END IF PRINT strTxt; lTotChars = lTotChars + rChar(i).Count iCountChars = iCountChars + 1 IF lLUC > rChar(i).Count THEN lLUC = rChar(i).Count iLUI = i END IF END IF NEXT i PRINT "." PRINT PRINT "File analyzed....................: "; strFile PRINT "Looked for.......................: "; : IF iCL = Letters THEN PRINT "Letters" ELSE PRINT "Characters" PRINT "Total characters in file.........:"; lHowMany PRINT "Total characters counted.........:"; lTotChars IF iCL = Letters THEN PRINT "Characters discarded on count....:"; lHowMany - lTotChars PRINT "Distinct characters found in file:"; iCountChars; "of"; iMaxIdx + 1 PRINT "Most used character was..........: "; iPrint = FALSE FOR i = 0 TO iMaxIdx IF rChar(i).Count = lMUC THEN IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE PRINT RTRIM$(LTRIM$(rChar(i).Character)); END IF NEXT i PRINT " ("; LTRIM$(STR$(rChar(iMUI).Count)); " times)" PRINT "Least used character was.........: "; iPrint = FALSE FOR i = 0 TO iMaxIdx IF rChar(i).Count = lLUC THEN IF iPrint THEN PRINT ", "; ELSE iPrint = TRUE PRINT RTRIM$(LTRIM$(rChar(i).Character)); END IF NEXT i PRINT " ("; LTRIM$(STR$(rChar(iLUI).Count)); " times)" PRINT "Time spent in the process........:"; TIMER - sTime; "seconds" ELSE CLOSE #iFile KILL strFile PRINT PRINT "File does not exist." END IF PRINT PRINT "Again? (Y/n)" DO strTxt = UCASE$(INKEY$) LOOP UNTIL strTxt = "N" OR strTxt = "Y" OR strTxt = CHR$(13) OR strTxt = CHR$(27) LOOP UNTIL strTxt = "N" OR strTxt = CHR$(27) CLS PRINT "End of execution." PRINT "Start time: "; strDate; " "; strTime; ", end time: "; DATE$; " "; TIME$; "." END
Ensure the translated VB code behaves exactly like the original PHP snippet.
$s = "12345"; $s++;
Dim s As String = "123" s = CStr(CInt("123") + 1) s = (CInt("123") + 1).ToString
Please provide an equivalent version of this PHP code in VB.
<?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"; ?>
Function StripChars(stString As String, stStripChars As String, Optional bSpace As Boolean) Dim i As Integer, stReplace As String If bSpace = True Then stReplace = " " Else stReplace = "" End If For i = 1 To Len(stStripChars) stString = Replace(stString, Mid(stStripChars, i, 1), stReplace) Next i StripChars = stString End Function
Generate a VB translation of this PHP snippet without changing its computational steps.
$nums = array(3, 1, 4, 1, 5, 9); if ($nums) echo array_sum($nums) / count($nums), "\n"; else echo "0\n";
Private Function mean(v() As Double, ByVal leng As Integer) As Variant Dim sum As Double, i As Integer sum = 0: i = 0 For i = 0 To leng - 1 sum = sum + vv Next i If leng = 0 Then mean = CVErr(xlErrDiv0) Else mean = sum / leng End If End Function Public Sub main() Dim v(4) As Double Dim i As Integer, leng As Integer v(0) = 1# v(1) = 2# v(2) = 2.178 v(3) = 3# v(4) = 3.142 For leng = 5 To 0 Step -1 Debug.Print "mean["; For i = 0 To leng - 1 Debug.Print IIf(i, "; " & v(i), "" & v(i)); Next i Debug.Print "] = "; mean(v, leng) Next leng End Sub
Translate the given PHP code snippet into VB without altering its behavior.
<?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); } }
Module ForwardDifference Sub Main() Dim lNum As New List(Of Integer)(New Integer() {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}) For i As UInteger = 0 To 9 Console.WriteLine(String.Join(" ", (From n In Difference(i, lNum) Select String.Format("{0,5}", n)).ToArray())) Next Console.ReadKey() End Sub Private Function Difference(ByVal Level As UInteger, ByVal Numbers As List(Of Integer)) As List(Of Integer) If Level >= Numbers.Count Then Throw New ArgumentOutOfRangeException("Level", "Level must be less than number of items in Numbers") For i As Integer = 1 To Level Numbers = (From n In Enumerable.Range(0, Numbers.Count - 1) _ Select Numbers(n + 1) - Numbers(n)).ToList() Next Return Numbers End Function End Module
Ensure the translated VB code behaves exactly like the original PHP snippet.
<?php function prime($a) { if (($a % 2 == 0 && $a != 2) || $a < 2) return false; $limit = sqrt($a); for ($i = 2; $i <= $limit; $i++) if ($a % $i == 0) return false; return true; } foreach (range(1, 100) as $x) if (prime($x)) echo "$x\n"; ?>
Option Explicit Sub FirstTwentyPrimes() Dim count As Integer, i As Long, t(19) As String Do i = i + 1 If IsPrime(i) Then t(count) = i count = count + 1 End If Loop While count <= UBound(t) Debug.Print Join(t, ", ") End Sub Function IsPrime(Nb As Long) As Boolean If Nb = 2 Then IsPrime = True ElseIf Nb < 2 Or Nb Mod 2 = 0 Then Exit Function Else Dim i As Long For i = 3 To Sqr(Nb) Step 2 If Nb Mod i = 0 Then Exit Function Next IsPrime = True End If End Function
Please provide an equivalent version of this PHP code in VB.
<?php $n=5; $k=3; function factorial($val){ for($f=2;$val-1>1;$f*=$val--); return $f; } $binomial_coefficient=factorial($n)/(factorial($k)*factorial($n-$k)); echo $binomial_coefficient; ?>
Function binomial(n,k) binomial = factorial(n)/(factorial(n-k)*factorial(k)) End Function Function factorial(n) If n = 0 Then factorial = 1 Else For i = n To 1 Step -1 If i = n Then factorial = n Else factorial = factorial * i End If Next End If End Function WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3) WScript.StdOut.WriteLine
Convert the following code from PHP to VB, ensuring the logic remains intact.
<?php $a = array(); # add elements "at the end" array_push($a, 55, 10, 20); print_r($a); # using an explicit key $a['one'] = 1; $a['two'] = 2; print_r($a); ?>
Dim coll As New Collection coll.Add "apple" coll.Add "banana"
Produce a language-to-language conversion: from C# to Java, same semantics.
static void bitwise(int a, int b) { Console.WriteLine("a and b is {0}", a & b); Console.WriteLine("a or b is {0}", a | b); Console.WriteLine("a xor b is {0}", a ^ b); Console.WriteLine("not a is {0}", ~a); Console.WriteLine("a lshift b is {0}", a << b); Console.WriteLine("a arshift b is {0}", a >> b); uint c = (uint)a; Console.WriteLine("c rshift b is {0}", c >> b); }
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())} | ); } } }
Generate an equivalent Java version of this C# code.
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; public class DragonCurve : Form { private List<int> turns; private double startingAngle, side; public DragonCurve(int iter) { Size = new Size(800, 600); StartPosition = FormStartPosition.CenterScreen; DoubleBuffered = true; BackColor = Color.White; startingAngle = -iter * (Math.PI / 4); side = 400 / Math.Pow(2, iter / 2.0); turns = getSequence(iter); } private List<int> getSequence(int iter) { var turnSequence = new List<int>(); for (int i = 0; i < iter; i++) { var copy = new List<int>(turnSequence); copy.Reverse(); turnSequence.Add(1); foreach (int turn in copy) { turnSequence.Add(-turn); } } return turnSequence; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; double angle = startingAngle; int x1 = 230, y1 = 350; int x2 = x1 + (int)(Math.Cos(angle) * side); int y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; foreach (int turn in turns) { angle += turn * (Math.PI / 2); x2 = x1 + (int)(Math.Cos(angle) * side); y2 = y1 + (int)(Math.Sin(angle) * side); e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2); x1 = x2; y1 = y2; } } [STAThread] static void Main() { Application.Run(new DragonCurve(14)); } }
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); } }
Convert the following code from C# to Java, ensuring the logic remains intact.
foreach (string readLine in File.ReadLines("FileName")) DoSomething(readLine);
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) {} } } } } }
Change the programming language of this snippet from C# to Java without modifying what it does.
static void InsertAfter(Link prev, int i) { if (prev.next != null) { prev.next.prev = new Link() { item = i, prev = prev, next = prev.next }; prev.next = prev.next.prev; } else prev.next = new Link() { item = i, prev = prev }; }
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(); } }
Transform the following C# implementation into Java, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; namespace QuickSelect { internal static class Program { #region Static Members private static void Main() { var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; Console.WriteLine( "Loop quick select 10 times." ); for( var i = 0 ; i < 10 ; i++ ) { Console.Write( inputArray.NthSmallestElement( i ) ); if( i < 9 ) Console.Write( ", " ); } Console.WriteLine(); Console.WriteLine( "Just sort 10 elements." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "Get 4 smallest and sort them." ); Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) ); Console.WriteLine( "< Press any key >" ); Console.ReadKey(); } #endregion } internal static class ArrayExtension { #region Static Members public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T> { if( count < 0 ) throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." ); if( count == 0 ) return new T[0]; if( array.Length <= count ) return array; return QuickSelectSmallest( array, count - 1 ).Take( count ); } public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T> { if( n < 0 || n > array.Length - 1 ) throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) ); if( array.Length == 0 ) throw new ArgumentException( "Array is empty.", "array" ); if( array.Length == 1 ) return array[ 0 ]; return QuickSelectSmallest( array, n )[ n ]; } private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T> { var partiallySortedArray = (T[]) input.Clone(); var startIndex = 0; var endIndex = input.Length - 1; var pivotIndex = n; var r = new Random(); while( endIndex > startIndex ) { pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex ); if( pivotIndex == n ) break; if( pivotIndex > n ) endIndex = pivotIndex - 1; else startIndex = pivotIndex + 1; pivotIndex = r.Next( startIndex, endIndex ); } return partiallySortedArray; } private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T> { var pivotValue = array[ pivotIndex ]; array.Swap( pivotIndex, endIndex ); for( var i = startIndex ; i < endIndex ; i++ ) { if( array[ i ].CompareTo( pivotValue ) > 0 ) continue; array.Swap( i, startIndex ); startIndex++; } array.Swap( endIndex, startIndex ); return startIndex; } private static void Swap<T>( this T[] array, int index1, int index2 ) { if( index1 == index2 ) return; var temp = array[ index1 ]; array[ index1 ] = array[ index2 ]; array[ index2 ] = temp; } #endregion } }
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(); } }
Translate this program into Java but keep the logic exactly as in C#.
public static class BaseConverter { public static long stringToLong(string s, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); checked { int slen = s.Length; long result = 0; bool isNegative = false; for ( int i = 0; i < slen; i++ ) { char c = s[i]; int num; if ( c == '-' ) { if ( i != 0 ) throw new ArgumentException("A negative sign is allowed only as the first character of the string.", "s"); isNegative = true; continue; } if ( c > 0x2F && c < 0x3A ) num = c - 0x30; else if ( c > 0x40 && c < 0x5B ) num = c - 0x37; else if ( c > 0x60 && c < 0x7B ) num = c - 0x57; else throw new ArgumentException("The string contains an invalid character '" + c + "'", "s"); if ( num >= b ) throw new ArgumentException("The string contains a character '" + c + "' which is not allowed in base " + b, "s"); result *= b; result += num; } if ( isNegative ) result = -result; return result; } } public static string longToString(long n, int b) { if ( b < 2 || b > 36 ) throw new ArgumentException("Base must be between 2 and 36", "b"); if ( b == 10 ) return n.ToString(); checked { long longBase = b; StringBuilder sb = new StringBuilder(); if ( n < 0 ) { n = -n; sb.Append('-'); } long div = 1; while ( n / div >= b ) div *= b; while ( true ) { byte digit = (byte) (n / div); if ( digit < 10 ) sb.Append((char) (digit + 0x30)); else sb.Append((char) (digit + 0x57)); if ( div == 1 ) break; n %= div; div /= b; } return sb.ToString(); } } }
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); }
Produce a language-to-language conversion: from C# to Java, same semantics.
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>(); directoryStack.Push(new DirectoryInfo(rootPath)); while (directoryStack.Count > 0) { var dir = directoryStack.Pop(); try { foreach (var i in dir.GetDirectories()) directoryStack.Push(i); } catch (UnauthorizedAccessException) { continue; } foreach (var f in dir.GetFiles().Where(Pattern)) yield return f; } } static void Main(string[] args) { foreach (var file in TraverseDirectory(@"C:\Windows", f => f.Extension == ".wmv")) Console.WriteLine(file.FullName); Console.WriteLine("Done."); } } }
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()); } } } } } }
Write the same code in Java as shown below in C#.
public class Crc32 { #region Constants private const UInt32 s_generator = 0xEDB88320; #endregion #region Constructors public Crc32() { m_checksumTable = Enumerable.Range(0, 256).Select(i => { var tableEntry = (uint)i; for (var j = 0; j < 8; ++j) { tableEntry = ((tableEntry & 1) != 0) ? (s_generator ^ (tableEntry >> 1)) : (tableEntry >> 1); } return tableEntry; }).ToArray(); } #endregion #region Methods public UInt32 Get<T>(IEnumerable<T> byteStream) { try { return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8))); } catch (FormatException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (InvalidCastException e) { throw new CrcException("Could not read the stream out as bytes.", e); } catch (OverflowException e) { throw new CrcException("Could not read the stream out as bytes.", e); } } #endregion #region Fields private readonly UInt32[] m_checksumTable; #endregion }
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( ) ) + " !" ) ; } }
Please provide an equivalent version of this C# code in Java.
public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { MyClass instance = new MyClass(); instance.SomeMethod(); instance.Variable = 99; System.Console.WriteLine( "Variable=" + instance.Variable.ToString() ); } }
public class MyClass{ private int variable; public MyClass(){ } public void someMethod(){ this.variable = 1; } }
Translate the given C# code snippet into Java without altering its behavior.
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
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); } }
Can you help me rewrite this code in Java instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; public class KaprekarNumbers { public static void Main() { int count = 0; foreach ( ulong i in _kaprekarGenerator(999999) ) { Console.WriteLine(i); count++; } Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); } private static IEnumerable<ulong> _kaprekarGenerator(ulong max) { ulong next = 1; yield return next; for ( next = 2; next <= max; next++ ) { ulong square = next * next; for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { if ( square <= check ) break; ulong r = square % check; ulong q = (square - r) / check; if ( r != 0 && q + r == next ) { yield return next; break; } } } } }
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 C# to Java with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; namespace HofstadterFigureFigure { class HofstadterFigureFigure { readonly List<int> _r = new List<int>() {1}; readonly List<int> _s = new List<int>(); public IEnumerable<int> R() { int iR = 0; while (true) { if (iR >= _r.Count) { Advance(); } yield return _r[iR++]; } } public IEnumerable<int> S() { int iS = 0; while (true) { if (iS >= _s.Count) { Advance(); } yield return _s[iS++]; } } private void Advance() { int rCount = _r.Count; int oldR = _r[rCount - 1]; int sVal; switch (rCount) { case 1: sVal = 2; break; case 2: sVal = 4; break; default: sVal = _s[rCount - 1]; break; } _r.Add(_r[rCount - 1] + sVal); int newR = _r[rCount]; for (int iS = oldR + 1; iS < newR; iS++) { _s.Add(iS); } } } class Program { static void Main() { var hff = new HofstadterFigureFigure(); var rs = hff.R(); var arr = rs.Take(40).ToList(); foreach(var v in arr.Take(10)) { Console.WriteLine("{0}", v); } var hs = new HashSet<int>(arr); hs.UnionWith(hff.S().Take(960)); Console.WriteLine(hs.Count == 1000 ? "Verified" : "Oops! Something's wrong!"); } } }
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"); } }