Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this C++ function in PHP with identical behavior. | #include <iostream>
#include <fstream>
int main(){
std::ofstream lprFile;
lprFile.open( "/dev/lp0" );
lprFile << "Hello World!\n";
lprFile.close();
return 0;
}
| <?php
file_put_contents('/dev/lp0', 'Hello world!');
?>
|
Keep all operations the same but rewrite the snippet in PHP. | #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
int main( ) {
std::vector<double> input( 11 ) , results( 11 ) ;
std::cout << "Please enter 11 numbers!\n" ;
for ( int i = 0 ; i < input.size( ) ; i++ )
std::cin >> input[i];
std::transform( input.begin( ) , input.end( ) , results.begin( ) ,
[ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;
for ( int i = 10 ; i > -1 ; i-- ) {
std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ;
if ( results[ i ] > 400 )
std::cout << "too large!" ;
else
std::cout << results[ i ] << " !" ;
std::cout << std::endl ;
}
return 0 ;
}
| <?php
function f($n)
{
return sqrt(abs($n)) + 5 * $n * $n * $n;
}
$sArray = [];
echo "Enter 11 numbers.\n";
for ($i = 0; $i <= 10; $i++) {
echo $i + 1, " - Enter number: ";
array_push($sArray, (float)fgets(STDIN));
}
echo PHP_EOL;
$sArray = array_reverse($sArray);
foreach ($sArray as $s) {
$r = f($s);
echo "f(", $s, ") = ";
if ($r > 400)
echo "overflow\n";
else
echo $r, PHP_EOL;
}
?>
|
Change the programming language of this snippet from C++ to PHP without modifying what it does. | #include <iostream>
std::string middleThreeDigits(int n)
{
auto number = std::to_string(std::abs(n));
auto length = number.size();
if (length < 3) {
return "less than three digits";
} else if (length % 2 == 0) {
return "even number of digits";
} else {
return number.substr(length / 2 - 1, 3);
}
}
int main()
{
auto values {123, 12345, 1234567, 987654321, 10001,
-10001, -123, -100, 100, -12345,
1, 2, -1, -10, 2002, -2002, 0};
for (auto&& v : values) {
std::cout << "middleThreeDigits(" << v << "): " <<
middleThreeDigits(v) << "\n";
}
}
|
function middlethree($integer)
{
$int = (int)str_replace('-','',$integer);
$length = strlen($int);
if(is_int($int))
{
if($length >= 3)
{
if($length % 2 == 1)
{
$middle = floor($length / 2) - 1;
return substr($int,$middle, 3);
}
else
{
return 'The value must contain an odd amount of digits...';
}
}
else
{
return 'The value must contain at least three digits...';
}
}
else
{
return 'The value does not appear to be an integer...';
}
}
$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);
foreach($numbers as $nums)
{
echo $nums.' : '.middlethree($nums). '<br>';
}
|
Produce a functionally identical PHP code for the snippet given in C++. | #include <iostream>
#include <cctype>
#include <functional>
using namespace std;
bool odd()
{
function<void ()> prev = []{};
while(true) {
int c = cin.get();
if (!isalpha(c)) {
prev();
cout.put(c);
return c != '.';
}
prev = [=] { cout.put(c); prev(); };
}
}
bool even()
{
while(true) {
int c;
cout.put(c = cin.get());
if (!isalpha(c)) return c != '.';
}
}
int main()
{
bool e = false;
while( e ? odd() : even() ) e = !e;
return 0;
}
| $odd = function ($prev) use ( &$odd ) {
$a = fgetc(STDIN);
if (!ctype_alpha($a)) {
$prev();
fwrite(STDOUT, $a);
return $a != '.';
}
$clos = function () use ($a , $prev) {
fwrite(STDOUT, $a);
$prev();
};
return $odd($clos);
};
$even = function () {
while (true) {
$c = fgetc(STDIN);
fwrite(STDOUT, $c);
if (!ctype_alpha($c)) {
return $c != ".";
}
}
};
$prev = function(){};
$e = false;
while ($e ? $odd($prev) : $even()) {
$e = !$e;
}
|
Write a version of this C++ function in PHP with identical behavior. | auto strA = R"(this is
a newline-separated
raw string)";
| 'c'; # character
'hello'; # these two strings are the same
"hello";
'Hi $name. How are you?'; # result: "Hi $name. How are you?"
"Hi $name. How are you?"; # result: "Hi Bob. How are you?"
'\n'; # 2-character string with a backslash and "n"
"\n"; # newline character
`ls`; # runs a command in the shell and returns the output as a string
<<END # Here-Document
Hi, whatever goes here gets put into the string,
including newlines and $variables,
until the label we put above
END;
<<'END' # Here-Document like single-quoted
Same as above, but no interpolation of $variables.
END;
|
Convert this C++ snippet to PHP and keep its semantics consistent. | enum fruits { apple, banana, cherry };
enum fruits { apple = 0, banana = 1, cherry = 2 };
|
$fruits = array( "apple", "banana", "cherry" );
$fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 );
class Fruit {
const APPLE = 0;
const BANANA = 1;
const CHERRY = 2;
}
$value = Fruit::APPLE;
define("FRUIT_APPLE", 0);
define("FRUIT_BANANA", 1);
define("FRUIT_CHERRY", 2);
|
Write a version of this C++ function in PHP with identical behavior. | int meaning_of_life();
| <?php
function meaning_of_life() {
return 42;
}
function main($args) {
echo "Main: The meaning of life is " . meaning_of_life() . "\n";
}
if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) {
main($argv);
}
?>
|
Produce a functionally identical PHP code for the snippet given in C++. | int meaning_of_life();
| <?php
function meaning_of_life() {
return 42;
}
function main($args) {
echo "Main: The meaning of life is " . meaning_of_life() . "\n";
}
if (preg_match("/scriptedmain/", $_SERVER["SCRIPT_NAME"])) {
main($argv);
}
?>
|
Rewrite the snippet below in PHP so it works the same as the original C++ code. | #include <iostream>
#include <set>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main(void)
{
fs::path p(fs::current_path());
std::set<std::string> tree;
for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)
tree.insert(it->path().filename().native());
for (auto entry : tree)
std::cout << entry << '\n';
}
| <?php
foreach(scandir('.') as $fileName){
echo $fileName."\n";
}
|
Rewrite this program in PHP while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
using namespace std;
class MTF
{
public:
string encode( string str )
{
fillSymbolTable();
vector<int> output;
for( string::iterator it = str.begin(); it != str.end(); it++ )
{
for( int i = 0; i < 26; i++ )
{
if( *it == symbolTable[i] )
{
output.push_back( i );
moveToFront( i );
break;
}
}
}
string r;
for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
{
ostringstream ss;
ss << *it;
r += ss.str() + " ";
}
return r;
}
string decode( string str )
{
fillSymbolTable();
istringstream iss( str ); vector<int> output;
copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );
string r;
for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
{
r.append( 1, symbolTable[*it] );
moveToFront( *it );
}
return r;
}
private:
void moveToFront( int i )
{
char t = symbolTable[i];
for( int z = i - 1; z >= 0; z-- )
symbolTable[z + 1] = symbolTable[z];
symbolTable[0] = t;
}
void fillSymbolTable()
{
for( int x = 0; x < 26; x++ )
symbolTable[x] = x + 'a';
}
char symbolTable[26];
};
int main()
{
MTF mtf;
string a, str[] = { "broood", "bananaaa", "hiphophiphop" };
for( int x = 0; x < 3; x++ )
{
a = str[x];
cout << a << " -> encoded = ";
a = mtf.encode( a );
cout << a << "; decoded = " << mtf.decode( a ) << endl;
}
return 0;
}
| <?php
function symbolTable() {
$symbol = array();
for ($c = ord('a') ; $c <= ord('z') ; $c++) {
$symbol[$c - ord('a')] = chr($c);
}
return $symbol;
}
function mtfEncode($original, $symbol) {
$encoded = array();
for ($i = 0 ; $i < strlen($original) ; $i++) {
$char = $original[$i];
$position = array_search($char, $symbol);
$encoded[] = $position;
$mtf = $symbol[$position];
unset($symbol[$position]);
array_unshift($symbol, $mtf);
}
return $encoded;
}
function mtfDecode($encoded, $symbol) {
$decoded = '';
foreach ($encoded AS $position) {
$char = $symbol[$position];
$decoded .= $char;
unset($symbol[$position]);
array_unshift($symbol, $char);
}
return $decoded;
}
foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {
$encoded = mtfEncode($original, symbolTable());
$decoded = mtfDecode($encoded, symbolTable());
echo
$original,
' -> [', implode(',', $encoded), ']',
' -> ', $decoded,
' : ', ($original === $decoded ? 'OK' : 'Error'),
PHP_EOL;
}
|
Ensure the translated PHP code behaves exactly like the original C++ snippet. | #include <vector>
#include <list>
#include <algorithm>
#include <iostream>
template <typename T>
struct Node {
T value;
Node* prev_node;
};
template <typename Container>
Container lis(const Container& values) {
using E = typename Container::value_type;
using NodePtr = Node<E>*;
using ConstNodePtr = const NodePtr;
std::vector<NodePtr> pileTops;
std::vector<Node<E>> nodes(values.size());
auto cur_node = std::begin(nodes);
for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)
{
auto node = &*cur_node;
node->value = *cur_value;
auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,
[](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });
if (lb != pileTops.begin())
node->prev_node = *std::prev(lb);
if (lb == pileTops.end())
pileTops.push_back(node);
else
*lb = node;
}
Container result(pileTops.size());
auto r = std::rbegin(result);
for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)
*r = node->value;
return result;
}
template <typename Container>
void show_lis(const Container& values)
{
auto&& result = lis(values);
for (auto& r : result) {
std::cout << r << ' ';
}
std::cout << std::endl;
}
int main()
{
show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });
show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });
}
| <?php
class Node {
public $val;
public $back = NULL;
}
function lis($n) {
$pileTops = array();
foreach ($n as $x) {
$low = 0; $high = count($pileTops)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($pileTops[$mid]->val >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
$node = new Node();
$node->val = $x;
if ($i != 0)
$node->back = $pileTops[$i-1];
$pileTops[$i] = $node;
}
$result = array();
for ($node = count($pileTops) ? $pileTops[count($pileTops)-1] : NULL;
$node != NULL; $node = $node->back)
$result[] = $node->val;
return array_reverse($result);
}
print_r(lis(array(3, 2, 6, 4, 5, 1)));
print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));
?>
|
Please provide an equivalent version of this C++ code in PHP. | #include <iostream>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
namespace detail {
template <typename ForwardIterator>
class tokenizer
{
ForwardIterator _tbegin, _tend, _end;
public:
tokenizer(ForwardIterator begin, ForwardIterator end)
: _tbegin(begin), _tend(begin), _end(end)
{ }
template <typename Lambda>
bool next(Lambda istoken)
{
if (_tbegin == _end) {
return false;
}
_tbegin = _tend;
for (; _tend != _end && !istoken(*_tend); ++_tend) {
if (*_tend == '\\' && std::next(_tend) != _end) {
++_tend;
}
}
if (_tend == _tbegin) {
_tend++;
}
return _tbegin != _end;
}
ForwardIterator begin() const { return _tbegin; }
ForwardIterator end() const { return _tend; }
bool operator==(char c) { return *_tbegin == c; }
};
template <typename List>
void append_all(List & lista, const List & listb)
{
if (listb.size() == 1) {
for (auto & a : lista) {
a += listb.back();
}
} else {
List tmp;
for (auto & a : lista) {
for (auto & b : listb) {
tmp.push_back(a + b);
}
}
lista = std::move(tmp);
}
}
template <typename String, typename List, typename Tokenizer>
List expand(Tokenizer & token)
{
std::vector<List> alts{ { String() } };
while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) {
if (token == '{') {
append_all(alts.back(), expand<String, List>(token));
} else if (token == ',') {
alts.push_back({ String() });
} else if (token == '}') {
if (alts.size() == 1) {
for (auto & a : alts.back()) {
a = '{' + a + '}';
}
return alts.back();
} else {
for (std::size_t i = 1; i < alts.size(); i++) {
alts.front().insert(alts.front().end(),
std::make_move_iterator(std::begin(alts[i])),
std::make_move_iterator(std::end(alts[i])));
}
return std::move(alts.front());
}
} else {
for (auto & a : alts.back()) {
a.append(token.begin(), token.end());
}
}
}
List result{ String{ '{' } };
append_all(result, alts.front());
for (std::size_t i = 1; i < alts.size(); i++) {
for (auto & a : result) {
a += ',';
}
append_all(result, alts[i]);
}
return result;
}
}
template <
typename ForwardIterator,
typename String = std::basic_string<
typename std::iterator_traits<ForwardIterator>::value_type
>,
typename List = std::vector<String>
>
List expand(ForwardIterator begin, ForwardIterator end)
{
detail::tokenizer<ForwardIterator> token(begin, end);
List list{ String() };
while (token.next([](char c) { return c == '{'; })) {
if (token == '{') {
detail::append_all(list, detail::expand<String, List>(token));
} else {
for (auto & a : list) {
a.append(token.begin(), token.end());
}
}
}
return list;
}
template <
typename Range,
typename String = std::basic_string<typename Range::value_type>,
typename List = std::vector<String>
>
List expand(const Range & range)
{
using Iterator = typename Range::const_iterator;
return expand<Iterator, String, List>(std::begin(range), std::end(range));
}
int main()
{
for (std::string string : {
R"(~/{Downloads,Pictures}/*.{jpg,gif,png})",
R"(It{{em,alic}iz,erat}e{d,}, please.)",
R"({,{,gotta have{ ,\, again\, }}more }cowbell!)",
R"({}} some {\\{edge,edgy} }{ cases, here\\\})",
R"(a{b{1,2}c)",
R"(a{1,2}b}c)",
R"(a{1,{2},3}b)",
R"(a{b{1,2}c{}})",
R"(more{ darn{ cowbell,},})",
R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)",
R"({a,{\,b}c)",
R"(a{b,{{c}})",
R"({a{\}b,c}d)",
R"({a,b{{1,2}e}f)",
R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})",
R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)",
}) {
std::cout << string << '\n';
for (auto expansion : expand(string)) {
std::cout << " " << expansion << '\n';
}
std::cout << '\n';
}
return 0;
}
| function getitem($s,$depth=0) {
$out = [''];
while ($s) {
$c = $s[0];
if ($depth && ($c == ',' || $c == '}')) {
return [$out, $s];
}
if ($c == '{') {
$x = getgroup(substr($s, 1), $depth + 1);
if($x) {
$tmp = [];
foreach($out as $a) {
foreach($x[0] as $b) {
$tmp[] = $a . $b;
}
}
$out = $tmp;
$s = $x[1];
continue;
}
}
if ($c == '\\' && strlen($s) > 1) {
list($s, $c) = [substr($s, 1), ($c . $s[1])];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = $a . $c;
}
$out = $tmp;
$s = substr($s, 1);
}
return [$out, $s];
}
function getgroup($s,$depth) {
list($out, $comma) = [[], false];
while ($s) {
list($g, $s) = getitem($s, $depth);
if (!$s) {
break;
}
$out = array_merge($out, $g);
if ($s[0] == '}') {
if ($comma) {
return [$out, substr($s, 1)];
}
$tmp = [];
foreach($out as $a) {
$tmp[] = '{' . $a . '}';
}
return [$tmp, substr($s, 1)];
}
if ($s[0] == ',') {
list($comma, $s) = [true, substr($s, 1)];
}
}
return null;
}
$lines = <<< 'END'
~/{Downloads,Pictures}/*.{jpg,gif,png}
It{{em,alic}iz,erat}e{d,}, please.
{,{,gotta have{ ,\, again\, }}more }cowbell!
{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}
END;
foreach( explode("\n", $lines) as $line ) {
printf("\n%s\n", $line);
foreach( getitem($line)[0] as $expansion ) {
printf(" %s\n", $expansion);
}
}
|
Port the provided C++ code into PHP while preserving the original functionality. | #include <iostream>
typedef unsigned long long bigint;
using namespace std;
class sdn
{
public:
bool check( bigint n )
{
int cc = digitsCount( n );
return compare( n, cc );
}
void displayAll( bigint s )
{
for( bigint y = 1; y < s; y++ )
if( check( y ) )
cout << y << " is a Self-Describing Number." << endl;
}
private:
bool compare( bigint n, int cc )
{
bigint a;
while( cc )
{
cc--; a = n % 10;
if( dig[cc] != a ) return false;
n -= a; n /= 10;
}
return true;
}
int digitsCount( bigint n )
{
int cc = 0; bigint a;
memset( dig, 0, sizeof( dig ) );
while( n )
{
a = n % 10; dig[a]++;
cc++ ; n -= a; n /= 10;
}
return cc;
}
int dig[10];
};
int main( int argc, char* argv[] )
{
sdn s;
s. displayAll( 1000000000000 );
cout << endl << endl; system( "pause" );
bigint n;
while( true )
{
system( "cls" );
cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n;
if( !n ) return 0;
if( s.check( n ) ) cout << n << " is";
else cout << n << " is NOT";
cout << " a Self-Describing Number!" << endl << endl;
system( "pause" );
}
return 0;
}
| <?php
function is_describing($number) {
foreach (str_split((int) $number) as $place => $value) {
if (substr_count($number, $place) != $value) {
return false;
}
}
return true;
}
for ($i = 0; $i <= 50000000; $i += 10) {
if (is_describing($i)) {
echo $i . PHP_EOL;
}
}
?>
|
Change the programming language of this snippet from C++ to PHP without modifying what it does. | #include <iostream>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int main(void) {
std::cout << mul_inv(42, 2017) << std::endl;
return 0;
}
| <?php
function invmod($a,$n){
if ($n < 0) $n = -$n;
if ($a < 0) $a = $n - (-$a % $n);
$t = 0; $nt = 1; $r = $n; $nr = $a % $n;
while ($nr != 0) {
$quot= intval($r/$nr);
$tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp;
$tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp;
}
if ($r > 1) return -1;
if ($t < 0) $t += $n;
return $t;
}
printf("%d\n", invmod(42, 2017));
?>
|
Rewrite the snippet below in PHP so it works the same as the original C++ code. | #include <iostream>
int main()
{
auto double1 = 2.5;
auto float1 = 2.5f;
auto longdouble1 = 2.5l;
auto double2 = 2.5e-3;
auto float2 = 2.5e3f;
auto double3 = 0x1p4;
auto float3 = 0xbeefp-8f;
std::cout << "\ndouble1: " << double1;
std::cout << "\nfloat1: " << float1;
std::cout << "\nlongdouble1: " << longdouble1;
std::cout << "\ndouble2: " << double2;
std::cout << "\nfloat2: " << float2;
std::cout << "\ndouble3: " << double3;
std::cout << "\nfloat3: " << float3;
std::cout << "\n";
}
| .12
0.1234
1.2e3
7E-10
|
Preserve the algorithm and functionality while converting the code from C++ to PHP. | #include <iostream>
auto Zero = [](auto){ return [](auto x){ return x; }; };
auto True = [](auto a){ return [=](auto){ return a; }; };
auto False = [](auto){ return [](auto b){ return b; }; };
auto Successor(auto a) {
return [=](auto f) {
return [=](auto x) {
return a(f)(f(x));
};
};
}
auto Add(auto a, auto b) {
return [=](auto f) {
return [=](auto x) {
return a(f)(b(f)(x));
};
};
}
auto Multiply(auto a, auto b) {
return [=](auto f) {
return a(b(f));
};
}
auto Exp(auto a, auto b) {
return b(a);
}
auto IsZero(auto a){
return a([](auto){ return False; })(True);
}
auto Predecessor(auto a) {
return [=](auto f) {
return [=](auto x) {
return a(
[=](auto g) {
return [=](auto h){
return h(g(f));
};
}
)([=](auto){ return x; })([](auto y){ return y; });
};
};
}
auto Subtract(auto a, auto b) {
{
return b([](auto c){ return Predecessor(c); })(a);
};
}
namespace
{
auto Divr(decltype(Zero), auto) {
return Zero;
}
auto Divr(auto a, auto b) {
auto a_minus_b = Subtract(a, b);
auto isZero = IsZero(a_minus_b);
return isZero
(Zero)
(Successor(Divr(isZero(Zero)(a_minus_b), b)));
}
}
auto Divide(auto a, auto b) {
return Divr(Successor(a), b);
}
template <int N> constexpr auto ToChurch() {
if constexpr(N<=0) return Zero;
else return Successor(ToChurch<N-1>());
}
int ToInt(auto church) {
return church([](int n){ return n + 1; })(0);
}
int main() {
auto three = Successor(Successor(Successor(Zero)));
auto four = Successor(three);
auto six = ToChurch<6>();
auto ten = ToChurch<10>();
auto thousand = Exp(ten, three);
std::cout << "\n 3 + 4 = " << ToInt(Add(three, four));
std::cout << "\n 3 * 4 = " << ToInt(Multiply(three, four));
std::cout << "\n 3^4 = " << ToInt(Exp(three, four));
std::cout << "\n 4^3 = " << ToInt(Exp(four, three));
std::cout << "\n 0^0 = " << ToInt(Exp(Zero, Zero));
std::cout << "\n 4 - 3 = " << ToInt(Subtract(four, three));
std::cout << "\n 3 - 4 = " << ToInt(Subtract(three, four));
std::cout << "\n 6 / 3 = " << ToInt(Divide(six, three));
std::cout << "\n 3 / 6 = " << ToInt(Divide(three, six));
auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));
auto looloolool = Successor(looloolooo);
std::cout << "\n 10^9 + 10^6 + 10^3 + 1 = " << ToInt(looloolool);
std::cout << "\n golden ratio = " <<
thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << "\n";
}
| <?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, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?>
|
Write a version of this C++ function in PHP with identical behavior. | #include <iostream>
auto Zero = [](auto){ return [](auto x){ return x; }; };
auto True = [](auto a){ return [=](auto){ return a; }; };
auto False = [](auto){ return [](auto b){ return b; }; };
auto Successor(auto a) {
return [=](auto f) {
return [=](auto x) {
return a(f)(f(x));
};
};
}
auto Add(auto a, auto b) {
return [=](auto f) {
return [=](auto x) {
return a(f)(b(f)(x));
};
};
}
auto Multiply(auto a, auto b) {
return [=](auto f) {
return a(b(f));
};
}
auto Exp(auto a, auto b) {
return b(a);
}
auto IsZero(auto a){
return a([](auto){ return False; })(True);
}
auto Predecessor(auto a) {
return [=](auto f) {
return [=](auto x) {
return a(
[=](auto g) {
return [=](auto h){
return h(g(f));
};
}
)([=](auto){ return x; })([](auto y){ return y; });
};
};
}
auto Subtract(auto a, auto b) {
{
return b([](auto c){ return Predecessor(c); })(a);
};
}
namespace
{
auto Divr(decltype(Zero), auto) {
return Zero;
}
auto Divr(auto a, auto b) {
auto a_minus_b = Subtract(a, b);
auto isZero = IsZero(a_minus_b);
return isZero
(Zero)
(Successor(Divr(isZero(Zero)(a_minus_b), b)));
}
}
auto Divide(auto a, auto b) {
return Divr(Successor(a), b);
}
template <int N> constexpr auto ToChurch() {
if constexpr(N<=0) return Zero;
else return Successor(ToChurch<N-1>());
}
int ToInt(auto church) {
return church([](int n){ return n + 1; })(0);
}
int main() {
auto three = Successor(Successor(Successor(Zero)));
auto four = Successor(three);
auto six = ToChurch<6>();
auto ten = ToChurch<10>();
auto thousand = Exp(ten, three);
std::cout << "\n 3 + 4 = " << ToInt(Add(three, four));
std::cout << "\n 3 * 4 = " << ToInt(Multiply(three, four));
std::cout << "\n 3^4 = " << ToInt(Exp(three, four));
std::cout << "\n 4^3 = " << ToInt(Exp(four, three));
std::cout << "\n 0^0 = " << ToInt(Exp(Zero, Zero));
std::cout << "\n 4 - 3 = " << ToInt(Subtract(four, three));
std::cout << "\n 3 - 4 = " << ToInt(Subtract(three, four));
std::cout << "\n 6 / 3 = " << ToInt(Divide(six, three));
std::cout << "\n 3 / 6 = " << ToInt(Divide(three, six));
auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand));
auto looloolool = Successor(looloolooo);
std::cout << "\n 10^9 + 10^6 + 10^3 + 1 = " << ToInt(looloolool);
std::cout << "\n golden ratio = " <<
thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << "\n";
}
| <?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, &$n, &$m) {
return ($m($f))(($n($f))($x));
};
};
};
$mult = function($n, $m) {
return function($f) use (&$n, &$m) {
return function($x) use (&$f, &$n, &$m) {
return ($m($n($f)))($x);
};
};
};
$power = function($b,$e) {
return $e($b);
};
$to_int = function($f) {
$count_up = function($i) { return $i+1; };
return ($f($count_up))(0);
};
$from_int = function($x) {
$countdown = function($i) use (&$countdown) {
global $zero, $succ;
if ( $i == 0 ) {
return $zero;
} else {
return $succ($countdown($i-1));
};
};
return $countdown($x);
};
$three = $succ($succ($succ($zero)));
$four = $from_int(4);
foreach (array($add($three,$four), $mult($three,$four),
$power($three,$four), $power($four,$three)) as $ch) {
print($to_int($ch));
print("\n");
}
?>
|
Can you help me rewrite this code in PHP instead of C++, keeping it the same logically? | #include <iostream>
class CWidget;
class CFactory
{
friend class CWidget;
private:
unsigned int m_uiCount;
public:
CFactory();
~CFactory();
CWidget* GetWidget();
};
class CWidget
{
private:
CFactory& m_parent;
private:
CWidget();
CWidget(const CWidget&);
CWidget& operator=(const CWidget&);
public:
CWidget(CFactory& parent);
~CWidget();
};
CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}
CWidget* CFactory::GetWidget()
{
return new CWidget(*this);
}
CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
++m_parent.m_uiCount;
std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
CWidget::~CWidget()
{
--m_parent.m_uiCount;
std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
int main()
{
CFactory factory;
CWidget* pWidget1 = factory.GetWidget();
CWidget* pWidget2 = factory.GetWidget();
delete pWidget1;
CWidget* pWidget3 = factory.GetWidget();
delete pWidget3;
delete pWidget2;
}
| <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['answer'];
|
Write the same algorithm in PHP as shown in this C++ implementation. | #include <iostream>
class CWidget;
class CFactory
{
friend class CWidget;
private:
unsigned int m_uiCount;
public:
CFactory();
~CFactory();
CWidget* GetWidget();
};
class CWidget
{
private:
CFactory& m_parent;
private:
CWidget();
CWidget(const CWidget&);
CWidget& operator=(const CWidget&);
public:
CWidget(CFactory& parent);
~CWidget();
};
CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}
CWidget* CFactory::GetWidget()
{
return new CWidget(*this);
}
CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
++m_parent.m_uiCount;
std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
CWidget::~CWidget()
{
--m_parent.m_uiCount;
std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}
int main()
{
CFactory factory;
CWidget* pWidget1 = factory.GetWidget();
CWidget* pWidget2 = factory.GetWidget();
delete pWidget1;
CWidget* pWidget3 = factory.GetWidget();
delete pWidget3;
delete pWidget2;
}
| <?php
class SimpleClass {
private $answer = "hello\"world\nforever :)";
}
$class = new SimpleClass;
ob_start();
var_export($class);
$class_content = ob_get_clean();
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);
$new_class = eval($class_content);
echo $new_class['answer'];
|
Translate the given C++ code snippet into PHP without altering its behavior. | #include <string>
#include <fstream>
#include <boost/serialization/string.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/base_object.hpp>
#include <iostream>
class Employee {
public :
Employee( ) { }
Employee ( const std::string &dep , const std::string &namen )
: department( dep ) , name( namen ) {
my_id = count++ ;
}
std::string getName( ) const {
return name ;
}
std::string getDepartment( ) const {
return department ;
}
int getId( ) const {
return my_id ;
}
void setDepartment( const std::string &dep ) {
department.assign( dep ) ;
}
virtual void print( ) {
std::cout << "Name: " << name << '\n' ;
std::cout << "Id: " << my_id << '\n' ;
std::cout << "Department: " << department << '\n' ;
}
virtual ~Employee( ) { }
static int count ;
private :
std::string name ;
std::string department ;
int my_id ;
friend class boost::serialization::access ;
template <class Archive>
void serialize( Archive &ar, const unsigned int version ) {
ar & my_id ;
ar & name ;
ar & department ;
}
} ;
class Worker : public Employee {
public :
Worker( const std::string & dep, const std::string &namen ,
double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { }
Worker( ) { }
double getSalary( ) {
return salary ;
}
void setSalary( double pay ) {
if ( pay > 0 )
salary = pay ;
}
virtual void print( ) {
Employee::print( ) ;
std::cout << "wage per hour: " << salary << '\n' ;
}
private :
double salary ;
friend class boost::serialization::access ;
template <class Archive>
void serialize ( Archive & ar, const unsigned int version ) {
ar & boost::serialization::base_object<Employee>( *this ) ;
ar & salary ;
}
} ;
int Employee::count = 0 ;
int main( ) {
std::ofstream storefile( "/home/ulrich/objects.dat" ) ;
const Employee emp1( "maintenance" , "Fritz Schmalstieg" ) ;
const Employee emp2( "maintenance" , "John Berry" ) ;
const Employee emp3( "repair" , "Pawel Lichatschow" ) ;
const Employee emp4( "IT" , "Marian Niculescu" ) ;
const Worker worker1( "maintenance" , "Laurent Le Chef" , 20 ) ;
const Worker worker2 ( "IT" , "Srinivan Taraman" , 55.35 ) ;
boost::archive::text_oarchive oar ( storefile ) ;
oar << emp1 ;
oar << emp2 ;
oar << emp3 ;
oar << emp4 ;
oar << worker1 ;
oar << worker2 ;
storefile.close( ) ;
std::cout << "Reading out the data again\n" ;
Employee e1 , e2 , e3 , e4 ;
Worker w1, w2 ;
std::ifstream sourcefile( "/home/ulrich/objects.dat" ) ;
boost::archive::text_iarchive iar( sourcefile ) ;
iar >> e1 >> e2 >> e3 >> e4 ;
iar >> w1 >> w2 ;
sourcefile.close( ) ;
std::cout << "And here are the data after deserialization!( abridged):\n" ;
e1.print( ) ;
e3.print( ) ;
w2.print( ) ;
return 0 ;
}
| $myObj = new Object();
$serializedObj = serialize($myObj);
|
Change the programming language of this snippet from C++ to PHP without modifying what it does. | #include <stdio.h>
#include <math.h>
int p(int year) {
return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7;
}
int is_long_year(int year) {
return p(year) == 4 || p(year - 1) == 3;
}
void print_long_years(int from, int to) {
for (int year = from; year <= to; ++year) {
if (is_long_year(year)) {
printf("%d ", year);
}
}
}
int main() {
printf("Long (53 week) years between 1800 and 2100\n\n");
print_long_years(1800, 2100);
printf("\n");
return 0;
}
| function isLongYear($year) {
return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}
for ($y=1995; $y<=2045; ++$y) {
if (isLongYear($y)) {
printf("%s\n", $y);
}
}
|
Keep all operations the same but rewrite the snippet in PHP. | #include <iostream>
#include <string>
#include <map>
template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
map_type result(update);
result.insert(original.begin(), original.end());
return result;
}
int main() {
typedef std::map<std::string, std::string> map;
map original{
{"name", "Rocket Skates"},
{"price", "12.75"},
{"color", "yellow"}
};
map update{
{"price", "15.25"},
{"color", "red"},
{"year", "1974"}
};
map merged(merge(original, update));
for (auto&& i : merged)
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
}
| <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
|
Can you help me rewrite this code in PHP instead of C++, keeping it the same logically? | #include <iostream>
#include <string>
#include <map>
template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
map_type result(update);
result.insert(original.begin(), original.end());
return result;
}
int main() {
typedef std::map<std::string, std::string> map;
map original{
{"name", "Rocket Skates"},
{"price", "12.75"},
{"color", "yellow"}
};
map update{
{"price", "15.25"},
{"color", "red"},
{"year", "1974"}
};
map merged(merge(original, update));
for (auto&& i : merged)
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
}
| <?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
|
Convert this C++ block to PHP, preserving its control flow and logic. | #include <ctime>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include <map>
class markov {
public:
void create( std::string& file, unsigned int keyLen, unsigned int words ) {
std::ifstream f( file.c_str(), std::ios_base::in );
fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
f.close();
if( fileBuffer.length() < 1 ) return;
createDictionary( keyLen );
createText( words - keyLen );
}
private:
void createText( int w ) {
std::string key, first, second;
size_t next;
std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin();
std::advance( it, rand() % dictionary.size() );
key = ( *it ).first;
std::cout << key;
while( true ) {
std::vector<std::string> d = dictionary[key];
if( d.size() < 1 ) break;
second = d[rand() % d.size()];
if( second.length() < 1 ) break;
std::cout << " " << second;
if( --w < 0 ) break;
next = key.find_first_of( 32, 0 );
first = key.substr( next + 1 );
key = first + " " + second;
}
std::cout << "\n";
}
void createDictionary( unsigned int kl ) {
std::string w1, key;
size_t wc = 0, pos, next;
next = fileBuffer.find_first_not_of( 32, 0 );
if( next == std::string::npos ) return;
while( wc < kl ) {
pos = fileBuffer.find_first_of( ' ', next );
w1 = fileBuffer.substr( next, pos - next );
key += w1 + " ";
next = fileBuffer.find_first_not_of( 32, pos + 1 );
if( next == std::string::npos ) return;
wc++;
}
key = key.substr( 0, key.size() - 1 );
while( true ) {
next = fileBuffer.find_first_not_of( 32, pos + 1 );
if( next == std::string::npos ) return;
pos = fileBuffer.find_first_of( 32, next );
w1 = fileBuffer.substr( next, pos - next );
if( w1.size() < 1 ) break;
if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() )
dictionary[key].push_back( w1 );
key = key.substr( key.find_first_of( 32 ) + 1 ) + " " + w1;
}
}
std::string fileBuffer;
std::map<std::string, std::vector<std::string> > dictionary;
};
int main( int argc, char* argv[] ) {
srand( unsigned( time( 0 ) ) );
markov m;
m.create( std::string( "alice_oz.txt" ), 3, 200 );
return 0;
}
| <?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];
$position += strlen($matches[1]);
}
elseif (preg_match('/^(\s+)/', substr($text, $position, 25), $matches)) {
$position += strlen($matches[1]);
}
else {
die(
'Unknown token found at position ' . $position . ' : ' .
substr($text, $position, 25) . '...' . PHP_EOL
);
}
}
$dictionary = array();
for ($i = 0 ; $i < count($token) - $keySize ; $i++) {
$prefix = '';
$separator = '';
for ($c = 0 ; $c < $keySize ; $c++) {
$prefix .= $separator . $token[$i + $c];
$separator = '.';
}
$dictionary[$prefix][] = $token[$i + $keySize];
}
$rand = rand(0, count($token) - $keySize);
$startToken = array();
for ($c = 0 ; $c < $keySize ; $c++) {
array_push($startToken, $token[$rand + $c]);
}
$text = implode(' ', $startToken);
$words = $keySize;
do {
$tokenKey = implode('.', $startToken);
$rand = rand(0, count($dictionary[$tokenKey]) - 1);
$newToken = $dictionary[$tokenKey][$rand];
$text .= ' ' . $newToken;
$words++;
array_shift($startToken);
array_push($startToken, $newToken);
} while($words < $maxWords);
return $text;
}
srand(5678);
$text = markovChainTextGenerator(
file_get_contents(__DIR__ . '/inc/alice_oz.txt'),
3,
308
);
echo wordwrap($text, 100, PHP_EOL) . PHP_EOL;
|
Write a version of this C++ function in PHP with identical behavior. | #include <iostream>
#include <vector>
#include <string>
#include <list>
#include <limits>
#include <set>
#include <utility>
#include <algorithm>
#include <iterator>
typedef int vertex_t;
typedef double weight_t;
const weight_t max_weight = std::numeric_limits<double>::infinity();
struct neighbor {
vertex_t target;
weight_t weight;
neighbor(vertex_t arg_target, weight_t arg_weight)
: target(arg_target), weight(arg_weight) { }
};
typedef std::vector<std::vector<neighbor> > adjacency_list_t;
void DijkstraComputePaths(vertex_t source,
const adjacency_list_t &adjacency_list,
std::vector<weight_t> &min_distance,
std::vector<vertex_t> &previous)
{
int n = adjacency_list.size();
min_distance.clear();
min_distance.resize(n, max_weight);
min_distance[source] = 0;
previous.clear();
previous.resize(n, -1);
std::set<std::pair<weight_t, vertex_t> > vertex_queue;
vertex_queue.insert(std::make_pair(min_distance[source], source));
while (!vertex_queue.empty())
{
weight_t dist = vertex_queue.begin()->first;
vertex_t u = vertex_queue.begin()->second;
vertex_queue.erase(vertex_queue.begin());
const std::vector<neighbor> &neighbors = adjacency_list[u];
for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();
neighbor_iter != neighbors.end();
neighbor_iter++)
{
vertex_t v = neighbor_iter->target;
weight_t weight = neighbor_iter->weight;
weight_t distance_through_u = dist + weight;
if (distance_through_u < min_distance[v]) {
vertex_queue.erase(std::make_pair(min_distance[v], v));
min_distance[v] = distance_through_u;
previous[v] = u;
vertex_queue.insert(std::make_pair(min_distance[v], v));
}
}
}
}
std::list<vertex_t> DijkstraGetShortestPathTo(
vertex_t vertex, const std::vector<vertex_t> &previous)
{
std::list<vertex_t> path;
for ( ; vertex != -1; vertex = previous[vertex])
path.push_front(vertex);
return path;
}
int main()
{
adjacency_list_t adjacency_list(6);
adjacency_list[0].push_back(neighbor(1, 7));
adjacency_list[0].push_back(neighbor(2, 9));
adjacency_list[0].push_back(neighbor(5, 14));
adjacency_list[1].push_back(neighbor(0, 7));
adjacency_list[1].push_back(neighbor(2, 10));
adjacency_list[1].push_back(neighbor(3, 15));
adjacency_list[2].push_back(neighbor(0, 9));
adjacency_list[2].push_back(neighbor(1, 10));
adjacency_list[2].push_back(neighbor(3, 11));
adjacency_list[2].push_back(neighbor(5, 2));
adjacency_list[3].push_back(neighbor(1, 15));
adjacency_list[3].push_back(neighbor(2, 11));
adjacency_list[3].push_back(neighbor(4, 6));
adjacency_list[4].push_back(neighbor(3, 6));
adjacency_list[4].push_back(neighbor(5, 9));
adjacency_list[5].push_back(neighbor(0, 14));
adjacency_list[5].push_back(neighbor(2, 2));
adjacency_list[5].push_back(neighbor(4, 9));
std::vector<weight_t> min_distance;
std::vector<vertex_t> previous;
DijkstraComputePaths(0, adjacency_list, min_distance, previous);
std::cout << "Distance from 0 to 4: " << min_distance[4] << std::endl;
std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);
std::cout << "Path : ";
std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, " "));
std::cout << std::endl;
return 0;
}
| <?php
function dijkstra($graph_array, $source, $target) {
$vertices = array();
$neighbours = array();
foreach ($graph_array as $edge) {
array_push($vertices, $edge[0], $edge[1]);
$neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]);
$neighbours[$edge[1]][] = array("end" => $edge[0], "cost" => $edge[2]);
}
$vertices = array_unique($vertices);
foreach ($vertices as $vertex) {
$dist[$vertex] = INF;
$previous[$vertex] = NULL;
}
$dist[$source] = 0;
$Q = $vertices;
while (count($Q) > 0) {
$min = INF;
foreach ($Q as $vertex){
if ($dist[$vertex] < $min) {
$min = $dist[$vertex];
$u = $vertex;
}
}
$Q = array_diff($Q, array($u));
if ($dist[$u] == INF or $u == $target) {
break;
}
if (isset($neighbours[$u])) {
foreach ($neighbours[$u] as $arr) {
$alt = $dist[$u] + $arr["cost"];
if ($alt < $dist[$arr["end"]]) {
$dist[$arr["end"]] = $alt;
$previous[$arr["end"]] = $u;
}
}
}
}
$path = array();
$u = $target;
while (isset($previous[$u])) {
array_unshift($path, $u);
$u = $previous[$u];
}
array_unshift($path, $u);
return $path;
}
$graph_array = array(
array("a", "b", 7),
array("a", "c", 9),
array("a", "f", 14),
array("b", "c", 10),
array("b", "d", 15),
array("c", "d", 11),
array("c", "f", 2),
array("d", "e", 6),
array("e", "f", 9)
);
$path = dijkstra($graph_array, "a", "e");
echo "path is: ".implode(", ", $path)."\n";
|
Ensure the translated PHP code behaves exactly like the original C++ snippet. | #include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> dict {
{"One", 1},
{"Two", 2},
{"Three", 7}
};
dict["Three"] = 3;
std::cout << "One: " << dict["One"] << std::endl;
std::cout << "Key/Value pairs: " << std::endl;
for(auto& kv: dict) {
std::cout << " " << kv.first << ": " << kv.second << std::endl;
}
return 0;
}
| <?php
$pairs = array( "hello" => 1,
"world" => 2,
"!" => 3 );
foreach($pairs as $k => $v) {
echo "(k,v) = ($k, $v)\n";
}
foreach(array_keys($pairs) as $key) {
echo "key = $key, value = $pairs[$key]\n";
}
foreach($pairs as $value) {
echo "values = $value\n";
}
?>
|
Convert this C++ snippet to PHP and keep its semantics consistent. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.
It ends with a closing parenthesis (')'), the identifer (if you used one),
and a double-quote.
All characters are okay in a raw string, no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}
| $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
|
Write a version of this C++ function in PHP with identical behavior. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.
It ends with a closing parenthesis (')'), the identifer (if you used one),
and a double-quote.
All characters are okay in a raw string, no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}
| $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
|
Translate the given C++ code snippet into PHP without altering its behavior. | #include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
using tab_t = std::vector<std::vector<std::string>>;
tab_t tab1 {
{"27", "Jonah"}
, {"18", "Alan"}
, {"28", "Glory"}
, {"18", "Popeye"}
, {"28", "Alan"}
};
tab_t tab2 {
{"Jonah", "Whales"}
, {"Jonah", "Spiders"}
, {"Alan", "Ghosts"}
, {"Alan", "Zombies"}
, {"Glory", "Buffy"}
};
std::ostream& operator<<(std::ostream& o, const tab_t& t) {
for(size_t i = 0; i < t.size(); ++i) {
o << i << ":";
for(const auto& e : t[i])
o << '\t' << e;
o << std::endl;
}
return o;
}
tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) {
std::unordered_multimap<std::string, size_t> hashmap;
for(size_t i = 0; i < a.size(); ++i) {
hashmap.insert(std::make_pair(a[i][columna], i));
}
tab_t result;
for(size_t i = 0; i < b.size(); ++i) {
auto range = hashmap.equal_range(b[i][columnb]);
for(auto it = range.first; it != range.second; ++it) {
tab_t::value_type row;
row.insert(row.end() , a[it->second].begin() , a[it->second].end());
row.insert(row.end() , b[i].begin() , b[i].end());
result.push_back(std::move(row));
}
}
return result;
}
int main(int argc, char const *argv[])
{
using namespace std;
int ret = 0;
cout << "Table A: " << endl << tab1 << endl;
cout << "Table B: " << endl << tab2 << endl;
auto tab3 = Join(tab1, 1, tab2, 0);
cout << "Joined tables: " << endl << tab3 << endl;
return ret;
}
| <?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"),
array(28, "Glory"),
array(18, "Popeye"),
array(28, "Alan"));
$table2 = array(array("Jonah", "Whales"),
array("Jonah", "Spiders"),
array("Alan", "Ghosts"),
array("Alan", "Zombies"),
array("Glory", "Buffy"),
array("Bob", "foo"));
foreach (hashJoin($table1, 1, $table2, 0) as $row)
print_r($row);
?>
|
Produce a functionally identical PHP code for the snippet given in C++. | class animal {
public:
virtual void bark()
{
throw "implement me: do not know how to bark";
}
};
class elephant : public animal
{
};
int main()
{
elephant e;
e.bark();
}
| <?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();
$example->foo(); // prints "this is foo"
$example->bar(); // prints "this is bar"
$example->grill(); // prints "tried to handle unknown method grill"
$example->ding("dong"); // prints "tried to handle unknown method ding"
?>
|
Transform the following C++ implementation into PHP, maintaining the same output and logic. | class Animal
{
};
class Dog: public Animal
{
};
class Lab: public Dog
{
};
class Collie: public Dog
{
};
class Cat: public Animal
{
};
| class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
class Lab extends Dog {
}
class Collie extends Dog {
}
|
Change the following C++ code into PHP without altering its purpose. | #include <map>
| $array = array();
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
$array['bar'] = 'foo';
echo($array['foo']); // bar
echo($array['moo']); // Undefined index
$array2 = array('fruit' => 'apple',
'price' => 12.96,
'colour' => 'green');
$array2 = ['fruit' => 'apple',
'price' => 12.96,
'colour' => 'green'];
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null
|
Can you help me rewrite this code in PHP instead of C++, keeping it the same logically? | #include <cstdio>
#include <cstdlib>
class Point {
protected:
int x, y;
public:
Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {}
Point(const Point &p) : x(p.x), y(p.y) {}
virtual ~Point() {}
const Point& operator=(const Point &p) {
if (this != &p) {
x = p.x;
y = p.y;
}
return *this;
}
int getX() { return x; }
int getY() { return y; }
void setX(int x0) { x = x0; }
void setY(int y0) { y = y0; }
virtual void print() { printf("Point\n"); }
};
class Circle: public Point {
private:
int r;
public:
Circle(Point p, int r0 = 0) : Point(p), r(r0) {}
Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {}
virtual ~Circle() {}
const Circle& operator=(const Circle &c) {
if (this != &c) {
x = c.x;
y = c.y;
r = c.r;
}
return *this;
}
int getR() { return r; }
void setR(int r0) { r = r0; }
virtual void print() { printf("Circle\n"); }
};
int main() {
Point *p = new Point();
Point *c = new Circle();
p->print();
c->print();
delete p;
delete c;
return EXIT_SUCCESS;
}
| class Point
{
protected $_x;
protected $_y;
public function __construct()
{
switch( func_num_args() )
{
case 1:
$point = func_get_arg( 0 );
$this->setFromPoint( $point );
break;
case 2:
$x = func_get_arg( 0 );
$y = func_get_arg( 1 );
$this->setX( $x );
$this->setY( $y );
break;
default:
throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );
}
}
public function setFromPoint( Point $point )
{
$this->setX( $point->getX() );
$this->setY( $point->getY() );
}
public function getX()
{
return $this->_x;
}
public function setX( $x )
{
if( !is_numeric( $x ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_x = (float) $x;
}
public function getY()
{
return $this->_y;
}
public function setY( $y )
{
if( !is_numeric( $y ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_y = (float) $y;
}
public function output()
{
echo $this->__toString();
}
public function __toString()
{
return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';
}
}
|
Convert the following code from C++ to PHP, ensuring the logic remains intact. | int a;
| <?php
# NULL typed variable
$null = NULL; var_dump($null); // output: null
# defining a boolean
$boolean = true; var_dump($boolean); // output: boolean true
$boolean = false; var_dump($boolean); // output: boolean false
# bool and boolean is the same
$boolean = (bool)1; var_dump($boolean); // output: boolean true
$boolean = (boolean)1; var_dump($boolean); // output: boolean true
$boolean = (bool)0; var_dump($boolean); // output: boolean false
$boolean = (boolean)0; var_dump($boolean); // output: boolean false
# defining an integer
$int = 0; var_dump($int); // output: int 0
# defining a float,
$float = 0.01; var_dump($float); // output: float 0.01
# which is also identical to "real" and "double"
var_dump((double)$float); // output: float 0.01
var_dump((real)$float); // output: float 0.01
# casting back to int (auto flooring the value)
var_dump((int)$float); // output: int 0
var_dump((int)($float+1)); // output: int 1
var_dump((int)($float+1.9)); // output: int 1
# defining a string
$string = 'string';
var_dump($string); // output: string 'string' (length=6)
# referencing a variable (there are no pointers in PHP).
$another_string = &$string;
var_dump($another_string);
$string = "I'm the same string!";
var_dump($another_string);
# "deleting" a variable from memory
unset($another_string);
$string = 'string';
$parsed_string = "This is a $string";
var_dump($parsed_string);
$parsed_string .= " with another {$string}";
var_dump($parsed_string);
# with string parsing
$heredoc = <<<HEREDOC
This is the content of \$string: {$string}
HEREDOC;
var_dump($heredoc);
# without string parsing (notice the single quotes surrounding NOWDOC)
$nowdoc = <<<'NOWDOC'
This is the content of \$string: {$string}
NOWDOC;
var_dump($nowdoc);
# as of PHP5, defining an object typed stdClass => standard class
$stdObject = new stdClass(); var_dump($stdObject);
# defining an object typed Foo
class Foo {}
$foo = new Foo(); var_dump($foo);
# defining an empty array
$array = array(); var_dump($array);
$assoc = array(
0 => $int,
'integer' => $int,
1 => $float,
'float' => $float,
2 => $string,
'string' => $string,
3 => NULL, // <=== key 3 is NULL
3, // <=== this is a value, not a key (key is 4)
5 => $stdObject,
'Foo' => $foo,
);
var_dump($assoc);
function a_function()
{
# not reachable
var_dump(isset($foo)); // output: boolean false
global $foo;
# "global" (reachable) inside a_function()'s scope
var_dump(isset($foo)); // output: boolean true
}
a_function();
|
Maintain the same structure and functionality when rewriting this code in PHP. | #include <cmath>
#include <iostream>
#include <string>
using namespace std;
struct LoggingMonad
{
double Value;
string Log;
};
auto operator>>(const LoggingMonad& monad, auto f)
{
auto result = f(monad.Value);
return LoggingMonad{result.Value, monad.Log + "\n" + result.Log};
}
auto Root = [](double x){ return sqrt(x); };
auto AddOne = [](double x){ return x + 1; };
auto Half = [](double x){ return x / 2.0; };
auto MakeWriter = [](auto f, string message)
{
return [=](double x){return LoggingMonad(f(x), message);};
};
auto writerRoot = MakeWriter(Root, "Taking square root");
auto writerAddOne = MakeWriter(AddOne, "Adding 1");
auto writerHalf = MakeWriter(Half, "Dividing by 2");
int main()
{
auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf;
cout << result.Log << "\nResult: " << result.Value;
}
| 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(callable $mapper): WriterMonad {
$mapped = $mapper($this->value);
assert($mapped instanceof WriterMonad);
return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
}
public function value() {
return $this->value;
}
public function logs(): array {
return $this->logs;
}
}
$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;
$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);
$result = WriterMonad::unit(5, "Initial value")
->bind($m($root, "square root"))
->bind($m($addOne, "add one"))
->bind($m($half, "half"));
print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | from ftplib import FTP
ftp = FTP('kernel.org')
ftp.login()
ftp.cwd('/pub/linux/kernel')
ftp.set_pasv(True)
print ftp.retrlines('LIST')
print ftp.retrbinary('RETR README', open('README', 'wb').write)
ftp.quit()
| import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FTPconn {
public static void main(String[] args) throws IOException {
String server = "ftp.hq.nasa.gov";
int port = 21;
String user = "anonymous";
String pass = "ftptest@example.com";
OutputStream output = null;
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
serverReply(ftpClient);
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Failure. Server reply code: " + replyCode);
return;
}
serverReply(ftpClient);
if (!ftpClient.login(user, pass)) {
System.out.println("Could not login to the server.");
return;
}
String dir = "pub/issoutreach/Living in Space Stories (MP3 Files)/";
if (!ftpClient.changeWorkingDirectory(dir)) {
System.out.println("Change directory failed.");
return;
}
ftpClient.enterLocalPassiveMode();
for (FTPFile file : ftpClient.listFiles())
System.out.println(file);
String filename = "Can People go to Mars.mp3";
output = new FileOutputStream(filename);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if (!ftpClient.retrieveFile(filename, output)) {
System.out.println("Retrieving file failed");
return;
}
serverReply(ftpClient);
ftpClient.logout();
} finally {
if (output != null)
output.close();
}
}
private static void serverReply(FTPClient ftpClient) {
for (String reply : ftpClient.getReplyStrings()) {
System.out.println(reply);
}
}
}
|
Translate this program into Java but keep the logic exactly as in Python. |
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("New digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
if __name__ == '__main__': main()
| import java.util.*;
public class Game24 {
static Random r = new Random();
public static void main(String[] args) {
int[] digits = randomDigits();
Scanner in = new Scanner(System.in);
System.out.print("Make 24 using these digits: ");
System.out.println(Arrays.toString(digits));
System.out.print("> ");
Stack<Float> s = new Stack<>();
long total = 0;
for (char c : in.nextLine().toCharArray()) {
if ('0' <= c && c <= '9') {
int d = c - '0';
total += (1 << (d * 5));
s.push((float) d);
} else if ("+/-*".indexOf(c) != -1) {
s.push(applyOperator(s.pop(), s.pop(), c));
}
}
if (tallyDigits(digits) != total)
System.out.print("Not the same digits. ");
else if (Math.abs(24 - s.peek()) < 0.001F)
System.out.println("Correct!");
else
System.out.print("Not correct.");
}
static float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
static long tallyDigits(int[] a) {
long total = 0;
for (int i = 0; i < 4; i++)
total += (1 << (a[i] * 5));
return total;
}
static int[] randomDigits() {
int[] result = new int[4];
for (int i = 0; i < 4; i++)
result[i] = r.nextInt(9) + 1;
return result;
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. |
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("New digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
if __name__ == '__main__': main()
| import java.util.*;
public class Game24 {
static Random r = new Random();
public static void main(String[] args) {
int[] digits = randomDigits();
Scanner in = new Scanner(System.in);
System.out.print("Make 24 using these digits: ");
System.out.println(Arrays.toString(digits));
System.out.print("> ");
Stack<Float> s = new Stack<>();
long total = 0;
for (char c : in.nextLine().toCharArray()) {
if ('0' <= c && c <= '9') {
int d = c - '0';
total += (1 << (d * 5));
s.push((float) d);
} else if ("+/-*".indexOf(c) != -1) {
s.push(applyOperator(s.pop(), s.pop(), c));
}
}
if (tallyDigits(digits) != total)
System.out.print("Not the same digits. ");
else if (Math.abs(24 - s.peek()) < 0.001F)
System.out.println("Correct!");
else
System.out.print("Not correct.");
}
static float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
static long tallyDigits(int[] a) {
long total = 0;
for (int i = 0; i < 4; i++)
total += (1 << (a[i] * 5));
return total;
}
static int[] randomDigits() {
int[] result = new int[4];
for (int i = 0; i < 4; i++)
result[i] = r.nextInt(9) + 1;
return result;
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | for i in range(1, 11):
if i % 5 == 0:
print(i)
continue
print(i, end=', ')
| for(int i = 1;i <= 10; i++){
System.out.print(i);
if(i % 5 == 0){
System.out.println();
continue;
}
System.out.print(", ");
}
|
Port the provided Python code into Java while preserving the original functionality. |
from livewires import *
horiz=640; vert=480
begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black)
NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"]
stepik=horiz/len(NameColors)
for index,each in enumerate(NameColors):
ExcStrng="set_colour(Colour."+each+")"
exec ExcStrng
box(index*stepik,0,(index+1)*stepik,vert,filled=1)
while keys_pressed() != ['x']:
pass
end_graphics()
| import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class ColorFrame extends JFrame {
public ColorFrame(int width, int height) {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(width, height);
this.setVisible(true);
}
@Override
public void paint(Graphics g) {
Color[] colors = { Color.black, Color.red, Color.green, Color.blue,
Color.pink, Color.CYAN, Color.yellow, Color.white };
for (int i = 0; i < colors.length; i++) {
g.setColor(colors[i]);
g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()
/ colors.length, this.getHeight());
}
}
public static void main(String args[]) {
new ColorFrame(200, 200);
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. |
from livewires import *
horiz=640; vert=480
begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black)
NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"]
stepik=horiz/len(NameColors)
for index,each in enumerate(NameColors):
ExcStrng="set_colour(Colour."+each+")"
exec ExcStrng
box(index*stepik,0,(index+1)*stepik,vert,filled=1)
while keys_pressed() != ['x']:
pass
end_graphics()
| import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class ColorFrame extends JFrame {
public ColorFrame(int width, int height) {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(width, height);
this.setVisible(true);
}
@Override
public void paint(Graphics g) {
Color[] colors = { Color.black, Color.red, Color.green, Color.blue,
Color.pink, Color.CYAN, Color.yellow, Color.white };
for (int i = 0; i < colors.length; i++) {
g.setColor(colors[i]);
g.fillRect(this.getWidth() / colors.length * i, 0, this.getWidth()
/ colors.length, this.getHeight());
}
}
public static void main(String args[]) {
new ColorFrame(200, 200);
}
}
|
Generate an equivalent Java version of this Python code. | from pprint import pprint
def matrixMul(A, B):
TB = zip(*B)
return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]
def pivotize(m):
n = len(m)
ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]
for j in xrange(n):
row = max(xrange(j, n), key=lambda i: abs(m[i][j]))
if j != row:
ID[j], ID[row] = ID[row], ID[j]
return ID
def lu(A):
n = len(A)
L = [[0.0] * n for i in xrange(n)]
U = [[0.0] * n for i in xrange(n)]
P = pivotize(A)
A2 = matrixMul(P, A)
for j in xrange(n):
L[j][j] = 1.0
for i in xrange(j+1):
s1 = sum(U[k][j] * L[i][k] for k in xrange(i))
U[i][j] = A2[i][j] - s1
for i in xrange(j, n):
s2 = sum(U[k][j] * L[i][k] for k in xrange(j))
L[i][j] = (A2[i][j] - s2) / U[j][j]
return (L, U, P)
a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]
for part in lu(a):
pprint(part, width=19)
print
print
b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]]
for part in lu(b):
pprint(part)
print
| import static java.util.Arrays.stream;
import java.util.Locale;
import static java.util.stream.IntStream.range;
public class Test {
static double dotProduct(double[] a, double[] b) {
return range(0, a.length).mapToDouble(i -> a[i] * b[i]).sum();
}
static double[][] matrixMul(double[][] A, double[][] B) {
double[][] result = new double[A.length][B[0].length];
double[] aux = new double[B.length];
for (int j = 0; j < B[0].length; j++) {
for (int k = 0; k < B.length; k++)
aux[k] = B[k][j];
for (int i = 0; i < A.length; i++)
result[i][j] = dotProduct(A[i], aux);
}
return result;
}
static double[][] pivotize(double[][] m) {
int n = m.length;
double[][] id = range(0, n).mapToObj(j -> range(0, n)
.mapToDouble(i -> i == j ? 1 : 0).toArray())
.toArray(double[][]::new);
for (int i = 0; i < n; i++) {
double maxm = m[i][i];
int row = i;
for (int j = i; j < n; j++)
if (m[j][i] > maxm) {
maxm = m[j][i];
row = j;
}
if (i != row) {
double[] tmp = id[i];
id[i] = id[row];
id[row] = tmp;
}
}
return id;
}
static double[][][] lu(double[][] A) {
int n = A.length;
double[][] L = new double[n][n];
double[][] U = new double[n][n];
double[][] P = pivotize(A);
double[][] A2 = matrixMul(P, A);
for (int j = 0; j < n; j++) {
L[j][j] = 1;
for (int i = 0; i < j + 1; i++) {
double s1 = 0;
for (int k = 0; k < i; k++)
s1 += U[k][j] * L[i][k];
U[i][j] = A2[i][j] - s1;
}
for (int i = j; i < n; i++) {
double s2 = 0;
for (int k = 0; k < j; k++)
s2 += U[k][j] * L[i][k];
L[i][j] = (A2[i][j] - s2) / U[j][j];
}
}
return new double[][][]{L, U, P};
}
static void print(double[][] m) {
stream(m).forEach(a -> {
stream(a).forEach(n -> System.out.printf(Locale.US, "%5.1f ", n));
System.out.println();
});
System.out.println();
}
public static void main(String[] args) {
double[][] a = {{1.0, 3, 5}, {2.0, 4, 7}, {1.0, 1, 0}};
double[][] b = {{11.0, 9, 24, 2}, {1.0, 5, 2, 6}, {3.0, 17, 18, 1},
{2.0, 5, 7, 1}};
for (double[][] m : lu(a))
print(m);
System.out.println();
for (double[][] m : lu(b))
print(m);
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | def genfizzbuzz(factorwords, numbers):
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
lines = []
for num in numbers:
words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
lines.append(words if words else str(num))
return '\n'.join(lines)
if __name__ == '__main__':
print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
| public class FizzBuzz {
public static void main(String[] args) {
Sound[] sounds = {new Sound(3, "Fizz"), new Sound(5, "Buzz"), new Sound(7, "Baxx")};
for (int i = 1; i <= 20; i++) {
StringBuilder sb = new StringBuilder();
for (Sound sound : sounds) {
sb.append(sound.generate(i));
}
System.out.println(sb.length() == 0 ? i : sb.toString());
}
}
private static class Sound {
private final int trigger;
private final String onomatopoeia;
public Sound(int trigger, String onomatopoeia) {
this.trigger = trigger;
this.onomatopoeia = onomatopoeia;
}
public String generate(int i) {
return i % trigger == 0 ? onomatopoeia : "";
}
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
| package linenbr7;
import java.io.*;
public class LineNbr7 {
public static void main(String[] args) throws Exception {
File f = new File(args[0]);
if (!f.isFile() || !f.canRead())
throw new IOException("can't read " + args[0]);
BufferedReader br = new BufferedReader(new FileReader(f));
try (LineNumberReader lnr = new LineNumberReader(br)) {
String line = null;
int lnum = 0;
while ((line = lnr.readLine()) != null
&& (lnum = lnr.getLineNumber()) < 7) {
}
switch (lnum) {
case 0:
System.out.println("the file has zero length");
break;
case 7:
boolean empty = "".equals(line);
System.out.println("line 7: " + (empty ? "empty" : line));
break;
default:
System.out.println("the file has only " + lnum + " line(s)");
}
}
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
| package linenbr7;
import java.io.*;
public class LineNbr7 {
public static void main(String[] args) throws Exception {
File f = new File(args[0]);
if (!f.isFile() || !f.canRead())
throw new IOException("can't read " + args[0]);
BufferedReader br = new BufferedReader(new FileReader(f));
try (LineNumberReader lnr = new LineNumberReader(br)) {
String line = null;
int lnum = 0;
while ((line = lnr.readLine()) != null
&& (lnum = lnr.getLineNumber()) < 7) {
}
switch (lnum) {
case 0:
System.out.println("the file has zero length");
break;
case 7:
boolean empty = "".equals(line);
System.out.println("line 7: " + (empty ? "empty" : line));
break;
default:
System.out.println("the file has only " + lnum + " line(s)");
}
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | def isExt(fileName, extensions):
return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
| import java.util.Arrays;
import java.util.Comparator;
public class FileExt{
public static void main(String[] args){
String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"};
String[] exts = {".txt",".gz","",".bat"};
System.out.println("Extensions: " + Arrays.toString(exts) + "\n");
for(String test:tests){
System.out.println(test +": " + extIsIn(test, exts));
}
}
public static boolean extIsIn(String test, String... exts){
int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\'));
String filename = test.substring(lastSlash + 1);
int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');
String ext = filename.substring(lastDot);
Arrays.sort(exts);
return Arrays.binarySearch(exts, ext, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
}) >= 0;
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | def isExt(fileName, extensions):
return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
| import java.util.Arrays;
import java.util.Comparator;
public class FileExt{
public static void main(String[] args){
String[] tests = {"text.txt", "text.TXT", "test.tar.gz", "test/test2.exe", "test\\test2.exe", "test", "a/b/c\\d/foo"};
String[] exts = {".txt",".gz","",".bat"};
System.out.println("Extensions: " + Arrays.toString(exts) + "\n");
for(String test:tests){
System.out.println(test +": " + extIsIn(test, exts));
}
}
public static boolean extIsIn(String test, String... exts){
int lastSlash = Math.max(test.lastIndexOf('/'), test.lastIndexOf('\\'));
String filename = test.substring(lastSlash + 1);
int lastDot = filename.lastIndexOf('.') == -1 ? filename.length() : filename.lastIndexOf('.');
String ext = filename.substring(lastDot);
Arrays.sort(exts);
return Arrays.binarySearch(exts, ext, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
}) >= 0;
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. |
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from itertools import izip_longest as zip_longest
else:
from itertools import zip_longest
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def ask4():
'get four random digits >0 from the player'
digits = ''
while len(digits) != 4 or not all(d in '123456789' for d in digits):
digits = input('Enter the digits to solve for: ')
digits = ''.join(digits.strip().split())
return list(digits)
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def solve(digits):
digilen = len(digits)
exprlen = 2 * digilen - 1
digiperm = sorted(set(permutations(digits)))
opcomb = list(product('+-*/', repeat=digilen-1))
brackets = ( [()] + [(x,y)
for x in range(0, exprlen, 2)
for y in range(x+4, exprlen+2, 2)
if (x,y) != (0,exprlen+1)]
+ [(0, 3+1, 4+2, 7+3)] )
for d in digiperm:
for ops in opcomb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insertpoint, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insertpoint, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [ (term if not term.startswith('F(') else term[2])
for term in exp ]
ans = ' '.join(exp).rstrip()
print ("Solution found:",ans)
return ans
print ("No solution found for:", ' '.join(digits))
return '!'
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer == '?':
solve(digits)
answer = '!'
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if answer == '!!':
digits = ask4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
if '/' in answer:
answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)
for char in answer )
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
main()
| import java.util.*;
public class Game24Player {
final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo",
"nnnnooo"};
final String ops = "+-*/^";
String solution;
List<Integer> digits;
public static void main(String[] args) {
new Game24Player().play();
}
void play() {
digits = getSolvableDigits();
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Make 24 using these digits: ");
System.out.println(digits);
System.out.println("(Enter 'q' to quit, 's' for a solution)");
System.out.print("> ");
String line = in.nextLine();
if (line.equalsIgnoreCase("q")) {
System.out.println("\nThanks for playing");
return;
}
if (line.equalsIgnoreCase("s")) {
System.out.println(solution);
digits = getSolvableDigits();
continue;
}
char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray();
try {
validate(entry);
if (evaluate(infixToPostfix(entry))) {
System.out.println("\nCorrect! Want to try another? ");
digits = getSolvableDigits();
} else {
System.out.println("\nNot correct.");
}
} catch (Exception e) {
System.out.printf("%n%s Try again.%n", e.getMessage());
}
}
}
void validate(char[] input) throws Exception {
int total1 = 0, parens = 0, opsCount = 0;
for (char c : input) {
if (Character.isDigit(c))
total1 += 1 << (c - '0') * 4;
else if (c == '(')
parens++;
else if (c == ')')
parens--;
else if (ops.indexOf(c) != -1)
opsCount++;
if (parens < 0)
throw new Exception("Parentheses mismatch.");
}
if (parens != 0)
throw new Exception("Parentheses mismatch.");
if (opsCount != 3)
throw new Exception("Wrong number of operators.");
int total2 = 0;
for (int d : digits)
total2 += 1 << d * 4;
if (total1 != total2)
throw new Exception("Not the same digits.");
}
boolean evaluate(char[] line) throws Exception {
Stack<Float> s = new Stack<>();
try {
for (char c : line) {
if ('0' <= c && c <= '9')
s.push((float) c - '0');
else
s.push(applyOperator(s.pop(), s.pop(), c));
}
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return (Math.abs(24 - s.peek()) < 0.001F);
}
float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
List<Integer> randomDigits() {
Random r = new Random();
List<Integer> result = new ArrayList<>(4);
for (int i = 0; i < 4; i++)
result.add(r.nextInt(9) + 1);
return result;
}
List<Integer> getSolvableDigits() {
List<Integer> result;
do {
result = randomDigits();
} while (!isSolvable(result));
return result;
}
boolean isSolvable(List<Integer> digits) {
Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);
permute(digits, dPerms, 0);
int total = 4 * 4 * 4;
List<List<Integer>> oPerms = new ArrayList<>(total);
permuteOperators(oPerms, 4, total);
StringBuilder sb = new StringBuilder(4 + 3);
for (String pattern : patterns) {
char[] patternChars = pattern.toCharArray();
for (List<Integer> dig : dPerms) {
for (List<Integer> opr : oPerms) {
int i = 0, j = 0;
for (char c : patternChars) {
if (c == 'n')
sb.append(dig.get(i++));
else
sb.append(ops.charAt(opr.get(j++)));
}
String candidate = sb.toString();
try {
if (evaluate(candidate.toCharArray())) {
solution = postfixToInfix(candidate);
return true;
}
} catch (Exception ignored) {
}
sb.setLength(0);
}
}
}
return false;
}
String postfixToInfix(String postfix) {
class Expression {
String op, ex;
int prec = 3;
Expression(String e) {
ex = e;
}
Expression(String e1, String e2, String o) {
ex = String.format("%s %s %s", e1, o, e2);
op = o;
prec = ops.indexOf(o) / 2;
}
}
Stack<Expression> expr = new Stack<>();
for (char c : postfix.toCharArray()) {
int idx = ops.indexOf(c);
if (idx != -1) {
Expression r = expr.pop();
Expression l = expr.pop();
int opPrec = idx / 2;
if (l.prec < opPrec)
l.ex = '(' + l.ex + ')';
if (r.prec <= opPrec)
r.ex = '(' + r.ex + ')';
expr.push(new Expression(l.ex, r.ex, "" + c));
} else {
expr.push(new Expression("" + c));
}
}
return expr.peek().ex;
}
char[] infixToPostfix(char[] infix) throws Exception {
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
try {
for (char c : infix) {
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 >= prec1)
sb.append(ops.charAt(s.pop()));
else
break;
}
s.push(idx);
}
} else if (c == '(') {
s.push(-2);
} else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop()));
s.pop();
} else {
sb.append(c);
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop()));
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return sb.toString().toCharArray();
}
void permute(List<Integer> lst, Set<List<Integer>> res, int k) {
for (int i = k; i < lst.size(); i++) {
Collections.swap(lst, i, k);
permute(lst, res, k + 1);
Collections.swap(lst, k, i);
}
if (k == lst.size())
res.add(new ArrayList<>(lst));
}
void permuteOperators(List<List<Integer>> res, int n, int total) {
for (int i = 0, npow = n * n; i < total; i++)
res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? |
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from itertools import izip_longest as zip_longest
else:
from itertools import zip_longest
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def ask4():
'get four random digits >0 from the player'
digits = ''
while len(digits) != 4 or not all(d in '123456789' for d in digits):
digits = input('Enter the digits to solve for: ')
digits = ''.join(digits.strip().split())
return list(digits)
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def solve(digits):
digilen = len(digits)
exprlen = 2 * digilen - 1
digiperm = sorted(set(permutations(digits)))
opcomb = list(product('+-*/', repeat=digilen-1))
brackets = ( [()] + [(x,y)
for x in range(0, exprlen, 2)
for y in range(x+4, exprlen+2, 2)
if (x,y) != (0,exprlen+1)]
+ [(0, 3+1, 4+2, 7+3)] )
for d in digiperm:
for ops in opcomb:
if '/' in ops:
d2 = [('F(%s)' % i) for i in d]
else:
d2 = d
ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))
for b in brackets:
exp = ex[::]
for insertpoint, bracket in zip(b, '()'*(len(b)//2)):
exp.insert(insertpoint, bracket)
txt = ''.join(exp)
try:
num = eval(txt)
except ZeroDivisionError:
continue
if num == 24:
if '/' in ops:
exp = [ (term if not term.startswith('F(') else term[2])
for term in exp ]
ans = ' '.join(exp).rstrip()
print ("Solution found:",ans)
return ans
print ("No solution found for:", ' '.join(digits))
return '!'
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer == '?':
solve(digits)
answer = '!'
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if answer == '!!':
digits = ask4()
trial = 0
print ("\nNew digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
if '/' in answer:
answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)
for char in answer )
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
main()
| import java.util.*;
public class Game24Player {
final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo",
"nnnnooo"};
final String ops = "+-*/^";
String solution;
List<Integer> digits;
public static void main(String[] args) {
new Game24Player().play();
}
void play() {
digits = getSolvableDigits();
Scanner in = new Scanner(System.in);
while (true) {
System.out.print("Make 24 using these digits: ");
System.out.println(digits);
System.out.println("(Enter 'q' to quit, 's' for a solution)");
System.out.print("> ");
String line = in.nextLine();
if (line.equalsIgnoreCase("q")) {
System.out.println("\nThanks for playing");
return;
}
if (line.equalsIgnoreCase("s")) {
System.out.println(solution);
digits = getSolvableDigits();
continue;
}
char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray();
try {
validate(entry);
if (evaluate(infixToPostfix(entry))) {
System.out.println("\nCorrect! Want to try another? ");
digits = getSolvableDigits();
} else {
System.out.println("\nNot correct.");
}
} catch (Exception e) {
System.out.printf("%n%s Try again.%n", e.getMessage());
}
}
}
void validate(char[] input) throws Exception {
int total1 = 0, parens = 0, opsCount = 0;
for (char c : input) {
if (Character.isDigit(c))
total1 += 1 << (c - '0') * 4;
else if (c == '(')
parens++;
else if (c == ')')
parens--;
else if (ops.indexOf(c) != -1)
opsCount++;
if (parens < 0)
throw new Exception("Parentheses mismatch.");
}
if (parens != 0)
throw new Exception("Parentheses mismatch.");
if (opsCount != 3)
throw new Exception("Wrong number of operators.");
int total2 = 0;
for (int d : digits)
total2 += 1 << d * 4;
if (total1 != total2)
throw new Exception("Not the same digits.");
}
boolean evaluate(char[] line) throws Exception {
Stack<Float> s = new Stack<>();
try {
for (char c : line) {
if ('0' <= c && c <= '9')
s.push((float) c - '0');
else
s.push(applyOperator(s.pop(), s.pop(), c));
}
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return (Math.abs(24 - s.peek()) < 0.001F);
}
float applyOperator(float a, float b, char c) {
switch (c) {
case '+':
return a + b;
case '-':
return b - a;
case '*':
return a * b;
case '/':
return b / a;
default:
return Float.NaN;
}
}
List<Integer> randomDigits() {
Random r = new Random();
List<Integer> result = new ArrayList<>(4);
for (int i = 0; i < 4; i++)
result.add(r.nextInt(9) + 1);
return result;
}
List<Integer> getSolvableDigits() {
List<Integer> result;
do {
result = randomDigits();
} while (!isSolvable(result));
return result;
}
boolean isSolvable(List<Integer> digits) {
Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2);
permute(digits, dPerms, 0);
int total = 4 * 4 * 4;
List<List<Integer>> oPerms = new ArrayList<>(total);
permuteOperators(oPerms, 4, total);
StringBuilder sb = new StringBuilder(4 + 3);
for (String pattern : patterns) {
char[] patternChars = pattern.toCharArray();
for (List<Integer> dig : dPerms) {
for (List<Integer> opr : oPerms) {
int i = 0, j = 0;
for (char c : patternChars) {
if (c == 'n')
sb.append(dig.get(i++));
else
sb.append(ops.charAt(opr.get(j++)));
}
String candidate = sb.toString();
try {
if (evaluate(candidate.toCharArray())) {
solution = postfixToInfix(candidate);
return true;
}
} catch (Exception ignored) {
}
sb.setLength(0);
}
}
}
return false;
}
String postfixToInfix(String postfix) {
class Expression {
String op, ex;
int prec = 3;
Expression(String e) {
ex = e;
}
Expression(String e1, String e2, String o) {
ex = String.format("%s %s %s", e1, o, e2);
op = o;
prec = ops.indexOf(o) / 2;
}
}
Stack<Expression> expr = new Stack<>();
for (char c : postfix.toCharArray()) {
int idx = ops.indexOf(c);
if (idx != -1) {
Expression r = expr.pop();
Expression l = expr.pop();
int opPrec = idx / 2;
if (l.prec < opPrec)
l.ex = '(' + l.ex + ')';
if (r.prec <= opPrec)
r.ex = '(' + r.ex + ')';
expr.push(new Expression(l.ex, r.ex, "" + c));
} else {
expr.push(new Expression("" + c));
}
}
return expr.peek().ex;
}
char[] infixToPostfix(char[] infix) throws Exception {
StringBuilder sb = new StringBuilder();
Stack<Integer> s = new Stack<>();
try {
for (char c : infix) {
int idx = ops.indexOf(c);
if (idx != -1) {
if (s.isEmpty())
s.push(idx);
else {
while (!s.isEmpty()) {
int prec2 = s.peek() / 2;
int prec1 = idx / 2;
if (prec2 >= prec1)
sb.append(ops.charAt(s.pop()));
else
break;
}
s.push(idx);
}
} else if (c == '(') {
s.push(-2);
} else if (c == ')') {
while (s.peek() != -2)
sb.append(ops.charAt(s.pop()));
s.pop();
} else {
sb.append(c);
}
}
while (!s.isEmpty())
sb.append(ops.charAt(s.pop()));
} catch (EmptyStackException e) {
throw new Exception("Invalid entry.");
}
return sb.toString().toCharArray();
}
void permute(List<Integer> lst, Set<List<Integer>> res, int k) {
for (int i = k; i < lst.size(); i++) {
Collections.swap(lst, i, k);
permute(lst, res, k + 1);
Collections.swap(lst, k, i);
}
if (k == lst.size())
res.add(new ArrayList<>(lst));
}
void permuteOperators(List<List<Integer>> res, int n, int total) {
for (int i = 0, npow = n * n; i < total; i++)
res.add(Arrays.asList((i / npow), (i % npow) / n, i % n));
}
}
|
Translate this program into Java but keep the logic exactly as in Python. |
import threading
import time
import random
def worker(workernum, barrier):
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier.wait()
sleeptime = random.random()
print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
time.sleep(sleeptime)
print('Exiting worker'+str(workernum))
barrier = threading.Barrier(3)
w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))
w1.start()
w2.start()
w3.start()
| import java.util.Scanner;
import java.util.Random;
public class CheckpointSync{
public static void main(String[] args){
System.out.print("Enter number of workers to use: ");
Scanner in = new Scanner(System.in);
Worker.nWorkers = in.nextInt();
System.out.print("Enter number of tasks to complete:");
runTasks(in.nextInt());
}
private static void runTasks(int nTasks){
for(int i = 0; i < nTasks; i++){
System.out.println("Starting task number " + (i+1) + ".");
runThreads();
Worker.checkpoint();
}
}
private static void runThreads(){
for(int i = 0; i < Worker.nWorkers; i ++){
new Thread(new Worker(i+1)).start();
}
}
public static class Worker implements Runnable{
public Worker(int threadID){
this.threadID = threadID;
}
public void run(){
work();
}
private synchronized void work(){
try {
int workTime = rgen.nextInt(900) + 100;
System.out.println("Worker " + threadID + " will work for " + workTime + " msec.");
Thread.sleep(workTime);
nFinished++;
System.out.println("Worker " + threadID + " is ready");
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
public static synchronized void checkpoint(){
while(nFinished != nWorkers){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.err.println("Error: thread execution interrupted");
e.printStackTrace();
}
}
nFinished = 0;
}
private int threadID;
private static Random rgen = new Random();
private static int nFinished = 0;
public static int nWorkers = 0;
}
}
|
Write the same code in Java as shown below in Python. | def tobits(n, _group=8, _sep='_', _pad=False):
'Express n as binary bits with separator'
bits = '{0:b}'.format(n)[::-1]
if _pad:
bits = '{0:0{1}b}'.format(n,
((_group+len(bits)-1)//_group)*_group)[::-1]
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
answer = '0'*(len(_sep)-1) + answer
else:
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
return answer
def tovlq(n):
return tobits(n, _group=7, _sep='1_', _pad=True)
def toint(vlq):
return int(''.join(vlq.split('_1')), 2)
def vlqsend(vlq):
for i, byte in enumerate(vlq.split('_')[::-1]):
print('Sent byte {0:3}: {1:
| public class VLQCode
{
public static byte[] encode(long n)
{
int numRelevantBits = 64 - Long.numberOfLeadingZeros(n);
int numBytes = (numRelevantBits + 6) / 7;
if (numBytes == 0)
numBytes = 1;
byte[] output = new byte[numBytes];
for (int i = numBytes - 1; i >= 0; i--)
{
int curByte = (int)(n & 0x7F);
if (i != (numBytes - 1))
curByte |= 0x80;
output[i] = (byte)curByte;
n >>>= 7;
}
return output;
}
public static long decode(byte[] b)
{
long n = 0;
for (int i = 0; i < b.length; i++)
{
int curByte = b[i] & 0xFF;
n = (n << 7) | (curByte & 0x7F);
if ((curByte & 0x80) == 0)
break;
}
return n;
}
public static String byteArrayToString(byte[] b)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++)
{
if (i > 0)
sb.append(", ");
String s = Integer.toHexString(b[i] & 0xFF);
if (s.length() < 2)
s = "0" + s;
sb.append(s);
}
return sb.toString();
}
public static void main(String[] args)
{
long[] testNumbers = { 2097152, 2097151, 1, 127, 128, 589723405834L };
for (long n : testNumbers)
{
byte[] encoded = encode(n);
long decoded = decode(encoded);
System.out.println("Original input=" + n + ", encoded = [" + byteArrayToString(encoded) + "], decoded=" + decoded + ", " + ((n == decoded) ? "OK" : "FAIL"));
}
}
}
|
Write the same code in Java as shown below in Python. |
import argh
import hashlib
import sys
@argh.arg('filename', nargs='?', default=None)
def main(filename, block_size=1024*1024):
if filename:
fin = open(filename, 'rb')
else:
fin = sys.stdin
stack = []
block = fin.read(block_size)
while block:
node = (0, hashlib.sha256(block).digest())
stack.append(node)
while len(stack) >= 2 and stack[-2][0] == stack[-1][0]:
a = stack[-2]
b = stack[-1]
l = a[0]
stack[-2:] = [(l+1, hashlib.sha256(a[1] + b[1]).digest())]
block = fin.read(block_size)
while len(stack) > 1:
a = stack[-2]
b = stack[-1]
al = a[0]
bl = b[0]
stack[-2:] = [(max(al, bl)+1, hashlib.sha256(a[1] + b[1]).digest())]
print(stack[0][1].hex())
argh.dispatch_command(main)
| import java.io.*;
import java.security.*;
import java.util.*;
public class SHA256MerkleTree {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("missing file argument");
System.exit(1);
}
try (InputStream in = new BufferedInputStream(new FileInputStream(args[0]))) {
byte[] digest = sha256MerkleTree(in, 1024);
if (digest != null)
System.out.println(digestToString(digest));
} catch (Exception e) {
e.printStackTrace();
}
}
private static String digestToString(byte[] digest) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < digest.length; ++i)
result.append(String.format("%02x", digest[i]));
return result.toString();
}
private static byte[] sha256MerkleTree(InputStream in, int blockSize) throws Exception {
byte[] buffer = new byte[blockSize];
int bytes;
MessageDigest md = MessageDigest.getInstance("SHA-256");
List<byte[]> digests = new ArrayList<>();
while ((bytes = in.read(buffer)) > 0) {
md.reset();
md.update(buffer, 0, bytes);
digests.add(md.digest());
}
int length = digests.size();
if (length == 0)
return null;
while (length > 1) {
int j = 0;
for (int i = 0; i < length; i += 2, ++j) {
byte[] digest1 = digests.get(i);
if (i + 1 < length) {
byte[] digest2 = digests.get(i + 1);
md.reset();
md.update(digest1);
md.update(digest2);
digests.set(j, md.digest());
} else {
digests.set(j, digest1);
}
}
length = j;
}
return digests.get(0);
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | s = "alphaBETA"
print s.upper()
print s.lower()
print s.swapcase()
print "fOo bAR".capitalize()
print "fOo bAR".title()
import string
print string.capwords("fOo bAR")
| String str = "alphaBETA";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
System.out.println("äàâáçñßæεбế".toUpperCase());
System.out.println("ÄÀÂÁÇÑSSÆΕБẾ".toLowerCase());
|
Convert this Python block to Java, preserving its control flow and logic. | from javax.swing import JOptionPane
def to_int(n, default=0):
try:
return int(n)
except ValueError:
return default
number = to_int(JOptionPane.showInputDialog ("Enter an Integer"))
println(number)
a_string = JOptionPane.showInputDialog ("Enter a String")
println(a_string)
| import javax.swing.*;
public class GetInputSwing {
public static void main(String[] args) throws Exception {
int number = Integer.parseInt(
JOptionPane.showInputDialog ("Enter an Integer"));
String string = JOptionPane.showInputDialog ("Enter a String");
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | t = { 'x': 20, 'y': 30, 'a': 60 }
def setup():
size(450, 400)
background(0, 0, 200)
stroke(-1)
sc(7, 400, -60)
def sc(o, l, a, s = t, X = 'x', Y = 'y', A = 'a', HALF = .5):
if o:
o -= 1
l *= HALF
sc(o, l, -a)[A] += a
sc(o, l, a)[A] += a
sc(o, l, -a)
else:
x, y = s[X], s[Y]
s[X] += cos(radians(s[A])) * l
s[Y] += sin(radians(s[A])) * l
line(x, y, s[X], s[Y])
return s
| final PVector t = new PVector(20, 30, 60);
void setup() {
size(450, 400);
noLoop();
background(0, 0, 200);
stroke(-1);
sc(7, 400, -60, t);
}
PVector sc(int o, float l, final int a, final PVector s) {
if (o > 0) {
sc(--o, l *= .5, -a, s).z += a;
sc(o, l, a, s).z += a;
sc(o, l, -a, s);
} else line(s.x, s.y,
s.x += cos(radians(s.z)) * l,
s.y += sin(radians(s.z)) * l);
return s;
}
|
Please provide an equivalent version of this Python code in Java. | import fileinput
import sys
nodata = 0;
nodata_max=-1;
nodata_maxline=[];
tot_file = 0
num_file = 0
infiles = sys.argv[1:]
for line in fileinput.input():
tot_line=0;
num_line=0;
field = line.split()
date = field[0]
data = [float(f) for f in field[1::2]]
flags = [int(f) for f in field[2::2]]
for datum, flag in zip(data, flags):
if flag<1:
nodata += 1
else:
if nodata_max==nodata and nodata>0:
nodata_maxline.append(date)
if nodata_max<nodata and nodata>0:
nodata_max=nodata
nodata_maxline=[date]
nodata=0;
tot_line += datum
num_line += 1
tot_file += tot_line
num_file += num_line
print "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f" % (
date,
len(data) -num_line,
num_line, tot_line,
tot_line/num_line if (num_line>0) else 0)
print ""
print "File(s) = %s" % (", ".join(infiles),)
print "Total = %10.3f" % (tot_file,)
print "Readings = %6i" % (num_file,)
print "Average = %10.3f" % (tot_file / num_file,)
print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % (
nodata_max, ", ".join(nodata_maxline))
| import java.io.File;
import java.util.*;
import static java.lang.System.out;
public class TextProcessing1 {
public static void main(String[] args) throws Exception {
Locale.setDefault(new Locale("en", "US"));
Metrics metrics = new Metrics();
int dataGap = 0;
String gapBeginDate = null;
try (Scanner lines = new Scanner(new File("readings.txt"))) {
while (lines.hasNextLine()) {
double lineTotal = 0.0;
int linePairs = 0;
int lineInvalid = 0;
String lineDate;
try (Scanner line = new Scanner(lines.nextLine())) {
lineDate = line.next();
while (line.hasNext()) {
final double value = line.nextDouble();
if (line.nextInt() <= 0) {
if (dataGap == 0)
gapBeginDate = lineDate;
dataGap++;
lineInvalid++;
continue;
}
lineTotal += value;
linePairs++;
metrics.addDataGap(dataGap, gapBeginDate, lineDate);
dataGap = 0;
}
}
metrics.addLine(lineTotal, linePairs);
metrics.lineResult(lineDate, lineInvalid, linePairs, lineTotal);
}
metrics.report();
}
}
private static class Metrics {
private List<String[]> gapDates;
private int maxDataGap = -1;
private double total;
private int pairs;
private int lineResultCount;
void addLine(double tot, double prs) {
total += tot;
pairs += prs;
}
void addDataGap(int gap, String begin, String end) {
if (gap > 0 && gap >= maxDataGap) {
if (gap > maxDataGap) {
maxDataGap = gap;
gapDates = new ArrayList<>();
}
gapDates.add(new String[]{begin, end});
}
}
void lineResult(String date, int invalid, int prs, double tot) {
if (lineResultCount >= 3)
return;
out.printf("%10s out: %2d in: %2d tot: %10.3f avg: %10.3f%n",
date, invalid, prs, tot, (prs > 0) ? tot / prs : 0.0);
lineResultCount++;
}
void report() {
out.printf("%ntotal = %10.3f%n", total);
out.printf("readings = %6d%n", pairs);
out.printf("average = %010.3f%n", total / pairs);
out.printf("%nmaximum run(s) of %d invalid measurements: %n",
maxDataGap);
for (String[] dates : gapDates)
out.printf("begins at %s and ends at %s%n", dates[0], dates[1]);
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | >>> import hashlib
>>>
>>> tests = (
(b"", 'd41d8cd98f00b204e9800998ecf8427e'),
(b"a", '0cc175b9c0f1b6a831c399e269772661'),
(b"abc", '900150983cd24fb0d6963f7d28e17f72'),
(b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'),
(b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'),
(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'),
(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden
>>>
| import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Digester {
public static void main(String[] args) {
System.out.println(hexDigest("Rosetta code", "MD5"));
}
static String hexDigest(String str, String digestName) {
try {
MessageDigest md = MessageDigest.getInstance(digestName);
byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));
char[] hex = new char[digest.length * 2];
for (int i = 0; i < digest.length; i++) {
hex[2 * i] = "0123456789abcdef".charAt((digest[i] & 0xf0) >> 4);
hex[2 * i + 1] = "0123456789abcdef".charAt(digest[i] & 0x0f);
}
return new String(hex);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pdsum(s[-1])
if new in s:
if s[0] == new:
if slen == 1:
return 'perfect', s
elif slen == 2:
return 'amicable', s
else:
return 'sociable of length %i' % slen, s
elif s[-1] == new:
return 'aspiring', s
else:
return 'cyclic back to %i' % new, s
elif new == 0:
return 'terminating', s + [0]
else:
s.append(new)
slen += 1
else:
return 'non-terminating', s
if __name__ == '__main__':
for n in range(1, 11):
print('%s: %r' % aliquot(n))
print()
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
print('%s: %r' % aliquot(n))
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.LongStream;
public class AliquotSequenceClassifications {
private static Long properDivsSum(long n) {
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();
}
static boolean aliquot(long n, int maxLen, long maxTerm) {
List<Long> s = new ArrayList<>(maxLen);
s.add(n);
long newN = n;
while (s.size() <= maxLen && newN < maxTerm) {
newN = properDivsSum(s.get(s.size() - 1));
if (s.contains(newN)) {
if (s.get(0) == newN) {
switch (s.size()) {
case 1:
return report("Perfect", s);
case 2:
return report("Amicable", s);
default:
return report("Sociable of length " + s.size(), s);
}
} else if (s.get(s.size() - 1) == newN) {
return report("Aspiring", s);
} else
return report("Cyclic back to " + newN, s);
} else {
s.add(newN);
if (newN == 0)
return report("Terminating", s);
}
}
return report("Non-terminating", s);
}
static boolean report(String msg, List<Long> result) {
System.out.println(msg + ": " + result);
return false;
}
public static void main(String[] args) {
long[] arr = {
11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488};
LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));
System.out.println();
Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));
}
}
|
Write the same code in Java as shown below in Python. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pdsum(s[-1])
if new in s:
if s[0] == new:
if slen == 1:
return 'perfect', s
elif slen == 2:
return 'amicable', s
else:
return 'sociable of length %i' % slen, s
elif s[-1] == new:
return 'aspiring', s
else:
return 'cyclic back to %i' % new, s
elif new == 0:
return 'terminating', s + [0]
else:
s.append(new)
slen += 1
else:
return 'non-terminating', s
if __name__ == '__main__':
for n in range(1, 11):
print('%s: %r' % aliquot(n))
print()
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
print('%s: %r' % aliquot(n))
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.LongStream;
public class AliquotSequenceClassifications {
private static Long properDivsSum(long n) {
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum();
}
static boolean aliquot(long n, int maxLen, long maxTerm) {
List<Long> s = new ArrayList<>(maxLen);
s.add(n);
long newN = n;
while (s.size() <= maxLen && newN < maxTerm) {
newN = properDivsSum(s.get(s.size() - 1));
if (s.contains(newN)) {
if (s.get(0) == newN) {
switch (s.size()) {
case 1:
return report("Perfect", s);
case 2:
return report("Amicable", s);
default:
return report("Sociable of length " + s.size(), s);
}
} else if (s.get(s.size() - 1) == newN) {
return report("Aspiring", s);
} else
return report("Cyclic back to " + newN, s);
} else {
s.add(newN);
if (newN == 0)
return report("Terminating", s);
}
}
return report("Non-terminating", s);
}
static boolean report(String msg, List<Long> result) {
System.out.println(msg + ": " + result);
return false;
}
public static void main(String[] args) {
long[] arr = {
11, 12, 28, 496, 220, 1184, 12496, 1264460,
790, 909, 562, 1064, 1488};
LongStream.rangeClosed(1, 10).forEach(n -> aliquot(n, 16, 1L << 47));
System.out.println();
Arrays.stream(arr).forEach(n -> aliquot(n, 16, 1L << 47));
}
}
|
Rewrite the snippet below in Java so it works the same as the original Python code. | import datetime
def mt():
datime1="March 7 2009 7:30pm EST"
formatting = "%B %d %Y %I:%M%p "
datime2 = datime1[:-3]
tdelta = datetime.timedelta(hours=12)
s3 = datetime.datetime.strptime(datime2, formatting)
datime2 = s3+tdelta
print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]
mt()
| import java.time.*;
import java.time.format.*;
class Main {
public static void main(String args[]) {
String dateStr = "March 7 2009 7:30pm EST";
DateTimeFormatter df = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MMMM d yyyy h:mma zzz")
.toFormatter();
ZonedDateTime after12Hours = ZonedDateTime.parse(dateStr, df).plusHours(12);
System.out.println("Date: " + dateStr);
System.out.println("+12h: " + after12Hours.format(df));
ZonedDateTime after12HoursInCentralEuropeTime = after12Hours.withZoneSameInstant(ZoneId.of("CET"));
System.out.println("+12h (in Central Europe): " + after12HoursInCentralEuropeTime.format(df));
}
}
|
Write the same algorithm in Java as shown in this Python implementation. | from time import sleep
from threading import Timer
def sleepsort(values):
sleepsort.result = []
def add1(x):
sleepsort.result.append(x)
mx = values[0]
for v in values:
if mx < v: mx = v
Timer(v, add1, [v]).start()
sleep(mx+1)
return sleepsort.result
if __name__ == '__main__':
x = [3,2,4,7,3,6,9,1]
if sleepsort(x) == sorted(x):
print('sleep sort worked for:',x)
else:
print('sleep sort FAILED for:',x)
| import java.util.concurrent.CountDownLatch;
public class SleepSort {
public static void sleepSortAndPrint(int[] nums) {
final CountDownLatch doneSignal = new CountDownLatch(nums.length);
for (final int num : nums) {
new Thread(new Runnable() {
public void run() {
doneSignal.countDown();
try {
doneSignal.await();
Thread.sleep(num * 1000);
System.out.println(num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
public static void main(String[] args) {
int[] nums = new int[args.length];
for (int i = 0; i < args.length; i++)
nums[i] = Integer.parseInt(args[i]);
sleepSortAndPrint(nums);
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | from random import randint
def do_scan(mat):
for row in mat:
for item in row:
print item,
if item == 20:
print
return
print
print
mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)
| import java.util.Random;
public class NestedLoopTest {
public static final Random gen = new Random();
public static void main(String[] args) {
int[][] a = new int[10][10];
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[i].length; j++)
a[i][j] = gen.nextInt(20) + 1;
Outer:for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(" " + a[i][j]);
if (a[i][j] == 20)
break Outer;
}
System.out.println();
}
System.out.println();
}
}
|
Port the provided Python code into Java while preserving the original functionality. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| import java.math.BigInteger;
import static java.math.BigInteger.ONE;
public class PythTrip{
public static void main(String[] args){
long tripCount = 0, primCount = 0;
BigInteger periLimit = BigInteger.valueOf(100),
peri2 = periLimit.divide(BigInteger.valueOf(2)),
peri3 = periLimit.divide(BigInteger.valueOf(3));
for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){
BigInteger aa = a.multiply(a);
for(BigInteger b = a.add(ONE);
b.compareTo(peri2) < 0; b = b.add(ONE)){
BigInteger bb = b.multiply(b);
BigInteger ab = a.add(b);
BigInteger aabb = aa.add(bb);
for(BigInteger c = b.add(ONE);
c.compareTo(peri2) < 0; c = c.add(ONE)){
int compare = aabb.compareTo(c.multiply(c));
if(ab.add(c).compareTo(periLimit) > 0){
break;
}
if(compare < 0){
break;
}else if (compare == 0){
tripCount++;
System.out.print(a + ", " + b + ", " + c);
if(a.gcd(b).equals(ONE)){
System.out.print(" primitive");
primCount++;
}
System.out.println();
}
}
}
}
System.out.println("Up to a perimeter of " + periLimit + ", there are "
+ tripCount + " triples, of which " + primCount + " are primitive.");
}
}
|
Translate this program into Java but keep the logic exactly as in Python. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| import java.math.BigInteger;
import static java.math.BigInteger.ONE;
public class PythTrip{
public static void main(String[] args){
long tripCount = 0, primCount = 0;
BigInteger periLimit = BigInteger.valueOf(100),
peri2 = periLimit.divide(BigInteger.valueOf(2)),
peri3 = periLimit.divide(BigInteger.valueOf(3));
for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){
BigInteger aa = a.multiply(a);
for(BigInteger b = a.add(ONE);
b.compareTo(peri2) < 0; b = b.add(ONE)){
BigInteger bb = b.multiply(b);
BigInteger ab = a.add(b);
BigInteger aabb = aa.add(bb);
for(BigInteger c = b.add(ONE);
c.compareTo(peri2) < 0; c = c.add(ONE)){
int compare = aabb.compareTo(c.multiply(c));
if(ab.add(c).compareTo(periLimit) > 0){
break;
}
if(compare < 0){
break;
}else if (compare == 0){
tripCount++;
System.out.print(a + ", " + b + ", " + c);
if(a.gcd(b).equals(ONE)){
System.out.print(" primitive");
primCount++;
}
System.out.println();
}
}
}
}
System.out.println("Up to a perimeter of " + periLimit + ", there are "
+ tripCount + " triples, of which " + primCount + " are primitive.");
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
| module RetainUniqueValues
{
@Inject Console console;
void run()
{
Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];
array = array.distinct().toArray();
console.print($"result={array}");
}
}
|
Port the following code from Python to Java with equivalent syntax and logic. | items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
| module RetainUniqueValues
{
@Inject Console console;
void run()
{
Int[] array = [1, 2, 3, 2, 1, 2, 3, 4, 5, 3, 2, 1];
array = array.distinct().toArray();
console.print($"result={array}");
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
| public static String lookandsay(String number){
StringBuilder result= new StringBuilder();
char repeat= number.charAt(0);
number= number.substring(1) + " ";
int times= 1;
for(char actual: number.toCharArray()){
if(actual != repeat){
result.append(times + "" + repeat);
times= 1;
repeat= actual;
}else{
times+= 1;
}
}
return result.toString();
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | from collections import deque
stack = deque()
stack.append(value)
value = stack.pop()
not stack
| import java.util.Stack;
public class StackTest {
public static void main( final String[] args ) {
final Stack<String> stack = new Stack<String>();
System.out.println( "New stack empty? " + stack.empty() );
stack.push( "There can be only one" );
System.out.println( "Pushed stack empty? " + stack.empty() );
System.out.println( "Popped single entry: " + stack.pop() );
stack.push( "First" );
stack.push( "Second" );
System.out.println( "Popped entry should be second: " + stack.pop() );
stack.pop();
stack.pop();
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | from math import gcd
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return φ(n) == n - 1
for n in range(1, 26):
print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}")
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f"Primes up to {n}: {count}")
| public class TotientFunction {
public static void main(String[] args) {
computePhi();
System.out.println("Compute and display phi for the first 25 integers.");
System.out.printf("n Phi IsPrime%n");
for ( int n = 1 ; n <= 25 ; n++ ) {
System.out.printf("%2d %2d %b%n", n, phi[n], (phi[n] == n-1));
}
for ( int i = 2 ; i < 8 ; i++ ) {
int max = (int) Math.pow(10, i);
System.out.printf("The count of the primes up to %,10d = %d%n", max, countPrimes(1, max));
}
}
private static int countPrimes(int min, int max) {
int count = 0;
for ( int i = min ; i <= max ; i++ ) {
if ( phi[i] == i-1 ) {
count++;
}
}
return count;
}
private static final int max = 10000000;
private static final int[] phi = new int[max+1];
private static final void computePhi() {
for ( int i = 1 ; i <= max ; i++ ) {
phi[i] = i;
}
for ( int i = 2 ; i <= max ; i++ ) {
if (phi[i] < i) continue;
for ( int j = i ; j <= max ; j += i ) {
phi[j] -= phi[j] / i;
}
}
}
}
|
Convert this Python block to Java, preserving its control flow and logic. | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
| if (s == 'Hello World') {
foo();
} else if (s == 'Bye World') {
bar();
} else {
deusEx();
}
|
Write the same code in Java as shown below in Python. | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
| if (s == 'Hello World') {
foo();
} else if (s == 'Bye World') {
bar();
} else {
deusEx();
}
|
Change the following Python code into Java without altering its purpose. | from fractions import Fraction
def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
'77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
'13 / 11, 15 / 14, 15 / 2, 55 / 1'):
flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]
n = Fraction(n)
while True:
yield n.numerator
for f in flist:
if (n * f).denominator == 1:
break
else:
break
n *= f
if __name__ == '__main__':
n, m = 2, 15
print('First %i members of fractran(%i):\n ' % (m, n) +
', '.join(str(f) for f,i in zip(fractran(n), range(m))))
| import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Fractran{
public static void main(String []args){
new Fractran("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2);
}
final int limit = 15;
Vector<Integer> num = new Vector<>();
Vector<Integer> den = new Vector<>();
public Fractran(String prog, Integer val){
compile(prog);
dump();
exec(2);
}
void compile(String prog){
Pattern regexp = Pattern.compile("\\s*(\\d*)\\s*\\/\\s*(\\d*)\\s*(.*)");
Matcher matcher = regexp.matcher(prog);
while(matcher.find()){
num.add(Integer.parseInt(matcher.group(1)));
den.add(Integer.parseInt(matcher.group(2)));
matcher = regexp.matcher(matcher.group(3));
}
}
void exec(Integer val){
int n = 0;
while(val != null && n<limit){
System.out.println(n+": "+val);
val = step(val);
n++;
}
}
Integer step(int val){
int i=0;
while(i<den.size() && val%den.get(i) != 0) i++;
if(i<den.size())
return num.get(i)*val/den.get(i);
return null;
}
void dump(){
for(int i=0; i<den.size(); i++)
System.out.print(num.get(i)+"/"+den.get(i)+" ");
System.out.println();
}
}
|
Transform the following Python implementation into Java, maintaining the same output and logic. | >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
if j is None:
j = len(L) - 1
if L[j] < L[i]:
L[i], L[j] = L[j], L[i]
if j - i > 1:
t = (j - i + 1) // 3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
| import java.util.Arrays;
public class Stooge {
public static void main(String[] args) {
int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};
stoogeSort(nums);
System.out.println(Arrays.toString(nums));
}
public static void stoogeSort(int[] L) {
stoogeSort(L, 0, L.length - 1);
}
public static void stoogeSort(int[] L, int i, int j) {
if (L[j] < L[i]) {
int tmp = L[i];
L[i] = L[j];
L[j] = tmp;
}
if (j - i > 1) {
int t = (j - i + 1) / 3;
stoogeSort(L, i, j - t);
stoogeSort(L, i + t, j);
stoogeSort(L, i, j - t);
}
}
}
|
Please provide an equivalent version of this Python code in Java. | >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7]
>>> def stoogesort(L, i=0, j=None):
if j is None:
j = len(L) - 1
if L[j] < L[i]:
L[i], L[j] = L[j], L[i]
if j - i > 1:
t = (j - i + 1) // 3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
>>> stoogesort(data)
[-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
| import java.util.Arrays;
public class Stooge {
public static void main(String[] args) {
int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5};
stoogeSort(nums);
System.out.println(Arrays.toString(nums));
}
public static void stoogeSort(int[] L) {
stoogeSort(L, 0, L.length - 1);
}
public static void stoogeSort(int[] L, int i, int j) {
if (L[j] < L[i]) {
int tmp = L[i];
L[i] = L[j];
L[j] = tmp;
}
if (j - i > 1) {
int t = (j - i + 1) / 3;
stoogeSort(L, i, j - t);
stoogeSort(L, i + t, j);
stoogeSort(L, i, j - t);
}
}
}
|
Convert this Python block to Java, preserving its control flow and logic. |
import sys, os
import random
import time
def print_there(x, y, text):
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush()
class Ball():
def __init__(self):
self.x = 0
self.y = 0
def update(self):
self.x += random.randint(0,1)
self.y += 1
def fall(self):
self.y +=1
class Board():
def __init__(self, width, well_depth, N):
self.balls = []
self.fallen = [0] * (width + 1)
self.width = width
self.well_depth = well_depth
self.N = N
self.shift = 4
def update(self):
for ball in self.balls:
if ball.y < self.width:
ball.update()
elif ball.y < self.width + self.well_depth - self.fallen[ball.x]:
ball.fall()
elif ball.y == self.width + self.well_depth - self.fallen[ball.x]:
self.fallen[ball.x] += 1
else:
pass
def balls_on_board(self):
return len(self.balls) - sum(self.fallen)
def add_ball(self):
if(len(self.balls) <= self.N):
self.balls.append(Ball())
def print_board(self):
for y in range(self.width + 1):
for x in range(y):
print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, "
def print_ball(self, ball):
if ball.y <= self.width:
x = self.width - ball.y + 2*ball.x + self.shift
else:
x = 2*ball.x + self.shift
y = ball.y + 1
print_there(y, x, "*")
def print_all(self):
print(chr(27) + "[2J")
self.print_board();
for ball in self.balls:
self.print_ball(ball)
def main():
board = Board(width = 15, well_depth = 5, N = 10)
board.add_ball()
while(board.balls_on_board() > 0):
board.print_all()
time.sleep(0.25)
board.update()
board.print_all()
time.sleep(0.25)
board.update()
board.add_ball()
if __name__=="__main__":
main()
| import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class GaltonBox {
public static void main( final String[] args ) {
new GaltonBox( 8, 200 ).run();
}
private final int m_pinRows;
private final int m_startRow;
private final Position[] m_balls;
private final Random m_random = new Random();
public GaltonBox( final int pinRows, final int ballCount ) {
m_pinRows = pinRows;
m_startRow = pinRows + 1;
m_balls = new Position[ ballCount ];
for ( int ball = 0; ball < ballCount; ball++ )
m_balls[ ball ] = new Position( m_startRow, 0, 'o' );
}
private static class Position {
int m_row;
int m_col;
char m_char;
Position( final int row, final int col, final char ch ) {
m_row = row;
m_col = col;
m_char = ch;
}
}
public void run() {
for ( int ballsInPlay = m_balls.length; ballsInPlay > 0; ) {
ballsInPlay = dropBalls();
print();
}
}
private int dropBalls() {
int ballsInPlay = 0;
int ballToStart = -1;
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == m_startRow )
ballToStart = ball;
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( ball == ballToStart ) {
m_balls[ ball ].m_row = m_pinRows;
ballsInPlay++;
}
else if ( m_balls[ ball ].m_row > 0 && m_balls[ ball ].m_row != m_startRow ) {
m_balls[ ball ].m_row -= 1;
m_balls[ ball ].m_col += m_random.nextInt( 2 );
if ( 0 != m_balls[ ball ].m_row )
ballsInPlay++;
}
return ballsInPlay;
}
private void print() {
for ( int row = m_startRow; row --> 1; ) {
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == row )
printBall( m_balls[ ball ] );
System.out.println();
printPins( row );
}
printCollectors();
System.out.println();
}
private static void printBall( final Position pos ) {
for ( int col = pos.m_row + 1; col --> 0; )
System.out.print( ' ' );
for ( int col = 0; col < pos.m_col; col++ )
System.out.print( " " );
System.out.print( pos.m_char );
}
private void printPins( final int row ) {
for ( int col = row + 1; col --> 0; )
System.out.print( ' ' );
for ( int col = m_startRow - row; col --> 0; )
System.out.print( ". " );
System.out.println();
}
private void printCollectors() {
final List<List<Position>> collectors = new ArrayList<List<Position>>();
for ( int col = 0; col < m_startRow; col++ ) {
final List<Position> collector = new ArrayList<Position>();
collectors.add( collector );
for ( int ball = 0; ball < m_balls.length; ball++ )
if ( m_balls[ ball ].m_row == 0 && m_balls[ ball ].m_col == col )
collector.add( m_balls[ ball ] );
}
for ( int row = 0, rows = longest( collectors ); row < rows; row++ ) {
for ( int col = 0; col < m_startRow; col++ ) {
final List<Position> collector = collectors.get( col );
final int pos = row + collector.size() - rows;
System.out.print( '|' );
if ( pos >= 0 )
System.out.print( collector.get( pos ).m_char );
else
System.out.print( ' ' );
}
System.out.println( '|' );
}
}
private static final int longest( final List<List<Position>> collectors ) {
int result = 0;
for ( final List<Position> collector : collectors )
result = Math.max( collector.size(), result );
return result;
}
}
|
Change the programming language of this snippet from Python to Java without modifying what it does. |
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':
n = R-L
if n < 2:
return 0
swaps = 0
m = n//2
for i in range(m):
if A[R-(i+1)] < A[L+i]:
(A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
swaps += 1
if (n & 1) and (A[L+m] < A[L+m-1]):
(A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)
swaps += 1
return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)
def circle_sort(L:list)->'sort A in place, returning the number of swaps':
swaps = 0
s = 1
while s:
s = circle_sort_backend(L, 0, len(L))
swaps += s
return swaps
if __name__ == '__main__':
from random import shuffle
for i in range(309):
L = list(range(i))
M = L[:]
shuffle(L)
N = L[:]
circle_sort(L)
if L != M:
print(len(L))
print(N)
print(L)
| import java.util.Arrays;
public class CircleSort {
public static void main(String[] args) {
circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1});
}
public static void circleSort(int[] arr) {
if (arr.length > 0)
do {
System.out.println(Arrays.toString(arr));
} while (circleSortR(arr, 0, arr.length - 1, 0) != 0);
}
private static int circleSortR(int[] arr, int lo, int hi, int numSwaps) {
if (lo == hi)
return numSwaps;
int high = hi;
int low = lo;
int mid = (hi - lo) / 2;
while (lo < hi) {
if (arr[lo] > arr[hi]) {
swap(arr, lo, hi);
numSwaps++;
}
lo++;
hi--;
}
if (lo == hi && arr[lo] > arr[hi + 1]) {
swap(arr, lo, hi + 1);
numSwaps++;
}
numSwaps = circleSortR(arr, low, low + mid, numSwaps);
numSwaps = circleSortR(arr, low + mid + 1, high, numSwaps);
return numSwaps;
}
private static void swap(int[] arr, int idx1, int idx2) {
int tmp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = tmp;
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | import os
from PIL import Image
def imgsave(path, arr):
w, h = len(arr), len(arr[0])
img = Image.new('1', (w, h))
for x in range(w):
for y in range(h):
img.putpixel((x, y), arr[x][y])
img.save(path)
def get_shape(mat):
return len(mat), len(mat[0])
def kron(matrix1, matrix2):
final_list = []
count = len(matrix2)
for elem1 in matrix1:
for i in range(count):
sub_list = []
for num1 in elem1:
for num2 in matrix2[i]:
sub_list.append(num1 * num2)
final_list.append(sub_list)
return final_list
def kronpow(mat):
matrix = mat
while True:
yield matrix
matrix = kron(mat, matrix)
def fractal(name, mat, order=6):
path = os.path.join('fractals', name)
os.makedirs(path, exist_ok=True)
fgen = kronpow(mat)
print(name)
for i in range(order):
p = os.path.join(path, f'{i}.jpg')
print('Calculating n =', i, end='\t', flush=True)
mat = next(fgen)
imgsave(p, mat)
x, y = get_shape(mat)
print('Saved as', x, 'x', y, 'image', p)
test1 = [
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
]
test2 = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
test3 = [
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
]
fractal('test1', test1)
fractal('test2', test2)
fractal('test3', test3)
| package kronecker;
public class ProductFractals {
public static int[][] product(final int[][] a, final int[][] b) {
final int[][] c = new int[a.length*b.length][];
for (int ix = 0; ix < c.length; ix++) {
final int num_cols = a[0].length*b[0].length;
c[ix] = new int[num_cols];
}
for (int ia = 0; ia < a.length; ia++) {
for (int ja = 0; ja < a[ia].length; ja++) {
for (int ib = 0; ib < b.length; ib++) {
for (int jb = 0; jb < b[ib].length; jb++) {
c[b.length*ia+ib][b[ib].length*ja+jb] = a[ia][ja] * b[ib][jb];
}
}
}
}
return c;
}
public static void show_matrix(final int[][] m, final char nz, final char z) {
for (int im = 0; im < m.length; im++) {
for (int jm = 0; jm < m[im].length; jm++) {
System.out.print(m[im][jm] == 0 ? z : nz);
}
System.out.println();
}
}
public static int[][] power(final int[][] m, final int n) {
int[][] m_pow = m;
for (int ix = 1; ix < n; ix++) {
m_pow = product(m, m_pow);
}
return m_pow;
}
private static void test(final int[][] m, final int n) {
System.out.println("Test matrix");
show_matrix(m, '*', ' ');
final int[][] m_pow = power(m, n);
System.out.println("Matrix power " + n);
show_matrix(m_pow, '*', ' ');
}
private static void test1() {
final int[][] m = {{0, 1, 0},
{1, 1, 1},
{0, 1, 0}};
test(m, 4);
}
private static void test2() {
final int[][] m = {{1, 1, 1},
{1, 0, 1},
{1, 1, 1}};
test(m, 4);
}
private static void test3() {
final int[][] m = {{1, 0, 1},
{1, 0, 1},
{0, 1, 0}};
test(m, 4);
}
public static void main(final String[] args) {
test1();
test2();
test3();
}
}
|
Keep all operations the same but rewrite the snippet in Java. | def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
if len(line.split()) != 1: continue
boolval = False
bits = line.split(None, 1)
if len(bits) == 1:
k = bits[0]
v = boolval
else:
k, v = bits
ret[k.lower()] = v
return ret
if __name__ == '__main__':
import sys
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConfigReader {
private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" );
private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>() {{
put( "needspeeling", false );
put( "seedsremoved", false );
}};
public static void main( final String[] args ) {
System.out.println( parseFile( args[ 0 ] ) );
}
public static Map<String, Object> parseFile( final String fileName ) {
final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS );
BufferedReader reader = null;
try {
reader = new BufferedReader( new FileReader( fileName ) );
for ( String line; null != ( line = reader.readLine() ); ) {
parseLine( line, result );
}
} catch ( final IOException x ) {
throw new RuntimeException( "Oops: " + x, x );
} finally {
if ( null != reader ) try {
reader.close();
} catch ( final IOException x2 ) {
System.err.println( "Could not close " + fileName + " - " + x2 );
}
}
return result;
}
private static void parseLine( final String line, final Map<String, Object> map ) {
if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) )
return;
final Matcher matcher = LINE_PATTERN.matcher( line );
if ( ! matcher.matches() ) {
System.err.println( "Bad config line: " + line );
return;
}
final String key = matcher.group( 1 ).trim().toLowerCase();
final String value = matcher.group( 2 ).trim();
if ( "".equals( value ) ) {
map.put( key, true );
} else if ( -1 == value.indexOf( ',' ) ) {
map.put( key, value );
} else {
final String[] values = value.split( "," );
for ( int i = 0; i < values.length; i++ ) {
values[ i ] = values[ i ].trim();
}
map.put( key, Arrays.asList( values ) );
}
}
}
|
Please provide an equivalent version of this Python code in Java. | strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
| import java.util.Comparator;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};
Arrays.sort(strings, new Comparator<String>() {
public int compare(String s1, String s2) {
int c = s2.length() - s1.length();
if (c == 0)
c = s1.compareToIgnoreCase(s2);
return c;
}
});
for (String s: strings)
System.out.print(s + " ");
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
| import java.util.Comparator;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};
Arrays.sort(strings, new Comparator<String>() {
public int compare(String s1, String s2) {
int c = s2.length() - s1.length();
if (c == 0)
c = s1.compareToIgnoreCase(s2);
return c;
}
});
for (String s: strings)
System.out.print(s + " ");
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. | import random
def is_Prime(n):
if n!=int(n):
return False
n=int(n)
if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
return False
if n==2 or n==3 or n==5 or n==7:
return True
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(8):
a = random.randrange(2, n)
if trial_composite(a):
return False
return True
def isPrime(n: int) -> bool:
if (n <= 1) :
return False
if (n <= 3) :
return True
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
def rotations(n: int)-> set((int,)):
a = str(n)
return set(int(a[i:] + a[:i]) for i in range(len(a)))
def isCircular(n: int) -> bool:
return all(isPrime(int(o)) for o in rotations(n))
from itertools import product
def main():
result = [2, 3, 5, 7]
first = '137'
latter = '1379'
for i in range(1, 6):
s = set(int(''.join(a)) for a in product(first, *((latter,) * i)))
while s:
a = s.pop()
b = rotations(a)
if isCircular(a):
result.append(min(b))
s -= b
result.sort()
return result
assert [2, 3, 5, 7, 11, 13, 17, 37, 79, 113, 197, 199, 337, 1193, 3779, 11939, 19937, 193939, 199933] == main()
repunit = lambda n: int('1' * n)
def repmain(n: int) -> list:
result = []
i = 2
while len(result) < n:
if is_Prime(repunit(i)):
result.append(i)
i += 1
return result
assert [2, 19, 23, 317, 1031] == repmain(5)
| import java.math.BigInteger;
import java.util.Arrays;
public class CircularPrimes {
public static void main(String[] args) {
System.out.println("First 19 circular primes:");
int p = 2;
for (int count = 0; count < 19; ++p) {
if (isCircularPrime(p)) {
if (count > 0)
System.out.print(", ");
System.out.print(p);
++count;
}
}
System.out.println();
System.out.println("Next 4 circular primes:");
int repunit = 1, digits = 1;
for (; repunit < p; ++digits)
repunit = 10 * repunit + 1;
BigInteger bignum = BigInteger.valueOf(repunit);
for (int count = 0; count < 4; ) {
if (bignum.isProbablePrime(15)) {
if (count > 0)
System.out.print(", ");
System.out.printf("R(%d)", digits);
++count;
}
++digits;
bignum = bignum.multiply(BigInteger.TEN);
bignum = bignum.add(BigInteger.ONE);
}
System.out.println();
testRepunit(5003);
testRepunit(9887);
testRepunit(15073);
testRepunit(25031);
}
private static boolean isPrime(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;
if (n % p == 0)
return false;
}
return true;
}
private static int cycle(int n) {
int m = n, p = 1;
while (m >= 10) {
p *= 10;
m /= 10;
}
return m + 10 * (n % p);
}
private static boolean isCircularPrime(int p) {
if (!isPrime(p))
return false;
int p2 = cycle(p);
while (p2 != p) {
if (p2 < p || !isPrime(p2))
return false;
p2 = cycle(p2);
}
return true;
}
private static void testRepunit(int digits) {
BigInteger repunit = repunit(digits);
if (repunit.isProbablePrime(15))
System.out.printf("R(%d) is probably prime.\n", digits);
else
System.out.printf("R(%d) is not prime.\n", digits);
}
private static BigInteger repunit(int digits) {
char[] ch = new char[digits];
Arrays.fill(ch, '1');
return new BigInteger(new String(ch));
}
}
|
Generate an equivalent Java version of this Python code. | txt = "Hello, world! "
left = True
def draw():
global txt
background(128)
text(txt, 10, height / 2)
if frameCount % 10 == 0:
if (left):
txt = rotate(txt, 1)
else:
txt = rotate(txt, -1)
println(txt)
def mouseReleased():
global left
left = not left
def rotate(text, startIdx):
rotated = text[startIdx:] + text[:startIdx]
return rotated
| import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class Rotate {
private static class State {
private final String text = "Hello World! ";
private int startIndex = 0;
private boolean rotateRight = true;
}
public static void main(String[] args) {
State state = new State();
JLabel label = new JLabel(state.text);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
state.rotateRight = !state.rotateRight;
}
});
TimerTask task = new TimerTask() {
public void run() {
int delta = state.rotateRight ? 1 : -1;
state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();
label.setText(rotate(state.text, state.startIndex));
}
};
Timer timer = new Timer(false);
timer.schedule(task, 0, 500);
JFrame rot = new JFrame();
rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
rot.add(label);
rot.pack();
rot.setLocationRelativeTo(null);
rot.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
timer.cancel();
}
});
rot.setVisible(true);
}
private static String rotate(String text, int startIdx) {
char[] rotated = new char[text.length()];
for (int i = 0; i < text.length(); i++) {
rotated[i] = text.charAt((i + startIdx) % text.length());
}
return String.valueOf(rotated);
}
}
|
Convert this Python snippet to Java and keep its semantics consistent. |
from math import log
def getDigit(num, base, digit_num):
return (num // base ** digit_num) % base
def makeBlanks(size):
return [ [] for i in range(size) ]
def split(a_list, base, digit_num):
buckets = makeBlanks(base)
for num in a_list:
buckets[getDigit(num, base, digit_num)].append(num)
return buckets
def merge(a_list):
new_list = []
for sublist in a_list:
new_list.extend(sublist)
return new_list
def maxAbs(a_list):
return max(abs(num) for num in a_list)
def split_by_sign(a_list):
buckets = [[], []]
for num in a_list:
if num < 0:
buckets[0].append(num)
else:
buckets[1].append(num)
return buckets
def radixSort(a_list, base):
passes = int(round(log(maxAbs(a_list), base)) + 1)
new_list = list(a_list)
for digit_num in range(passes):
new_list = merge(split(new_list, base, digit_num))
return merge(split_by_sign(new_list))
| public static int[] sort(int[] old) {
for (int shift = Integer.SIZE - 1; shift > -1; shift--) {
int[] tmp = new int[old.length];
int j = 0;
for (int i = 0; i < old.length; i++) {
boolean move = old[i] << shift >= 0;
if (shift == 0 ? !move : move) {
tmp[j] = old[i];
j++;
} else {
old[i - j] = old[i];
}
}
for (int i = j; i < tmp.length; i++) {
tmp[i] = old[i - j];
}
old = tmp;
}
return old;
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. | [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
|
import java.util.Arrays;
import java.util.List;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public interface PythagComp{
static void main(String... args){
System.out.println(run(20));
}
static List<List<Integer>> run(int n){
return
range(1, n).mapToObj(
x -> range(x, n).mapToObj(
y -> range(y, n).mapToObj(
z -> new Integer[]{x, y, z}
)
)
)
.flatMap(identity())
.flatMap(identity())
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])
.map(Arrays::asList)
.collect(toList())
;
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
| public static void sort(int[] nums){
for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
int smallest = Integer.MAX_VALUE;
int smallestAt = currentPlace+1;
for(int check = currentPlace; check<nums.length;check++){
if(nums[check]<smallest){
smallestAt = check;
smallest = nums[check];
}
}
int temp = nums[currentPlace];
nums[currentPlace] = nums[smallestAt];
nums[smallestAt] = temp;
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | def jacobi(a, n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
if n % 2 == 0:
raise ValueError("'n' must be odd.")
a %= n
result = 1
while a != 0:
while a % 2 == 0:
a /= 2
n_mod_8 = n % 8
if n_mod_8 in (3, 5):
result = -result
a, n = n, a
if a % 4 == 3 and n % 4 == 3:
result = -result
a %= n
if n == 1:
return result
else:
return 0
| public class JacobiSymbol {
public static void main(String[] args) {
int max = 30;
System.out.printf("n\\k ");
for ( int k = 1 ; k <= max ; k++ ) {
System.out.printf("%2d ", k);
}
System.out.printf("%n");
for ( int n = 1 ; n <= max ; n += 2 ) {
System.out.printf("%2d ", n);
for ( int k = 1 ; k <= max ; k++ ) {
System.out.printf("%2d ", jacobiSymbol(k, n));
}
System.out.printf("%n");
}
}
private static int jacobiSymbol(int k, int n) {
if ( k < 0 || n % 2 == 0 ) {
throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n);
}
k %= n;
int jacobi = 1;
while ( k > 0 ) {
while ( k % 2 == 0 ) {
k /= 2;
int r = n % 8;
if ( r == 3 || r == 5 ) {
jacobi = -jacobi;
}
}
int temp = n;
n = k;
k = temp;
if ( k % 4 == 3 && n % 4 == 3 ) {
jacobi = -jacobi;
}
k %= n;
}
if ( n == 1 ) {
return jacobi;
}
return 0;
}
}
|
Can you help me rewrite this code in Java instead of Python, keeping it the same logically? | def jacobi(a, n):
if n <= 0:
raise ValueError("'n' must be a positive integer.")
if n % 2 == 0:
raise ValueError("'n' must be odd.")
a %= n
result = 1
while a != 0:
while a % 2 == 0:
a /= 2
n_mod_8 = n % 8
if n_mod_8 in (3, 5):
result = -result
a, n = n, a
if a % 4 == 3 and n % 4 == 3:
result = -result
a %= n
if n == 1:
return result
else:
return 0
| public class JacobiSymbol {
public static void main(String[] args) {
int max = 30;
System.out.printf("n\\k ");
for ( int k = 1 ; k <= max ; k++ ) {
System.out.printf("%2d ", k);
}
System.out.printf("%n");
for ( int n = 1 ; n <= max ; n += 2 ) {
System.out.printf("%2d ", n);
for ( int k = 1 ; k <= max ; k++ ) {
System.out.printf("%2d ", jacobiSymbol(k, n));
}
System.out.printf("%n");
}
}
private static int jacobiSymbol(int k, int n) {
if ( k < 0 || n % 2 == 0 ) {
throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n);
}
k %= n;
int jacobi = 1;
while ( k > 0 ) {
while ( k % 2 == 0 ) {
k /= 2;
int r = n % 8;
if ( r == 3 || r == 5 ) {
jacobi = -jacobi;
}
}
int temp = n;
n = k;
k = temp;
if ( k % 4 == 3 && n % 4 == 3 ) {
jacobi = -jacobi;
}
k %= n;
}
if ( n == 1 ) {
return jacobi;
}
return 0;
}
}
|
Convert the following code from Python to Java, ensuring the logic remains intact. | from random import seed, random
from time import time
from operator import itemgetter
from collections import namedtuple
from math import sqrt
from copy import deepcopy
def sqd(p1, p2):
return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))
class KdNode(object):
__slots__ = ("dom_elt", "split", "left", "right")
def __init__(self, dom_elt, split, left, right):
self.dom_elt = dom_elt
self.split = split
self.left = left
self.right = right
class Orthotope(object):
__slots__ = ("min", "max")
def __init__(self, mi, ma):
self.min, self.max = mi, ma
class KdTree(object):
__slots__ = ("n", "bounds")
def __init__(self, pts, bounds):
def nk2(split, exset):
if not exset:
return None
exset.sort(key=itemgetter(split))
m = len(exset) // 2
d = exset[m]
while m + 1 < len(exset) and exset[m + 1][split] == d[split]:
m += 1
d = exset[m]
s2 = (split + 1) % len(d)
return KdNode(d, split, nk2(s2, exset[:m]),
nk2(s2, exset[m + 1:]))
self.n = nk2(0, pts)
self.bounds = bounds
T3 = namedtuple("T3", "nearest dist_sqd nodes_visited")
def find_nearest(k, t, p):
def nn(kd, target, hr, max_dist_sqd):
if kd is None:
return T3([0.0] * k, float("inf"), 0)
nodes_visited = 1
s = kd.split
pivot = kd.dom_elt
left_hr = deepcopy(hr)
right_hr = deepcopy(hr)
left_hr.max[s] = pivot[s]
right_hr.min[s] = pivot[s]
if target[s] <= pivot[s]:
nearer_kd, nearer_hr = kd.left, left_hr
further_kd, further_hr = kd.right, right_hr
else:
nearer_kd, nearer_hr = kd.right, right_hr
further_kd, further_hr = kd.left, left_hr
n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)
nearest = n1.nearest
dist_sqd = n1.dist_sqd
nodes_visited += n1.nodes_visited
if dist_sqd < max_dist_sqd:
max_dist_sqd = dist_sqd
d = (pivot[s] - target[s]) ** 2
if d > max_dist_sqd:
return T3(nearest, dist_sqd, nodes_visited)
d = sqd(pivot, target)
if d < dist_sqd:
nearest = pivot
dist_sqd = d
max_dist_sqd = dist_sqd
n2 = nn(further_kd, target, further_hr, max_dist_sqd)
nodes_visited += n2.nodes_visited
if n2.dist_sqd < dist_sqd:
nearest = n2.nearest
dist_sqd = n2.dist_sqd
return T3(nearest, dist_sqd, nodes_visited)
return nn(t.n, p, t.bounds, float("inf"))
def show_nearest(k, heading, kd, p):
print(heading + ":")
print("Point: ", p)
n = find_nearest(k, kd, p)
print("Nearest neighbor:", n.nearest)
print("Distance: ", sqrt(n.dist_sqd))
print("Nodes visited: ", n.nodes_visited, "\n")
def random_point(k):
return [random() for _ in range(k)]
def random_points(k, n):
return [random_point(k) for _ in range(n)]
if __name__ == "__main__":
seed(1)
P = lambda *coords: list(coords)
kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],
Orthotope(P(0, 0), P(10, 10)))
show_nearest(2, "Wikipedia example data", kd1, P(9, 2))
N = 400000
t0 = time()
kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))
t1 = time()
text = lambda *parts: "".join(map(str, parts))
show_nearest(2, text("k-d tree with ", N,
" random 3D points (generation time: ",
t1-t0, "s)"),
kd2, random_point(3))
| import java.util.*;
public class KdTree {
private int dimensions_;
private Node root_ = null;
private Node best_ = null;
private double bestDistance_ = 0;
private int visited_ = 0;
public KdTree(int dimensions, List<Node> nodes) {
dimensions_ = dimensions;
root_ = makeTree(nodes, 0, nodes.size(), 0);
}
public Node findNearest(Node target) {
if (root_ == null)
throw new IllegalStateException("Tree is empty!");
best_ = null;
visited_ = 0;
bestDistance_ = 0;
nearest(root_, target, 0);
return best_;
}
public int visited() {
return visited_;
}
public double distance() {
return Math.sqrt(bestDistance_);
}
private void nearest(Node root, Node target, int index) {
if (root == null)
return;
++visited_;
double d = root.distance(target);
if (best_ == null || d < bestDistance_) {
bestDistance_ = d;
best_ = root;
}
if (bestDistance_ == 0)
return;
double dx = root.get(index) - target.get(index);
index = (index + 1) % dimensions_;
nearest(dx > 0 ? root.left_ : root.right_, target, index);
if (dx * dx >= bestDistance_)
return;
nearest(dx > 0 ? root.right_ : root.left_, target, index);
}
private Node makeTree(List<Node> nodes, int begin, int end, int index) {
if (end <= begin)
return null;
int n = begin + (end - begin)/2;
Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));
index = (index + 1) % dimensions_;
node.left_ = makeTree(nodes, begin, n, index);
node.right_ = makeTree(nodes, n + 1, end, index);
return node;
}
private static class NodeComparator implements Comparator<Node> {
private int index_;
private NodeComparator(int index) {
index_ = index;
}
public int compare(Node n1, Node n2) {
return Double.compare(n1.get(index_), n2.get(index_));
}
}
public static class Node {
private double[] coords_;
private Node left_ = null;
private Node right_ = null;
public Node(double[] coords) {
coords_ = coords;
}
public Node(double x, double y) {
this(new double[]{x, y});
}
public Node(double x, double y, double z) {
this(new double[]{x, y, z});
}
double get(int index) {
return coords_[index];
}
double distance(Node node) {
double dist = 0;
for (int i = 0; i < coords_.length; ++i) {
double d = coords_[i] - node.coords_[i];
dist += d * d;
}
return dist;
}
public String toString() {
StringBuilder s = new StringBuilder("(");
for (int i = 0; i < coords_.length; ++i) {
if (i > 0)
s.append(", ");
s.append(coords_[i]);
}
s.append(')');
return s.toString();
}
}
}
|
Keep all operations the same but rewrite the snippet in Java. | from random import seed, random
from time import time
from operator import itemgetter
from collections import namedtuple
from math import sqrt
from copy import deepcopy
def sqd(p1, p2):
return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))
class KdNode(object):
__slots__ = ("dom_elt", "split", "left", "right")
def __init__(self, dom_elt, split, left, right):
self.dom_elt = dom_elt
self.split = split
self.left = left
self.right = right
class Orthotope(object):
__slots__ = ("min", "max")
def __init__(self, mi, ma):
self.min, self.max = mi, ma
class KdTree(object):
__slots__ = ("n", "bounds")
def __init__(self, pts, bounds):
def nk2(split, exset):
if not exset:
return None
exset.sort(key=itemgetter(split))
m = len(exset) // 2
d = exset[m]
while m + 1 < len(exset) and exset[m + 1][split] == d[split]:
m += 1
d = exset[m]
s2 = (split + 1) % len(d)
return KdNode(d, split, nk2(s2, exset[:m]),
nk2(s2, exset[m + 1:]))
self.n = nk2(0, pts)
self.bounds = bounds
T3 = namedtuple("T3", "nearest dist_sqd nodes_visited")
def find_nearest(k, t, p):
def nn(kd, target, hr, max_dist_sqd):
if kd is None:
return T3([0.0] * k, float("inf"), 0)
nodes_visited = 1
s = kd.split
pivot = kd.dom_elt
left_hr = deepcopy(hr)
right_hr = deepcopy(hr)
left_hr.max[s] = pivot[s]
right_hr.min[s] = pivot[s]
if target[s] <= pivot[s]:
nearer_kd, nearer_hr = kd.left, left_hr
further_kd, further_hr = kd.right, right_hr
else:
nearer_kd, nearer_hr = kd.right, right_hr
further_kd, further_hr = kd.left, left_hr
n1 = nn(nearer_kd, target, nearer_hr, max_dist_sqd)
nearest = n1.nearest
dist_sqd = n1.dist_sqd
nodes_visited += n1.nodes_visited
if dist_sqd < max_dist_sqd:
max_dist_sqd = dist_sqd
d = (pivot[s] - target[s]) ** 2
if d > max_dist_sqd:
return T3(nearest, dist_sqd, nodes_visited)
d = sqd(pivot, target)
if d < dist_sqd:
nearest = pivot
dist_sqd = d
max_dist_sqd = dist_sqd
n2 = nn(further_kd, target, further_hr, max_dist_sqd)
nodes_visited += n2.nodes_visited
if n2.dist_sqd < dist_sqd:
nearest = n2.nearest
dist_sqd = n2.dist_sqd
return T3(nearest, dist_sqd, nodes_visited)
return nn(t.n, p, t.bounds, float("inf"))
def show_nearest(k, heading, kd, p):
print(heading + ":")
print("Point: ", p)
n = find_nearest(k, kd, p)
print("Nearest neighbor:", n.nearest)
print("Distance: ", sqrt(n.dist_sqd))
print("Nodes visited: ", n.nodes_visited, "\n")
def random_point(k):
return [random() for _ in range(k)]
def random_points(k, n):
return [random_point(k) for _ in range(n)]
if __name__ == "__main__":
seed(1)
P = lambda *coords: list(coords)
kd1 = KdTree([P(2, 3), P(5, 4), P(9, 6), P(4, 7), P(8, 1), P(7, 2)],
Orthotope(P(0, 0), P(10, 10)))
show_nearest(2, "Wikipedia example data", kd1, P(9, 2))
N = 400000
t0 = time()
kd2 = KdTree(random_points(3, N), Orthotope(P(0, 0, 0), P(1, 1, 1)))
t1 = time()
text = lambda *parts: "".join(map(str, parts))
show_nearest(2, text("k-d tree with ", N,
" random 3D points (generation time: ",
t1-t0, "s)"),
kd2, random_point(3))
| import java.util.*;
public class KdTree {
private int dimensions_;
private Node root_ = null;
private Node best_ = null;
private double bestDistance_ = 0;
private int visited_ = 0;
public KdTree(int dimensions, List<Node> nodes) {
dimensions_ = dimensions;
root_ = makeTree(nodes, 0, nodes.size(), 0);
}
public Node findNearest(Node target) {
if (root_ == null)
throw new IllegalStateException("Tree is empty!");
best_ = null;
visited_ = 0;
bestDistance_ = 0;
nearest(root_, target, 0);
return best_;
}
public int visited() {
return visited_;
}
public double distance() {
return Math.sqrt(bestDistance_);
}
private void nearest(Node root, Node target, int index) {
if (root == null)
return;
++visited_;
double d = root.distance(target);
if (best_ == null || d < bestDistance_) {
bestDistance_ = d;
best_ = root;
}
if (bestDistance_ == 0)
return;
double dx = root.get(index) - target.get(index);
index = (index + 1) % dimensions_;
nearest(dx > 0 ? root.left_ : root.right_, target, index);
if (dx * dx >= bestDistance_)
return;
nearest(dx > 0 ? root.right_ : root.left_, target, index);
}
private Node makeTree(List<Node> nodes, int begin, int end, int index) {
if (end <= begin)
return null;
int n = begin + (end - begin)/2;
Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index));
index = (index + 1) % dimensions_;
node.left_ = makeTree(nodes, begin, n, index);
node.right_ = makeTree(nodes, n + 1, end, index);
return node;
}
private static class NodeComparator implements Comparator<Node> {
private int index_;
private NodeComparator(int index) {
index_ = index;
}
public int compare(Node n1, Node n2) {
return Double.compare(n1.get(index_), n2.get(index_));
}
}
public static class Node {
private double[] coords_;
private Node left_ = null;
private Node right_ = null;
public Node(double[] coords) {
coords_ = coords;
}
public Node(double x, double y) {
this(new double[]{x, y});
}
public Node(double x, double y, double z) {
this(new double[]{x, y, z});
}
double get(int index) {
return coords_[index];
}
double distance(Node node) {
double dist = 0;
for (int i = 0; i < coords_.length; ++i) {
double d = coords_[i] - node.coords_[i];
dist += d * d;
}
return dist;
}
public String toString() {
StringBuilder s = new StringBuilder("(");
for (int i = 0; i < coords_.length; ++i) {
if (i > 0)
s.append(", ");
s.append(coords_[i]);
}
s.append(')');
return s.toString();
}
}
}
|
Please provide an equivalent version of this Python code in Java. | def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers]
squares2a = map(square, numbers)
squares2b = map(lambda x: x*x, numbers)
squares3 = [n * n for n in numbers]
isquares1 = (n * n for n in numbers)
import itertools
isquares2 = itertools.imap(square, numbers)
| public class ArrayCallback7 {
interface IntConsumer {
void run(int x);
}
interface IntToInt {
int run(int x);
}
static void forEach(int[] arr, IntConsumer consumer) {
for (int i : arr) {
consumer.run(i);
}
}
static void update(int[] arr, IntToInt mapper) {
for (int i = 0; i < arr.length; i++) {
arr[i] = mapper.run(arr[i]);
}
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
update(numbers, new IntToInt() {
@Override
public int run(int x) {
return x * x;
}
});
forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
}
}
|
Generate a Java translation of this Python snippet without changing its computational steps. | >>> class Borg(object):
__state = {}
def __init__(self):
self.__dict__ = self.__state
>>> b1 = Borg()
>>> b2 = Borg()
>>> b1 is b2
False
>>> b1.datum = range(5)
>>> b1.datum
[0, 1, 2, 3, 4]
>>> b2.datum
[0, 1, 2, 3, 4]
>>> b1.datum is b2.datum
True
>>>
| class Singleton
{
private static Singleton myInstance;
public static Singleton getInstance()
{
if (myInstance == null)
{
synchronized(Singleton.class)
{
if (myInstance == null)
{
myInstance = new Singleton();
}
}
}
return myInstance;
}
protected Singleton()
{
}
}
|
Produce a language-to-language conversion: from Python to Java, same semantics. | >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> from math import fsum
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0
| public class SafeAddition {
private static double stepDown(double d) {
return Math.nextAfter(d, Double.NEGATIVE_INFINITY);
}
private static double stepUp(double d) {
return Math.nextUp(d);
}
private static double[] safeAdd(double a, double b) {
return new double[]{stepDown(a + b), stepUp(a + b)};
}
public static void main(String[] args) {
double a = 1.2;
double b = 0.03;
double[] result = safeAdd(a, b);
System.out.printf("(%.2f + %.2f) is in the range %.16f..%.16f", a, b, result[0], result[1]);
}
}
|
Generate an equivalent Java version of this Python code. | >>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named Benjamin , Samba , and Bernie
>>>
| String dog = "Benjamin";
String Dog = "Samba";
String DOG = "Bernie";
@Inject Console console;
console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");
|
Change the programming language of this snippet from Python to Java without modifying what it does. | for i in xrange(10, -1, -1):
print i
| for (int i = 10; i >= 0; i--) {
System.out.println(i);
}
|
Translate the given Python code snippet into Java without altering its behavior. | with open(filename, 'w') as f:
f.write(data)
| import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) {
bw.write("abc");
}
}
}
|
Write the same code in Java as shown below in Python. | for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
| for (Integer i = 0; i < 5; i++) {
String line = '';
for (Integer j = 0; j < i; j++) {
line += '*';
}
System.debug(line);
}
List<String> lines = new List<String> {
'*',
'**',
'***',
'****',
'*****'
};
for (String line : lines) {
System.debug(line);
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. | from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))
def is_gapful(x):
return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)
if __name__ == '__main__':
start = 100
for mx, last in [(20, 20), (100, 15), (1_000, 10)]:
print(f"\nLast {last} of the first {mx} binned-by-last digit "
f"gapful numbers >= {start}")
bin = {i: [] for i in range(1, 10)}
gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))
while any(len(val) < mx for val in bin.values()):
g = next(gen)
val = bin[g % 10]
if len(val) < mx:
val.append(g)
b = {k:v[-last:] for k, v in bin.items()}
txt = pformat(b, width=220)
print('', re.sub(r"[{},\[\]]", '', txt))
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalindromicGapfulNumbers {
public static void main(String[] args) {
System.out.println("First 20 palindromic gapful numbers ending in:");
displayMap(getPalindromicGapfulEnding(20, 20));
System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(15, 100));
System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(10, 1000));
}
private static void displayMap(Map<Integer,List<Long>> map) {
for ( int key = 1 ; key <= 9 ; key++ ) {
System.out.println(key + " : " + map.get(key));
}
}
public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {
Map<Integer,List<Long>> map = new HashMap<>();
Map<Integer,Integer> mapCount = new HashMap<>();
for ( int i = 1 ; i <= 9 ; i++ ) {
map.put(i, new ArrayList<>());
mapCount.put(i, 0);
}
boolean notPopulated = true;
for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {
if ( isGapful(n) ) {
int index = (int) (n % 10);
if ( mapCount.get(index) < firstHowMany ) {
map.get(index).add(n);
mapCount.put(index, mapCount.get(index) + 1);
if ( map.get(index).size() > countReturned ) {
map.get(index).remove(0);
}
}
boolean finished = true;
for ( int i = 1 ; i <= 9 ; i++ ) {
if ( mapCount.get(i) < firstHowMany ) {
finished = false;
break;
}
}
if ( finished ) {
notPopulated = false;
}
}
}
return map;
}
public static boolean isGapful(long n) {
String s = Long.toString(n);
return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0;
}
public static int length(long n) {
int length = 0;
while ( n > 0 ) {
length += 1;
n /= 10;
}
return length;
}
public static long nextPalindrome(long n) {
int length = length(n);
if ( length % 2 == 0 ) {
length /= 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/10));
}
return Long.parseLong(n + reverse(n));
}
length = (length - 1) / 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/100));
}
return Long.parseLong(n + reverse(n/10));
}
private static boolean powerTen(long n) {
while ( n > 9 && n % 10 == 0 ) {
n /= 10;
}
return n == 1;
}
private static String reverse(long n) {
return (new StringBuilder(n + "")).reverse().toString();
}
}
|
Produce a functionally identical Java code for the snippet given in Python. | from itertools import count
from pprint import pformat
import re
import heapq
def pal_part_gen(odd=True):
for i in count(1):
fwd = str(i)
rev = fwd[::-1][1:] if odd else fwd[::-1]
yield int(fwd + rev)
def pal_ordered_gen():
yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False))
def is_gapful(x):
return (x % (int(str(x)[0]) * 10 + (x % 10)) == 0)
if __name__ == '__main__':
start = 100
for mx, last in [(20, 20), (100, 15), (1_000, 10)]:
print(f"\nLast {last} of the first {mx} binned-by-last digit "
f"gapful numbers >= {start}")
bin = {i: [] for i in range(1, 10)}
gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i))
while any(len(val) < mx for val in bin.values()):
g = next(gen)
val = bin[g % 10]
if len(val) < mx:
val.append(g)
b = {k:v[-last:] for k, v in bin.items()}
txt = pformat(b, width=220)
print('', re.sub(r"[{},\[\]]", '', txt))
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PalindromicGapfulNumbers {
public static void main(String[] args) {
System.out.println("First 20 palindromic gapful numbers ending in:");
displayMap(getPalindromicGapfulEnding(20, 20));
System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(15, 100));
System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n");
displayMap(getPalindromicGapfulEnding(10, 1000));
}
private static void displayMap(Map<Integer,List<Long>> map) {
for ( int key = 1 ; key <= 9 ; key++ ) {
System.out.println(key + " : " + map.get(key));
}
}
public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) {
Map<Integer,List<Long>> map = new HashMap<>();
Map<Integer,Integer> mapCount = new HashMap<>();
for ( int i = 1 ; i <= 9 ; i++ ) {
map.put(i, new ArrayList<>());
mapCount.put(i, 0);
}
boolean notPopulated = true;
for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) {
if ( isGapful(n) ) {
int index = (int) (n % 10);
if ( mapCount.get(index) < firstHowMany ) {
map.get(index).add(n);
mapCount.put(index, mapCount.get(index) + 1);
if ( map.get(index).size() > countReturned ) {
map.get(index).remove(0);
}
}
boolean finished = true;
for ( int i = 1 ; i <= 9 ; i++ ) {
if ( mapCount.get(i) < firstHowMany ) {
finished = false;
break;
}
}
if ( finished ) {
notPopulated = false;
}
}
}
return map;
}
public static boolean isGapful(long n) {
String s = Long.toString(n);
return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0;
}
public static int length(long n) {
int length = 0;
while ( n > 0 ) {
length += 1;
n /= 10;
}
return length;
}
public static long nextPalindrome(long n) {
int length = length(n);
if ( length % 2 == 0 ) {
length /= 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/10));
}
return Long.parseLong(n + reverse(n));
}
length = (length - 1) / 2;
while ( length > 0 ) {
n /= 10;
length--;
}
n += 1;
if ( powerTen(n) ) {
return Long.parseLong(n + reverse(n/100));
}
return Long.parseLong(n + reverse(n/10));
}
private static boolean powerTen(long n) {
while ( n > 9 && n % 10 == 0 ) {
n /= 10;
}
return n == 1;
}
private static String reverse(long n) {
return (new StringBuilder(n + "")).reverse().toString();
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the Python version. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| import javax.swing.*;
import java.awt.*;
class SierpinskyTriangle {
public static void main(String[] args) {
int i = 3;
if(args.length >= 1) {
try {
i = Integer.parseInt(args[0]);
}
catch(NumberFormatException e) {
System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i);
}
}
final int level = i;
JFrame frame = new JFrame("Sierpinsky Triangle - Java");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);
}
};
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {
if(level <= 0) return;
g.drawLine(x, y, x+size, y);
g.drawLine(x, y, x, y+size);
g.drawLine(x+size, y, x, y+size);
drawSierpinskyTriangle(level-1, x, y, size/2, g);
drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);
drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);
}
}
|
Ensure the translated Java code behaves exactly like the original Python snippet. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| import javax.swing.*;
import java.awt.*;
class SierpinskyTriangle {
public static void main(String[] args) {
int i = 3;
if(args.length >= 1) {
try {
i = Integer.parseInt(args[0]);
}
catch(NumberFormatException e) {
System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i);
}
}
final int level = i;
JFrame frame = new JFrame("Sierpinsky Triangle - Java");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g);
}
};
panel.setPreferredSize(new Dimension(400, 400));
frame.add(panel);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) {
if(level <= 0) return;
g.drawLine(x, y, x+size, y);
g.drawLine(x, y, x, y+size);
g.drawLine(x+size, y, x, y+size);
drawSierpinskyTriangle(level-1, x, y, size/2, g);
drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g);
drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.