Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Keep all operations the same but rewrite the snippet in Perl. | $key2val = ["A"=>"30", "B"=>"31", "C"=>"32", "D"=>"33", "E"=>"5", "F"=>"34", "G"=>"35",
"H"=>"0", "I"=>"36", "J"=>"37", "K"=>"38", "L"=>"2", "M"=>"4", "."=>"78", "N"=>"39",
"/"=>"79", "O"=>"1", "0"=>"790", "P"=>"70", "1"=>"791", "Q"=>"71", "2"=>"792",
"R"=>"8", "3"=>"793", "S"=>"6", "4"=>"794", ... | use strict;
use warnings;
use feature 'say';
use List::Util <min max>;
my(%encode,%decode,@table);
sub build {
my($u,$v,$alphabet) = @_;
my(@flat_board,%p2c,%c2p);
my $numeric_escape = '/';
@flat_board = split '', uc $alphabet;
splice @flat_board, min($u,$v), 0, undef;
splice @flat_board, max... |
Produce a functionally identical Perl code for the snippet given in PHP. | <?php
class Example {
function foo() {
echo "this is foo\n";
}
function bar() {
echo "this is bar\n";
}
function __call($name, $args) {
echo "tried to handle unknown method $name\n";
if ($args)
echo "it had arguments: ", implode(', ', $args), "\n";
}
}
$example = new Example();
$exam... | package Example;
sub new {
bless {}
}
sub foo {
print "this is foo\n";
}
sub bar {
print "this is bar\n";
}
sub AUTOLOAD {
my $name = $Example::AUTOLOAD;
my ($self, @args) = @_;
print "tried to handle unknown method $name\n";
if (@args) {
print "it had arguments: @args\n";
}
}
su... |
Rewrite the snippet below in Perl so it works the same as the original PHP code. | <?php
function is_prime($n) {
if ($n <= 3) {
return $n > 1;
} elseif (($n % 2 == 0) or ($n % 3 == 0)) {
return false;
}
$i = 5;
while ($i * $i <= $n) {
if ($n % $i == 0) {
return false;
}
$i += 2;
if ($n % $i == 0) {
return fal... | use ntheory qw/forprimes is_mersenne_prime/;
forprimes { is_mersenne_prime($_) && say } 1e9;
|
Write the same algorithm in Perl as shown in this PHP implementation. | <?php
function is_prime($n) {
if ($n <= 3) {
return $n > 1;
} elseif (($n % 2 == 0) or ($n % 3 == 0)) {
return false;
}
$i = 5;
while ($i * $i <= $n) {
if ($n % $i == 0) {
return false;
}
$i += 2;
if ($n % $i == 0) {
return fal... | use ntheory qw/forprimes is_mersenne_prime/;
forprimes { is_mersenne_prime($_) && say } 1e9;
|
Convert this PHP block to Perl, preserving its control flow and logic. | <?php
function hashJoin($table1, $index1, $table2, $index2) {
foreach ($table1 as $s)
$h[$s[$index1]][] = $s;
foreach ($table2 as $r)
foreach ($h[$r[$index2]] as $s)
$result[] = array($s, $r);
return $result;
}
$table1 = array(array(27, "Jonah"),
array(18, "Alan"),
... | use Data::Dumper qw(Dumper);
sub hashJoin {
my ($table1, $index1, $table2, $index2) = @_;
my %h;
foreach my $s (@$table1) {
push @{ $h{$s->[$index1]} }, $s;
}
map { my $r = $_;
map [$_, $r], @{ $h{$r->[$index2]} }
} @$table2;
}
@table1 = ([27, "Jonah"],
[18, "Alan"],
... |
Translate the given PHP code snippet into Perl without altering its behavior. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array... | use Algorithm::Combinatorics qw/tuples_with_repetition/;
print join(" ", map { "[@$_]" } tuples_with_repetition([qw/A B C/],2)), "\n";
|
Rewrite the snippet below in Perl so it works the same as the original PHP code. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array... | use Algorithm::Combinatorics qw/tuples_with_repetition/;
print join(" ", map { "[@$_]" } tuples_with_repetition([qw/A B C/],2)), "\n";
|
Produce a language-to-language conversion: from PHP to Perl, same semantics. | <?php
<?php
$mac_use_espeak = false;
$voice = "espeak";
$statement = 'Hello World!';
$save_file_args = '-w HelloWorld.wav'; // eSpeak args
$OS = strtoupper(substr(PHP_OS, 0, 3));
elseif($OS === 'DAR' && $mac_use_espeak == false) {
$voice = "say -v 'Victoria'";
$save_file_args = '-o HelloWorl... | use Speech::Synthesis;
($engine) = Speech::Synthesis->InstalledEngines();
($voice) = Speech::Synthesis->InstalledVoices(engine => $engine);
Speech::Synthesis
->new(engine => $engine, voice => $voice->{id})
->speak("This is an example of speech synthesis.");
|
Write the same code in Perl as shown below in PHP. | <?php
define('MINEGRID_WIDTH', 6);
define('MINEGRID_HEIGHT', 4);
define('MINESWEEPER_NOT_EXPLORED', -1);
define('MINESWEEPER_MINE', -2);
define('MINESWEEPER_FLAGGED', -3);
define('MINESWEEPER_FLAGGED_MINE', -4);
define('ACTIVATED_MINE', -5);
function check_field($field) {
if ($field === MI... |
use warnings;
use strict;
{ package Local::Field;
use constant {
REAL => 0,
SHOW => 1,
COUNT => 2,
};
sub new {
my ($class, $width, $height, $percent) = @_;
my $field;
for my $x (1 .. $width) {
for my $y (1 .. $height) {
$fi... |
Produce a language-to-language conversion: from PHP to Perl, same semantics. | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$... | use 5.020;
use feature qw<signatures>;
no warnings qw<experimental::signatures>;
use constant zero => sub ($f) {
sub ($x) { $x }};
use constant succ => sub ($n) {
sub ($f) {
sub ($x) { $f->($n->($f)($x)) }}};
use constant add => sub ($n) {
... |
Port the provided PHP code into Perl while preserving the original functionality. | <?php
$zero = function($f) { return function ($x) { return $x; }; };
$succ = function($n) {
return function($f) use (&$n) {
return function($x) use (&$n, &$f) {
return $f( ($n($f))($x) );
};
};
};
$add = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$... | use 5.020;
use feature qw<signatures>;
no warnings qw<experimental::signatures>;
use constant zero => sub ($f) {
sub ($x) { $x }};
use constant succ => sub ($n) {
sub ($f) {
sub ($x) { $f->($n->($f)($x)) }}};
use constant add => sub ($n) {
... |
Write the same algorithm in Perl as shown in this PHP implementation. | <?
class Foo {
function bar(int $x) {
}
}
$method_names = get_class_methods('Foo');
foreach ($method_names as $name) {
echo "$name\n";
$method_info = new ReflectionMethod('Foo', $name);
echo $method_info;
}
?>
| package Nums;
use overload ('<=>' => \&compare);
sub new { my $self = shift; bless [@_] }
sub flip { my @a = @_; 1/$a }
sub double { my @a = @_; 2*$a }
sub compare { my ($a, $b) = @_; abs($a) <=> abs($b) }
my $a = Nums->new(42);
print "$_\n" for %{ref ($a)."::" });
|
Convert this PHP block to Perl, preserving its control flow and logic. | <?php
class Example {
function foo($x) {
return 42 + $x;
}
}
$example = new Example();
$name = 'foo';
echo $example->$name(5), "\n"; // prints "47"
echo call_user_func(array($example, $name), 5), "\n";
?>
| package Example;
sub new {
bless {}
}
sub foo {
my ($self, $x) = @_;
return 42 + $x;
}
package main;
my $name = "foo";
print Example->new->$name(5), "\n";
|
Translate this program into Perl but keep the logic exactly as in PHP. | function perpendicular_distance(array $pt, array $line) {
$dx = $line[1][0] - $line[0][0];
$dy = $line[1][1] - $line[0][1];
$mag = sqrt($dx * $dx + $dy * $dy);
if ($mag > 0) {
$dx /= $mag;
$dy /= $mag;
}
$pvx = $pt[0] - $line[0][0];
$pvy = $pt[1] - $line[0][1];
$pvdot = $dx * $pvx + $dy * $pvy... | use strict;
use warnings;
use feature 'say';
use List::MoreUtils qw(firstidx minmax);
my $epsilon = 1;
sub norm {
my(@list) = @_;
my $sum;
$sum += $_**2 for @list;
sqrt($sum)
}
sub perpendicular_distance {
our(@start,@end,@point);
local(*start,*end,*point) = (shift, shift, shift);
return ... |
Port the following code from PHP to Perl with equivalent syntax and logic. | function perpendicular_distance(array $pt, array $line) {
$dx = $line[1][0] - $line[0][0];
$dy = $line[1][1] - $line[0][1];
$mag = sqrt($dx * $dx + $dy * $dy);
if ($mag > 0) {
$dx /= $mag;
$dy /= $mag;
}
$pvx = $pt[0] - $line[0][0];
$pvy = $pt[1] - $line[0][1];
$pvdot = $dx * $pvx + $dy * $pvy... | use strict;
use warnings;
use feature 'say';
use List::MoreUtils qw(firstidx minmax);
my $epsilon = 1;
sub norm {
my(@list) = @_;
my $sum;
$sum += $_**2 for @list;
sqrt($sum)
}
sub perpendicular_distance {
our(@start,@end,@point);
local(*start,*end,*point) = (shift, shift, shift);
return ... |
Produce a functionally identical Perl code for the snippet given in PHP. | <?php
$l = ldap_connect('ldap.example.com');
ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($l, LDAP_OPT_REFERRALS, false);
$bind = ldap_bind($l, 'me@example.com', 'password');
$base = 'dc=example, dc=com';
$criteria = '(&(objectClass=user)(sAMAccountName=username))';
$attributes = array('display... |
use strict;
use warnings;
use Net::LDAP;
my $ldap = Net::LDAP->new( 'ldap://ldap.forumsys.com' ) or die "$@";
my $mesg = $ldap->bind( "cn=read-only-admin,dc=example,dc=com",
password => "password" );
$mesg->code and die $mesg->error;
my $srch = $ldap->sear... |
Please provide an equivalent version of this PHP code in Perl. | <?
class Foo {
}
$obj = new Foo();
$obj->bar = 42;
$obj->baz = true;
var_dump(get_object_vars($obj));
?>
| {
package Point;
use Class::Spiffy -base;
field 'x';
field 'y';
}
{
package Circle;
use base qw(Point);
field 'r';
}
my $p1 = Point->new(x => 8, y => -5);
my $c1 = Circle->new(r => 4);
my $c2 = Circle->new(x => 1, y => 2, r => 3);
use Data::Dumper;
say Dumper $p1;
say Dumper $c1;
... |
Please provide an equivalent version of this PHP code in Perl. | <?php
function markovChainTextGenerator($text, $keySize, $maxWords) {
$token = array();
$position = 0;
$maxPosition = strlen($text);
while ($position < $maxPosition) {
if (preg_match('/^(\S+)/', substr($text, $position, 25), $matches)) {
$token[] = $matches[1];
$positio... | use strict;
use warnings;
my $file = shift || 'alice_oz.txt';
my $n = shift || 3;
my $max = shift || 200;
sub build_dict {
my ($n, @words) = @_;
my %dict;
for my $i (0 .. $
my @prefix = @words[$i .. $i+$n-1];
push @{$dict{join ' ', @prefix}}, $words[$i+$n];
}
return %dict;
}
s... |
Produce a language-to-language conversion: from PHP to Perl, same semantics. |
function RGBtoHSV($r, $g, $b) {
$r = $r/255.; // convert to range 0..1
$g = $g/255.;
$b = $b/255.;
$cols = array("r" => $r, "g" => $g, "b" => $b);
asort($cols, SORT_NUMERIC);
$min = key(array_slice($cols, 1)); // "r", "g" or "b"
$max = key(array_slice($cols, -1)); // "r", "g" or "b"
if($cols[$min] == $cols[$m... |
use strict;
use warnings;
use lib '/home/hkdtam/lib';
use Image::EdgeDetect;
my $detector = Image::EdgeDetect->new();
$detector->process('./input.jpg', './output.jpg') or die;
|
Port the following code from PHP to Perl with equivalent syntax and logic. | function ownCalcPass($password, $nonce) {
$msr = 0x7FFFFFFF;
$m_1 = (int)0xFFFFFFFF;
$m_8 = (int)0xFFFFFFF8;
$m_16 = (int)0xFFFFFFF0;
$m_128 = (int)0xFFFFFF80;
$m_16777216 = (int)0xFF000000;
$flag = True;
$num1 = 0;
$num2 = 0;
foreach (str_split($nonce) as $c) {
$num1 = ... | use strict;
use warnings;
use feature 'say';
use integer;
sub own_password {
my($password, $nonce) = @_;
my $n1 = 0;
my $n2 = $password;
for my $d (split //, $nonce) {
if ($d == 1) {
$n1 = ($n2 & 0xFFFFFF80) >> 7;
$n2 <<= 25;
} elsif ($d == 2) {
... |
Change the programming language of this snippet from PHP to Perl without modifying what it does. | $tests = array(
'this URI contains an illegal character, parentheses and a misplaced full stop:',
'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',
'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',
'")" is handled t... |
use strict;
use warnings;
use Regexp::Common qw /URI/;
while ( my $line = <DATA> ) {
chomp $line;
my @URIs = $line =~ /$RE{URI}/g and print "URI(s) found.\n";
foreach my $uri (@URIs) { print "URI : $uri\n" }
}
|
Convert this PHP snippet to Perl and keep its semantics consistent. | $tests = array(
'this URI contains an illegal character, parentheses and a misplaced full stop:',
'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',
'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',
'")" is handled t... |
use strict;
use warnings;
use Regexp::Common qw /URI/;
while ( my $line = <DATA> ) {
chomp $line;
my @URIs = $line =~ /$RE{URI}/g and print "URI(s) found.\n";
foreach my $uri (@URIs) { print "URI : $uri\n" }
}
|
Produce a functionally identical Perl code for the snippet given in PHP. | libxml_use_internal_errors(true);
$xml = new DOMDocument();
$xml->load('shiporder.xml');
if (!$xml->schemaValidate('shiporder.xsd')) {
var_dump(libxml_get_errors()); exit;
} else {
echo 'success';
}
|
use 5.018_002;
use warnings;
use Try::Tiny;
use XML::LibXML;
our $VERSION = 1.000_000;
my $parser = XML::LibXML->new();
my $good_xml = '<a>5</a>';
my $bad_xml = '<a>5<b>foobar</b></a>';
my $xmlschema_markup = <<'END';
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="a"... |
Convert the following code from PHP to Perl, ensuring the logic remains intact. | class WriterMonad {
private $value;
private $logs;
private function __construct($value, array $logs = []) {
$this->value = $value;
$this->logs = $logs;
}
public static function unit($value, string $log): WriterMonad {
return new WriterMonad($value, ["{$log}: {$value}"]);
}
public function bind(call... |
package Writer;
use strict;
use warnings;
sub new {
my ($class, $value, $log) = @_;
return bless [ $value => $log ], $class;
}
sub Bind {
my ($self, $code) = @_;
my ($value, $log) = @$self;
my $n = $code->($value);
return Writer->new( @$n[0], $log.@$n[1] );
}
sub Unit { Writer->new($_[0], sprint... |
Write the same algorithm in Perl as shown in this PHP implementation. | <?php
class PeriodicTable
{
private $aArray = array(1, 2, 5, 13, 57, 72, 89, 104);
private $bArray = array(-1, 15, 25, 35, 72, 21, 58, 7);
public function rowAndColumn($n)
{
$i = 7;
while ($this->aArray[$i] > $n)
$i--;
$m = $n + $this->bArray[$i];
... | use strict;
use warnings; no warnings 'uninitialized';
use feature 'say';
use List::Util <sum head>;
sub divmod { int $_[0]/$_[1], $_[0]%$_[1] }
my $b = 18;
my(@offset,@span,$cnt);
push @span, ($cnt++) x $_ for <1 3 8 44 15 17 15 15>;
@offset = (16, 10, 10, (2*$b)+1, (-2*$b)-15, (2*$b)+1, (-2*$b)-15);
for my $n (<1 ... |
Change the programming language of this snippet from PHP to Perl without modifying what it does. | function connect_db($database, $db_user, $db_password, $host = 'localhost', $port = NULL, $die = false) {
if(!$db_handle = @mysql_connect($host.($port ? ':'.$port : ''), $db_user, $db_password)) {
if($die)
die("Can't connect to MySQL server:\r\n".mysql_error());
else
return false;
}
if(!@mysql_select_... | use DBI;
sub connect_db {
my ($dbname, $host, $user, $pass) = @_;
my $db = DBI->connect("dbi:mysql:$dbname:$host", $user, $pass)
or die $DBI::errstr;
$db->{RaiseError} = 1;
$db
}
sub create_user {
my ($db, $user, $pass) = @_;
my $salt = pack "C*", map {int rand 256} 1..16;
$d... |
Change the following C++ code into Julia without altering its purpose. | #include <iostream>
#include <sstream>
#include <set>
bool checkDec(int num) {
std::set<int> set;
std::stringstream ss;
ss << num;
auto str = ss.str();
for (int i = 0; i < str.size(); ++i) {
char c = str[i];
int d = c - '0';
if (d == 0) return false;
if (num % d !=... | function main()
num = 9876432
dif = [4, 2, 2, 2]
local k = 1
@label start
local str = dec(num)
for (i, ch) in enumerate(str)
if ch in ('0', '5') || num % (ch - '0') != 0
num -= dif[k]
k = (k + 1) % 4 + 1
@goto start
end
for j in i+1:end... |
Transform the following C++ implementation into Julia, maintaining the same output and logic. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int jacobi(int n, int k) {
assert(k > 0 && k % 2 == 1);
n %= k;
int t = 1;
while (n != 0) {
while (n % 2 == 0) {
n /= 2;
int r = k % 8;
if (r == 3 || r == 5)
t = -t... | function jacobi(a, n)
a %= n
result = 1
while a != 0
while iseven(a)
a ÷= 2
((n % 8) in [3, 5]) && (result *= -1)
end
a, n = n, a
(a % 4 == n % 4 == 3) && (result *= -1)
a %= n
end
return n == 1 ? result : 0
end
print(" Table of jac... |
Convert this C++ snippet to Julia and keep its semantics consistent. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int jacobi(int n, int k) {
assert(k > 0 && k % 2 == 1);
n %= k;
int t = 1;
while (n != 0) {
while (n % 2 == 0) {
n /= 2;
int r = k % 8;
if (r == 3 || r == 5)
t = -t... | function jacobi(a, n)
a %= n
result = 1
while a != 0
while iseven(a)
a ÷= 2
((n % 8) in [3, 5]) && (result *= -1)
end
a, n = n, a
(a % 4 == n % 4 == 3) && (result *= -1)
a %= n
end
return n == 1 ? result : 0
end
print(" Table of jac... |
Write a version of this C++ function in Julia with identical behavior. | #include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *i... | using LinearAlgebra
|
Rewrite the snippet below in Julia so it works the same as the original C++ code. | #include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *i... | using LinearAlgebra
|
Generate a Julia translation of this C++ snippet without changing its computational steps. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
... | using Primes
function deceptives(numwanted)
n, r, ret = 2, big"1", Int[]
while length(ret) < numwanted
!isprime(n) && r % n == 0 && push!(ret, n)
n += 1
r = 10r + 1
end
return ret
end
@time println(deceptives(30))
|
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically? | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
... | using Primes
function deceptives(numwanted)
n, r, ret = 2, big"1", Int[]
while length(ret) < numwanted
!isprime(n) && r % n == 0 && push!(ret, n)
n += 1
r = 10r + 1
end
return ret
end
@time println(deceptives(30))
|
Translate this program into Julia but keep the logic exactly as in C++. | #include <iostream>
int digitSum(int n) {
int s = 0;
do {s += n % 10;} while (n /= 10);
return s;
}
int main() {
for (int i=0; i<1000; i++) {
auto s_i = std::to_string(i);
auto s_ds = std::to_string(digitSum(i));
if (s_i.find(s_ds) != std::string::npos) {
std::cout ... | issumsub(n, base=10) = occursin(string(sum(digits(n, base=base)), base=base), string(n, base=base))
foreach(p -> print(rpad(p[2], 4), p[1] % 10 == 0 ? "\n" : ""), enumerate(filter(issumsub, 0:999)))
|
Write the same code in Julia as shown below in C++. | #include <ctime>
#include <string>
#include <iostream>
#include <algorithm>
class cycle{
public:
template <class T>
void cy( T* a, int len ) {
int i, j;
show( "original: ", a, len );
std::srand( unsigned( time( 0 ) ) );
for( int i = len - 1; i > 0; i-- ) {
do {
... | function sattolocycle!(arr::Array, last::Int=length(arr))
for i in last:-1:2
j = rand(1:i-1)
arr[i], arr[j] = arr[j], arr[i]
end
return arr
end
@show sattolocycle!([])
@show sattolocycle!([10])
@show sattolocycle!([10, 20, 30])
@show sattolocycle!([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21... |
Generate an equivalent Julia version of this C++ code. | #include <ctime>
#include <string>
#include <iostream>
#include <algorithm>
class cycle{
public:
template <class T>
void cy( T* a, int len ) {
int i, j;
show( "original: ", a, len );
std::srand( unsigned( time( 0 ) ) );
for( int i = len - 1; i > 0; i-- ) {
do {
... | function sattolocycle!(arr::Array, last::Int=length(arr))
for i in last:-1:2
j = rand(1:i-1)
arr[i], arr[j] = arr[j], arr[i]
end
return arr
end
@show sattolocycle!([])
@show sattolocycle!([10])
@show sattolocycle!([10, 20, 30])
@show sattolocycle!([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21... |
Write a version of this C++ function in Julia with identical behavior. |
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <sys/stat.h>
#include <ftplib.h>
#include <ftp++.hpp>
int stat(const char *pathname, struct stat *buf);
char *strerror(int errnum);
char *basename(char *path);
namespace stl
{
using std::cout; ... | using FTPClient
ftp = FTP(hostname = "ftp.ed.ac.uk", username = "anonymous")
cd(ftp, "pub/courses")
println(readdir(ftp))
bytes = read(download(ftp, "make.notes.tar"))
close(ftp)
|
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically? | #include <time.h>
#include <iostream>
#include <vector>
using namespace std;
class cSort
{
public:
void doIt( vector<unsigned> s )
{
sq = s; display(); c_sort();
cout << "writes: " << wr << endl; display();
}
private:
void display()
{
copy( sq.begin(), sq.end(), ostream_iterator<unsigned>( std... | function cyclesort!(v::Vector)
writes = 0
for (cyclestart, item) in enumerate(v)
pos = cyclestart
for item2 in v[cyclestart + 1:end]
if item2 < item pos += 1 end
end
if pos == cyclestart continue end
while item == v[pos]
pos += 1
end
... |
Translate this program into Julia but keep the logic exactly as in C++. | #include <time.h>
#include <iostream>
#include <vector>
using namespace std;
class cSort
{
public:
void doIt( vector<unsigned> s )
{
sq = s; display(); c_sort();
cout << "writes: " << wr << endl; display();
}
private:
void display()
{
copy( sq.begin(), sq.end(), ostream_iterator<unsigned>( std... | function cyclesort!(v::Vector)
writes = 0
for (cyclestart, item) in enumerate(v)
pos = cyclestart
for item2 in v[cyclestart + 1:end]
if item2 < item pos += 1 end
end
if pos == cyclestart continue end
while item == v[pos]
pos += 1
end
... |
Change the programming language of this snippet from C++ to Julia without modifying what it does. | #include <cstdint>
#include <iostream>
#include <string>
#include <primesieve.hpp>
void print_twin_prime_count(long long limit) {
std::cout << "Number of twin prime pairs less than " << limit
<< " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n';
}
int main(int argc, char** argv) {
... | using Formatting, Primes
function counttwinprimepairsbetween(n1, n2)
npairs, t = 0, nextprime(n1)
while t < n2
p = nextprime(t + 1)
if p - t == 2
npairs += 1
end
t = p
end
return npairs
end
for t2 in (10).^collect(2:8)
paircount = counttwinprimepairsbetw... |
Ensure the translated Julia code behaves exactly like the original C++ snippet. | #include <iostream>
bool sameDigits(int n, int b) {
int f = n % b;
while ((n /= b) > 0) {
if (n % b != f) {
return false;
}
}
return true;
}
bool isBrazilian(int n) {
if (n < 7) return false;
if (n % 2 == 0)return true;
for (int b = 2; b < n - 1; b++) {
... | using Primes, Lazy
function samedigits(n, b)
n, f = divrem(n, b)
while n > 0
n, f2 = divrem(n, b)
if f2 != f
return false
end
end
true
end
isbrazilian(n) = n >= 7 && (iseven(n) || any(b -> samedigits(n, b), 2:n-2))
brazilians = filter(isbrazilian, Lazy.range())
oddb... |
Rewrite the snippet below in Julia so it works the same as the original C++ code. | #include <iostream>
bool sameDigits(int n, int b) {
int f = n % b;
while ((n /= b) > 0) {
if (n % b != f) {
return false;
}
}
return true;
}
bool isBrazilian(int n) {
if (n < 7) return false;
if (n % 2 == 0)return true;
for (int b = 2; b < n - 1; b++) {
... | using Primes, Lazy
function samedigits(n, b)
n, f = divrem(n, b)
while n > 0
n, f2 = divrem(n, b)
if f2 != f
return false
end
end
true
end
isbrazilian(n) = n >= 7 && (iseven(n) || any(b -> samedigits(n, b), 2:n-2))
brazilians = filter(isbrazilian, Lazy.range())
oddb... |
Change the following C++ code into Julia without altering its purpose. | #include <iostream>
#include <fstream>
#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif
int main() {
std::filebuf fb;
fb.open(FILENAME,std::ios::out);
std::ostream os(&fb);
os << "Hello World\n";
fb.close();
return... | open("/dev/tape", "w") do f
write(f, "Hello tape!")
end
|
Write a version of this C++ function in Julia with identical behavior. | #include <iostream>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto i = v.cbegin();
auto e = v.cend();
os << '[';
if (i != e) {
os << *i;
i = std::next(i);
}
while (i != e) {
... | function recaman()
a = Vector{Int}([0])
used = Dict{Int, Bool}(0 => true)
used1000 = Set(0)
founddup = false
termcount = 1
while length(used1000) <= 1000
nextterm = a[termcount] - termcount
if nextterm < 1 || haskey(used, nextterm)
nextterm += termcount + termcount
... |
Port the provided C++ code into Julia while preserving the original functionality. | #include <iostream>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto i = v.cbegin();
auto e = v.cend();
os << '[';
if (i != e) {
os << *i;
i = std::next(i);
}
while (i != e) {
... | function recaman()
a = Vector{Int}([0])
used = Dict{Int, Bool}(0 => true)
used1000 = Set(0)
founddup = false
termcount = 1
while length(used1000) <= 1000
nextterm = a[termcount] - termcount
if nextterm < 1 || haskey(used, nextterm)
nextterm += termcount + termcount
... |
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically? | #include <iostream>
#include <functional>
template <typename F>
struct RecursiveFunc {
std::function<F(RecursiveFunc)> o;
};
template <typename A, typename B>
std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) {
RecursiveFunc<std::function<B(A)>> r = {
std::function<std::function<B(... | _
_ _ _(_)_ | Documentation: https://docs.julialang.org
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.6.3 (2021-09-23)
_/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release
|_... |
Transform the following C++ implementation into Julia, maintaining the same output and logic. | #include <iostream>
class factorion_t {
public:
factorion_t() {
f[0] = 1u;
for (uint n = 1u; n < 12u; n++)
f[n] = f[n - 1] * n;
}
bool operator()(uint i, uint b) const {
uint sum = 0;
for (uint j = i; j > 0u; j /= b)
sum += f[j % b];
return s... | isfactorian(n, base) = mapreduce(factorial, +, map(c -> parse(Int, c, base=16), split(string(n, base=base), ""))) == n
printallfactorian(base) = println("Factorians for base $base: ", [n for n in 1:100000 if isfactorian(n, base)])
foreach(printallfactorian, 9:12)
|
Convert the following code from C++ to Julia, ensuring the logic remains intact. | #include <iostream>
class factorion_t {
public:
factorion_t() {
f[0] = 1u;
for (uint n = 1u; n < 12u; n++)
f[n] = f[n - 1] * n;
}
bool operator()(uint i, uint b) const {
uint sum = 0;
for (uint j = i; j > 0u; j /= b)
sum += f[j % b];
return s... | isfactorian(n, base) = mapreduce(factorial, +, map(c -> parse(Int, c, base=16), split(string(n, base=base), ""))) == n
printallfactorian(base) = println("Factorians for base $base: ", [n for n in 1:100000 if isfactorian(n, base)])
foreach(printallfactorian, 9:12)
|
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version. | #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0;... | using Primes
function sumdivisors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
return sum(f)
end
for i in 1:100
print(rpad(sumdivisors(i), 5), i % 25 == 0 ? " \n" : "")
end
|
Generate an equivalent Julia version of this C++ code. | #include <iomanip>
#include <iostream>
unsigned int divisor_sum(unsigned int n) {
unsigned int total = 1, power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
total += power;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int sum = 1;
for (power = p; n % p == 0;... | using Primes
function sumdivisors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
return sum(f)
end
for i in 1:100
print(rpad(sumdivisors(i), 5), i % 25 == 0 ? " \n" : "")
end
|
Write a version of this C++ function in Julia with identical behavior. | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool InteractiveCompare(const string& s1, const string& s2)
{
if(s1 == s2) return false;
static int count = 0;
string response;
cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
getline(cin, response);
... | const nrequests = [0]
const ordering = Dict("violet" => 7, "red" => 1, "green" => 4, "indigo" => 6, "blue" => 5,
"yellow" => 3, "orange" => 2)
function tellmeifgt(x, y)
nrequests[1] += 1
while true
print("Is $x greater than $y? (Y/N) => ")
s = strip(readline())
i... |
Transform the following C++ implementation into Julia, maintaining the same output and logic. | #include <iostream>
#include <vector>
#include <boost/integer/common_factor.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/miller_rabin.hpp>
typedef boost::multiprecision::cpp_int integer;
integer fermat(unsigned int n) {
unsigned int p = 1;
for (unsigned int i = 0; i < n; ++i... | using Primes
fermat(n) = BigInt(2)^(BigInt(2)^n) + 1
prettyprint(fdict) = replace(replace(string(fdict), r".+\(([^)]+)\)" => s"\1"), r"\=\>" => "^")
function factorfermats(max, nofactor=false)
for n in 0:max
fm = fermat(n)
if nofactor
println("Fermat number F($n) is $fm.")
... |
Write the same code in Julia as shown below in C++. |
#include <iostream>
#include <vector>
using std::cout;
using std::vector;
void distribute(int dist, vector<int> &List) {
if (dist > List.size() )
List.resize(dist);
for (int i=0; i < dist; i++)
List[i]++;
}
vector<int> beadSort(int *myints, int n) {
vector<int> list, list2, fifth ... | function beadsort(a::Vector{<:Integer})
lo, hi = extrema(a)
if lo < 1 throw(DomainError()) end
len = length(a)
abacus = falses(len, hi)
for (i, v) in enumerate(a)
abacus[i, 1:v] = true
end
for i in 1:hi
v = sum(abacus[:, i])
if v < len
abacus[1:end-v, i] = ... |
Convert this C++ block to Julia, preserving its control flow and logic. |
#include <iostream>
int main() {
int Base = 10;
const int N = 2;
int c1 = 0;
int c2 = 0;
for (int k=1; k<pow((double)Base,N); k++){
c1++;
if (k%(Base-1) == (k*k)%(Base-1)){
c2++;
std::cout << k << " ";
}
}
std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 ... | co9(x) = x == 9 ? 0 :
1<=x<=8 ? x :
co9(sum(digits(x)))
|
Translate this program into Julia but keep the logic exactly as in C++. |
#include <iostream>
int main() {
int Base = 10;
const int N = 2;
int c1 = 0;
int c2 = 0;
for (int k=1; k<pow((double)Base,N); k++){
c1++;
if (k%(Base-1) == (k*k)%(Base-1)){
c2++;
std::cout << k << " ";
}
}
std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 ... | co9(x) = x == 9 ? 0 :
1<=x<=8 ? x :
co9(sum(digits(x)))
|
Generate a Julia translation of this C++ snippet without changing its computational steps. | void runCode(string code)
{
int c_len = code.length();
unsigned accumulator=0;
int bottles;
for(int i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
cout << code << endl;
break;
case 'H':
cout << "Hello, world!" <... | hello() = println("Hello, world!")
quine() = println(src)
bottles() = for i = 99:-1:1 print("\n$i bottles of beer on the wall\n$i bottles of beer\nTake one down, pass it around\n$(i-1) bottles of beer on the wall\n") end
acc = 0
incr() = global acc += 1
const dispatch = Dict(
'h' => hello,
'q' => quine,
'9' => ... |
Change the programming language of this snippet from C++ to Julia without modifying what it does. | void runCode(string code)
{
int c_len = code.length();
unsigned accumulator=0;
int bottles;
for(int i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
cout << code << endl;
break;
case 'H':
cout << "Hello, world!" <... | hello() = println("Hello, world!")
quine() = println(src)
bottles() = for i = 99:-1:1 print("\n$i bottles of beer on the wall\n$i bottles of beer\nTake one down, pass it around\n$(i-1) bottles of beer on the wall\n") end
acc = 0
incr() = global acc += 1
const dispatch = Dict(
'h' => hello,
'q' => quine,
'9' => ... |
Ensure the translated Julia code behaves exactly like the original C++ snippet. | #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
... | using Primes
function numfactors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
length(f)
end
for i in 1:100
print(rpad(numfactors(i), 3), i % 25 == 0 ? " \n" : " ")
end
|
Write a version of this C++ function in Julia with identical behavior. | #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
... | using Primes
function numfactors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
length(f)
end
for i in 1:100
print(rpad(numfactors(i), 3), i % 25 == 0 ? " \n" : " ")
end
|
Generate an equivalent Julia version of this C++ code. | #include <iomanip>
#include <iostream>
#include <vector>
constexpr int MU_MAX = 1'000'000;
std::vector<int> MU;
int mobiusFunction(int n) {
if (!MU.empty()) {
return MU[n];
}
MU.resize(MU_MAX + 1, 1);
int root = sqrt(MU_MAX);
for (int i = 2; i <= root; i++) {
if (MU[i] == 1)... | using Primes
function moebius(n::Integer)
@assert n > 0
m(p, e) = p == 0 ? 0 : e == 1 ? -1 : 0
reduce(*, m(p, e) for (p, e) in factor(n) if p ≥ 0; init=1)
end
μ(n) = moebius(n)
print("First 199 terms of the Möbius sequence:\n ")
for n in 1:199
print(lpad(μ(n), 3), n % 20 == 19 ? "\n" : "")
end
|
Convert this C++ block to Julia, preserving its control flow and logic. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;... | isCurzon(n, k) = (BigInt(k)^n + 1) % (k * n + 1) == 0
function printcurzons(klow, khigh)
for k in filter(iseven, klow:khigh)
n, curzons = 0, Int[]
while length(curzons) < 1000
isCurzon(n, k) && push!(curzons, n)
n += 1
end
println("Curzon numbers with k = $k:... |
Preserve the algorithm and functionality while converting the code from C++ to Julia. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) {
if (mod == 1)
return 0;
uint64_t result = 1;
base %= mod;
for (; exp > 0; exp >>= 1) {
if ((exp & 1) == 1)
result = (result * base) % mod;... | isCurzon(n, k) = (BigInt(k)^n + 1) % (k * n + 1) == 0
function printcurzons(klow, khigh)
for k in filter(iseven, klow:khigh)
n, curzons = 0, Int[]
while length(curzons) < 1000
isCurzon(n, k) && push!(curzons, n)
n += 1
end
println("Curzon numbers with k = $k:... |
Generate a Julia translation of this C++ snippet without changing its computational steps. | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> mertens_numbers(int max) {
std::vector<int> m(max + 1, 1);
for (int n = 2; n <= max; ++n) {
for (int k = 2; k <= n; ++k)
m[n] -= m[n / k];
}
return m;
}
int main() {
const int max = 1000;
auto m(merte... | using Primes, Formatting
function moebius(n::Integer)
@assert n > 0
m(p, e) = p == 0 ? 0 : e == 1 ? -1 : 0
return reduce(*, m(p, e) for (p, e) in factor(n) if p ≥ 0; init=1)
end
μ(n) = moebius(n)
mertens(x) = sum(n -> μ(n), 1:x)
M(x) = mertens(x)
print("First 99 terms of the Mertens function for positiv... |
Convert this C++ block to Julia, preserving its control flow and logic. | #include <cmath>
#include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
... | using Primes
function proddivisors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
return prod(f)
end
for i in 1:50
print(lpad(proddivisors(i), 10), i % 10 == 0 ? " \n" : "")
end
|
Ensure the translated Julia code behaves exactly like the original C++ snippet. | #include <cmath>
#include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
... | using Primes
function proddivisors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
return prod(f)
end
for i in 1:50
print(lpad(proddivisors(i), 10), i % 10 == 0 ? " \n" : "")
end
|
Change the programming language of this snippet from C++ to Julia without modifying what it does. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <set>
#include <primesieve.hpp>
class erdos_prime_generator {
public:
erdos_prime_generator() {}
uint64_t next();
private:
bool erdos(uint64_t p) const;
primesieve::iterator iter_;
std::set<uint64_t> primes_;
};
uint64_t erdos_prim... | using Primes, Formatting
function isErdős(p::Integer)
isprime(p) || return false
for i in 1:100
kfac = factorial(i)
kfac >= p && break
isprime(p - kfac) && return false
end
return true
end
const Erdőslist = filter(isErdős, 1:1000000)
const E2500 = filter(x -> x < 2500, Erdőslis... |
Port the following code from C++ to Julia with equivalent syntax and logic. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <set>
#include <primesieve.hpp>
class erdos_prime_generator {
public:
erdos_prime_generator() {}
uint64_t next();
private:
bool erdos(uint64_t p) const;
primesieve::iterator iter_;
std::set<uint64_t> primes_;
};
uint64_t erdos_prim... | using Primes, Formatting
function isErdős(p::Integer)
isprime(p) || return false
for i in 1:100
kfac = factorial(i)
kfac >= p && break
isprime(p - kfac) && return false
end
return true
end
const Erdőslist = filter(isErdős, 1:1000000)
const E2500 = filter(x -> x < 2500, Erdőslis... |
Write the same algorithm in Julia as shown in this C++ implementation. | #include <deque>
#include <algorithm>
#include <ostream>
#include <iterator>
namespace cards
{
class card
{
public:
enum pip_type { two, three, four, five, six, seven, eight, nine, ten,
jack, queen, king, ace, pip_count };
enum suite_type { hearts, spades, diamonds, clubs, suite_count };
... | type DeckDesign{T<:Integer,U<:String}
rlen::T
slen::T
ranks::Array{U,1}
suits::Array{U,1}
hlen::T
end
type Deck{T<:Integer}
cards::Array{T,1}
design::DeckDesign
end
Deck(n::Integer, des::DeckDesign) = Deck([n], des)
function pokerlayout()
r = [map(string, 2:10), "J", "Q", "K", "A"]
... |
Change the programming language of this snippet from C++ to Julia without modifying what it does. | #include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
int gcd(int a, int b) {
int c;
while (b) {
c = a;
a = b;
b = c % b;
}
return a;
}
int main() {
using intpair = std::pair<int,int>;
std::vector<intpair> pairs = {
{21,15}, {17,23}, {36,... | filter(p -> gcd(p...) == 1, [[21,15],[17,23],[36,12],[18,29],[60,15],[21,22,25,31,143]])
|
Keep all operations the same but rewrite the snippet in Julia. | #include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
int gcd(int a, int b) {
int c;
while (b) {
c = a;
a = b;
b = c % b;
}
return a;
}
int main() {
using intpair = std::pair<int,int>;
std::vector<intpair> pairs = {
{21,15}, {17,23}, {36,... | filter(p -> gcd(p...) == 1, [[21,15],[17,23],[36,12],[18,29],[60,15],[21,22,25,31,143]])
|
Port the following code from C++ to Julia with equivalent syntax and logic. | #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
contin... | using Primes
eulerphi(n) = (r = one(n); for (p,k) in factor(abs(n)) r *= p^(k-1)*(p-1) end; r)
const phicache = Dict{Int, Int}()
cachedphi(n) = (if !haskey(phicache, n) phicache[n] = eulerphi(n) end; phicache[n])
function perfecttotientseries(n)
perfect = Vector{Int}()
i = 1
while length(perfect) < n
... |
Port the following code from C++ to Julia with equivalent syntax and logic. | #include <cassert>
#include <iostream>
#include <vector>
class totient_calculator {
public:
explicit totient_calculator(int max) : totient_(max + 1) {
for (int i = 1; i <= max; ++i)
totient_[i] = i;
for (int i = 2; i <= max; ++i) {
if (totient_[i] < i)
contin... | using Primes
eulerphi(n) = (r = one(n); for (p,k) in factor(abs(n)) r *= p^(k-1)*(p-1) end; r)
const phicache = Dict{Int, Int}()
cachedphi(n) = (if !haskey(phicache, n) phicache[n] = eulerphi(n) end; phicache[n])
function perfecttotientseries(n)
perfect = Vector{Int}()
i = 1
while length(perfect) < n
... |
Convert this C++ snippet to Julia and keep its semantics consistent. |
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <gmpxx.h>
using integer = mpz_class;
class unsigned_lah_numbers {
public:
integer get(int n, int k);
private:
std::map<std::pair<int, int>, integer> cache_;
};
integer unsigned_lah_numbers::get(int n, int k) {
if (k == ... | using Combinatorics
function lah(n::Integer, k::Integer, signed=false)
if n == 0 || k == 0 || k > n
return zero(n)
elseif n == k
return one(n)
elseif k == 1
return factorial(n)
else
unsignedvalue = binomial(n, k) * binomial(n - 1, k - 1) * factorial(n - k)
if sig... |
Generate an equivalent Julia version of this C++ code. |
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <gmpxx.h>
using integer = mpz_class;
class unsigned_lah_numbers {
public:
integer get(int n, int k);
private:
std::map<std::pair<int, int>, integer> cache_;
};
integer unsigned_lah_numbers::get(int n, int k) {
if (k == ... | using Combinatorics
function lah(n::Integer, k::Integer, signed=false)
if n == 0 || k == 0 || k > n
return zero(n)
elseif n == k
return one(n)
elseif k == 1
return factorial(n)
else
unsignedvalue = binomial(n, k) * binomial(n - 1, k - 1) * factorial(n - k)
if sig... |
Rewrite the snippet below in Julia so it works the same as the original C++ code. | #include <iostream>
#include <map>
#include <tuple>
#include <vector>
using namespace std;
pair<int, int> twoSum(vector<int> numbers, int sum) {
auto m = map<int, int>();
for (size_t i = 0; i < numbers.size(); ++i) {
auto key = sum - numbers[i];
if (m.find(key) != m.end()) {
return make_pair(m[key], i);
... | function twosum(v::Vector, s)
i = 1
j = length(v)
while i < j
if v[i] + v[j] == s
return [i, j]
elseif v[i] + v[j] < s
i += 1
else
j -= 1
end
end
return similar(v, 0)
end
@show twosum([0, 2, 11, 19, 90], 21)
|
Change the following C++ code into Julia without altering its purpose. | #include <iostream>
#include <map>
#include <tuple>
#include <vector>
using namespace std;
pair<int, int> twoSum(vector<int> numbers, int sum) {
auto m = map<int, int>();
for (size_t i = 0; i < numbers.size(); ++i) {
auto key = sum - numbers[i];
if (m.find(key) != m.end()) {
return make_pair(m[key], i);
... | function twosum(v::Vector, s)
i = 1
j = length(v)
while i < j
if v[i] + v[j] == s
return [i, j]
elseif v[i] + v[j] < s
i += 1
else
j -= 1
end
end
return similar(v, 0)
end
@show twosum([0, 2, 11, 19, 90], 21)
|
Ensure the translated Julia code behaves exactly like the original C++ snippet. | #include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <vector>
template <typename iterator>
void cocktail_shaker_sort(iterator begin, iterator end) {
if (begin == end)
return;
for (--end; begin < end; ) {
iterator new_begin = end;
iterator new_end = b... | module CocktailShakerSorts
using Base.Order, Base.Sort
import Base.Sort: sort!
export CocktailShakerSort
struct CocktailSortAlg <: Algorithm end
const CocktailShakerSort = CocktailSortAlg()
function sort!(A::AbstractVector, lo::Int, hi::Int, a::CocktailSortAlg, ord::Ordering)
if lo > 1 || hi < length(A)
... |
Port the following code from C++ to Julia with equivalent syntax and logic. | #include <iostream>
#include <cstdint>
#include "prime_sieve.hpp"
typedef uint32_t integer;
int count_digits(integer n) {
int digits = 0;
for (; n > 0; ++digits)
n /= 10;
return digits;
}
integer change_digit(integer n, int index, int new_digit) {
integer p = 1;
integer changed = 0;
... | using Primes, Lazy, Formatting
function isunprimeable(n)
dvec = digits(n)
for pos in 1:length(dvec), newdigit in 0:9
olddigit, dvec[pos] = dvec[pos], newdigit
isprime(foldr((i, j) -> i + 10j, dvec)) && return false
dvec[pos] = olddigit
end
return true
end
println("First 35 unpr... |
Produce a functionally identical Julia code for the snippet given in C++. | #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
... | using Primes
function numfactors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
length(f)
end
function taunumbers(toget = 100)
n = 0
for i in 1:100000000
if i % numfactors(i) == 0
n += 1
print(rpad(i, 5), n... |
Generate a Julia translation of this C++ snippet without changing its computational steps. | #include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <string>
#include <gmpxx.h>
bool is_probably_prime(const mpz_class& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 3) != 0;
}
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2... | using Primes
let
pmask, pcount = primesmask(1, 5000), 0
issum25prime(n) = pmask[n] && sum(digits(n)) == 25
println("Primes with digits summing to 25 between 0 and 5000:")
for n in 1:4999
if issum25prime(n)
pcount += 1
print(rpad(n, 5))
end
end
println("\... |
Convert this C++ block to Julia, preserving its control flow and logic. | #include <cstdio>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;
for (int x : lst) w.push_back({x, x});
while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());
for (int x : lst) if ((sum = get<1>(i) + x) == 13)
... | using Combinatorics, Primes
function primedigitsums(targetsum)
possibles = mapreduce(x -> fill(x, div(targetsum, x)), vcat, [2, 3, 5, 7])
a = map(x -> evalpoly(BigInt(10), x),
mapreduce(x -> unique(collect(permutations(x))), vcat,
unique(filter(x -> sum(x) == targetsum, collect(combinations(p... |
Produce a functionally identical Julia code for the snippet given in C++. | #include <cstdio>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;
for (int x : lst) w.push_back({x, x});
while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());
for (int x : lst) if ((sum = get<1>(i) + x) == 13)
... | using Combinatorics, Primes
function primedigitsums(targetsum)
possibles = mapreduce(x -> fill(x, div(targetsum, x)), vcat, [2, 3, 5, 7])
a = map(x -> evalpoly(BigInt(10), x),
mapreduce(x -> unique(collect(permutations(x))), vcat,
unique(filter(x -> sum(x) == targetsum, collect(combinations(p... |
Transform the following C++ implementation into Julia, maintaining the same output and logic. | #include <array>
#include <iostream>
#include <list>
#include <map>
#include <vector>
int main()
{
auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"};
auto myColors = std::vector<std::string>{"red", "green", "blue"};
auto myArray = std::array<std::vector<std::string>, 2>{myNumber... |
cp = deepcopy(obj)
|
Write a version of this C++ function in Julia with identical behavior. | #include <array>
#include <iostream>
#include <list>
#include <map>
#include <vector>
int main()
{
auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"};
auto myColors = std::vector<std::string>{"red", "green", "blue"};
auto myArray = std::array<std::vector<std::string>, 2>{myNumber... |
cp = deepcopy(obj)
|
Produce a language-to-language conversion: from C++ to Julia, same semantics. | #include <cstdint>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <gmpxx.h>
typedef mpz_class integer;
bool is_prime(const integer& n, int reps = 50) {
return mpz_probab_prime_p(n.get_mpz_t(), reps);
}
std::string to_string(const integer& n) {
std::ostringstream out;
out << n;
r... | using Lazy, Primes
function iscircularprime(n)
!isprime(n) && return false
dig = digits(n)
return all(i -> (m = evalpoly(10, circshift(dig, i))) >= n && isprime(m), 1:length(dig)-1)
end
filtcircular(n, rang) = Int.(collect(take(n, filter(iscircularprime, rang))))
isprimerepunit(n) = isprime(evalpoly(BigIn... |
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <primesieve.hpp>
bool is_prime(uint64_t n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (uint64_t p = 5; p * p <= n; p += 4) {
if (n % p == 0)
r... | using Primes
const primeslt10k = primes(10000)
frobenius(n) = begin (x, y) = primeslt10k[n:n+1]; x * y - x - y end
function frobeniuslessthan(maxnum)
frobpairs = Pair{Int, Bool}[]
for n in 1:maxnum
frob = frobenius(n)
frob > maxnum && break
push!(frobpairs, Pair(frob, isprime(frob)))
... |
Please provide an equivalent version of this C++ code in Julia. | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <primesieve.hpp>
bool is_prime(uint64_t n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (uint64_t p = 5; p * p <= n; p += 4) {
if (n % p == 0)
r... | using Primes
const primeslt10k = primes(10000)
frobenius(n) = begin (x, y) = primeslt10k[n:n+1]; x * y - x - y end
function frobeniuslessthan(maxnum)
frobpairs = Pair{Int, Bool}[]
for n in 1:maxnum
frob = frobenius(n)
frob > maxnum && break
push!(frobpairs, Pair(frob, isprime(frob)))
... |
Change the following C++ code into Julia without altering its purpose. | #include <algorithm>
template<typename ForwardIterator>
void permutation_sort(ForwardIterator begin, ForwardIterator end)
{
while (std::next_permutation(begin, end))
{
}
}
|
using Combinatorics
function permsort(x::Array)
for perm in permutations(x)
if issorted(perm)
return perm
end
end
end
x = randn(10)
@show x permsort(x)
|
Translate this program into Julia but keep the logic exactly as in C++. | #include <iostream>
#include <math.h>
unsigned long long root(unsigned long long base, unsigned int n) {
if (base < 2) return base;
if (n == 0) return 1;
unsigned int n1 = n - 1;
unsigned long long n2 = n;
unsigned long long n3 = n1;
unsigned long long c = 1;
auto d = (n3 + base) / n2;
auto e = (n3 * d + base... | function iroot(a, b)
b < 2 && return b
a1, c = a - 1, 1
d = (a1 * c + b ÷ c^a1) ÷ a
e = (a1 * d + b ÷ d^a1) ÷ a
while d ≠ c ≠ e
c, d, e = d, e, (a1 * e + b ÷ (e ^ a1)) ÷ a
end
min(d, e)
end
println("First 2,001 digits of the square root of two:\n", iroot(2, 2 * big(100) ^ 2000))
|
Change the programming language of this snippet from C++ to Julia without modifying what it does. | #include <iostream>
#include <math.h>
unsigned long long root(unsigned long long base, unsigned int n) {
if (base < 2) return base;
if (n == 0) return 1;
unsigned int n1 = n - 1;
unsigned long long n2 = n;
unsigned long long n3 = n1;
unsigned long long c = 1;
auto d = (n3 + base) / n2;
auto e = (n3 * d + base... | function iroot(a, b)
b < 2 && return b
a1, c = a - 1, 1
d = (a1 * c + b ÷ c^a1) ÷ a
e = (a1 * d + b ÷ d^a1) ÷ a
while d ≠ c ≠ e
c, d, e = d, e, (a1 * e + b ÷ (e ^ a1)) ÷ a
end
min(d, e)
end
println("First 2,001 digits of the square root of two:\n", iroot(2, 2 * big(100) ^ 2000))
|
Ensure the translated Julia code behaves exactly like the original C++ snippet. | int meaning_of_life();
| module Divisors
using Primes
export properdivisors
function properdivisors(n::T) where T <: Integer
0 < n || throw(ArgumentError("number to be factored must be ≥ 0, got $n"))
1 < n || return T[]
!isprime(n) || return T[one(T), n]
f = factor(n)
d = T[one(T)]
for (k, v) in f
c = T[k^i f... |
Generate a Julia translation of this C++ snippet without changing its computational steps. | int meaning_of_life();
| module Divisors
using Primes
export properdivisors
function properdivisors(n::T) where T <: Integer
0 < n || throw(ArgumentError("number to be factored must be ≥ 0, got $n"))
1 < n || return T[]
!isprime(n) || return T[one(T), n]
f = factor(n)
d = T[one(T)]
for (k, v) in f
c = T[k^i f... |
Write the same code in Julia as shown below in C++. | #include <iostream>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
... | using Primes
isnice(n, base=10) = isprime(n) && (mod1(n - 1, base - 1) + 1) in [2, 3, 5, 7, 11, 13, 17, 19]
filter_open_interval(500, 1000, isnice)
|
Ensure the translated Julia code behaves exactly like the original C++ snippet. | #include <iostream>
bool is_prime(unsigned int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (unsigned int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
... | using Primes
isnice(n, base=10) = isprime(n) && (mod1(n - 1, base - 1) + 1) in [2, 3, 5, 7, 11, 13, 17, 19]
filter_open_interval(500, 1000, isnice)
|
Port the following code from C++ to Julia with equivalent syntax and logic. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class lastSunday
{
public:
lastSunday()
{
m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: ";
m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";... | isdefined(:Date) || using Dates
const wday = Dates.Sun
const lo = 1
const hi = 12
print("\nThis script will print the last ", Dates.dayname(wday))
println("s of each month of the year given.")
println("(Leave input empty to quit.)")
while true
print("\nYear> ")
y = chomp(readline())
0 < length(y) || brea... |
Change the programming language of this snippet from C++ to Julia without modifying what it does. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
class lastSunday
{
public:
lastSunday()
{
m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: ";
m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";... | isdefined(:Date) || using Dates
const wday = Dates.Sun
const lo = 1
const hi = 12
print("\nThis script will print the last ", Dates.dayname(wday))
println("s of each month of the year given.")
println("(Leave input empty to quit.)")
while true
print("\nYear> ")
y = chomp(readline())
0 < length(y) || brea... |
Change the programming language of this snippet from C++ to Julia without modifying what it does. | #include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it... | using Random
shufflerows(mat) = mat[shuffle(1:end), :]
shufflecols(mat) = mat[:, shuffle(1:end)]
function addatdiagonal(mat)
n = size(mat)[1] + 1
newmat = similar(mat, size(mat) .+ 1)
for j in 1:n, i in 1:n
newmat[i, j] = (i == n && j < n) ? mat[1, j] : (i == j) ? n - 1 :
(i < j) ? mat... |
Rewrite the snippet below in Julia so it works the same as the original C++ code. | #include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
#include <string>
#include <vector>
std::set<std::string> load_dictionary(const std::string& filename) {
std::ifstream in(filename);
if (!in)
throw std::runtime_error("Cannot open file " + filename);
std::set<std::string> w... | using HTTP
rotate(s, n) = String(circshift(Vector{UInt8}(s), n))
isliketea(w, d) = (n = length(w); n > 2 && any(c -> c != w[1], w) &&
all(i -> haskey(d, rotate(w, i)), 1:n-1))
function getteawords(listuri)
req = HTTP.request("GET", listuri)
wdict = Dict{String, Int}((lowercase(string(x)), 1) for x in... |
Change the following C++ code into Julia without altering its purpose. | #include <iostream>
#include <vector>
int turn(int base, int n) {
int sum = 0;
while (n != 0) {
int rem = n % base;
n = n / base;
sum += rem;
}
return sum % base;
}
void fairshare(int base, int count) {
printf("Base %2d:", base);
for (int i = 0; i < count; i++) {
... | fairshare(nplayers,len) = [sum(digits(n, base=nplayers)) % nplayers for n in 0:len-1]
for n in [2, 3, 5, 11]
println("Fairshare ", n > 2 ? "among" : "between", " $n people: ", fairshare(n, 25))
end
|
Ensure the translated Julia code behaves exactly like the original C++ snippet. | #include <functional>
#include <iostream>
#include <sstream>
#include <vector>
std::string to(int n, int b) {
static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::stringstream ss;
while (n > 0) {
auto rem = n % b;
n = n / b;
ss << BASE[rem];
}
auto fwd = ss.str(... | using Formatting
import Base.iterate, Base.IteratorSize, Base.IteratorEltype
"""
struct Esthetic
Used for iteration of esthetic numbers
"""
struct Esthetic{T}
lowerlimit::T where T <: Integer
base::T
upperlimit::T
Esthetic{T}(n, bas, m=typemax(T)) where T = new{T}(nextesthetic(n, bas), bas, m)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.