Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate an equivalent Mathematica version of this C++ code. | #include <gmp.h>
#include <iostream>
using namespace std;
typedef unsigned long long int u64;
bool primality_pretest(u64 k) {
if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) ||
!(k % 13) || !(k % 17) || !(k % 19) || !(k % 23)
) {
return (k <= 23);
}
return true;
}
bool pr... | ClearAll[PrimeFactorCounts, U]
PrimeFactorCounts[n_Integer] := Total[FactorInteger[n][[All, 2]]]
U[n_, m_] := (6 m + 1) (12 m + 1) Product[2^i 9 m + 1, {i, 1, n - 2}]
FindFirstChernickCarmichaelNumber[n_Integer?Positive] :=
Module[{step, i, m, formula, value},
step = Ceiling[2^(n - 4)];
If[n > 5, step *= 5];
i ... |
Convert this C++ snippet to Mathematica and keep its semantics consistent. | #include <cstdint>
#include <iostream>
#include <vector>
#include <primesieve.hpp>
void print_diffs(const std::vector<uint64_t>& vec) {
for (size_t i = 0, n = vec.size(); i != n; ++i) {
if (i != 0)
std::cout << " (" << vec[i] - vec[i - 1] << ") ";
std::cout << vec[i];
}
std::cou... | prime = Prime[Range[PrimePi[10^6]]];
s = Split[Differences[prime], Less];
max = Max[Length /@ s];
diffs = Select[s, Length/*EqualTo[max]];
seqs = SequencePosition[Flatten[s], #, 1][[1]] & /@ diffs;
Take[prime, # + {0, 1}] & /@ seqs
s = Split[Differences[prime], Greater];
max = Max[Length /@ s];
diffs = Select[s, Lengt... |
Generate an equivalent Mathematica version of this C++ code. | #include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
std::vector<int> generate_primes(int limit) {
std::vector<bool> sieve(limit >> 1, true);
for (int p = 3, s = 9; s < limit; p += 2) {
if (sieve[p >> 1]) {
for (int q = s; q < limit; q += p << 1)
sieve... | ClearAll[WilsonPrime]
WilsonPrime[n_Integer] := Module[{primes, out},
primes = Prime[Range[PrimePi[11000]]];
out = Reap@Do[
If[Divisible[((n - 1)!) ((p - n)!) - (-1)^n, p^2], Sow[p]]
,
{p, primes}
];
First[out[[2]], {}]
]
Do[
Print[WilsonPrime[n]]
,
{n, 1, 11}
]
|
Change the programming language of this snippet from C++ to Mathematica without modifying what it does. | #include <cassert>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
bool is_prime(unsigned int n) {
assert(n > 0 && n < 64);
return (1ULL << n) & 0x28208a20a08a28ac;
}
template <typename Iterator>
bool prime_triangle_row(Iterator begin, Iterator end) {
if (std:... | ClearAll[FindPrimeTriangles, FindPrimeTrianglesHelper]
FindPrimeTriangles[max_] :=
Module[{count = 0, firstsolution, primes, primeQ},
primes = PrimeQ[Range[2 max]];
primeQ[n_] := primes[[n]];
ClearAll[FindPrimeTrianglesHelper];
FindPrimeTrianglesHelper[start_, remainder_, mxx_] :=
Module[{last, nexts, r, ... |
Convert the following code from C++ to Mathematica, ensuring the logic remains intact. | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };
template<const uint N>
void lucas(ulong b) {
std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b... | ClearAll[FindMetallicRatio]
FindMetallicRatio[b_, digits_] :=
Module[{n, m, data, acc, old, done = False},
{n, m} = {1, 1};
old = -100;
data = {};
While[done == False,
{n, m} = {m, b m + n};
AppendTo[data, {m, m/n}];
If[Length[data] > 15,
If[-N[Log10[Abs[data[[-1, 2]] - data[[-2, 2]]]]] > digits,... |
Convert this C++ block to Mathematica, preserving its control flow and logic. | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };
template<const uint N>
void lucas(ulong b) {
std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b... | ClearAll[FindMetallicRatio]
FindMetallicRatio[b_, digits_] :=
Module[{n, m, data, acc, old, done = False},
{n, m} = {1, 1};
old = -100;
data = {};
While[done == False,
{n, m} = {m, b m + n};
AppendTo[data, {m, m/n}];
If[Length[data] > 15,
If[-N[Log10[Abs[data[[-1, 2]] - data[[-2, 2]]]]] > digits,... |
Transform the following C++ implementation into Mathematica, maintaining the same output and logic. | #include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
class prime_counter {
public:
explicit prime_counter(int limit);
int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }
private:
std::vector<int> count_;
};
prime_counter::prime_count... | l = PrimePi[Range[10^6]] - PrimePi[Range[10^6]/2];
Multicolumn[1 + Position[l, #][[-1, 1]] & /@ Range[0, 99], {Automatic, 10}, Appearance -> "Horizontal"]
1 + Position[l, 999][[-1, 1]]
1 + Position[l, 9999][[-1, 1]]
|
Maintain the same structure and functionality when rewriting this code in Mathematica. | #include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>
class prime_counter {
public:
explicit prime_counter(int limit);
int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }
private:
std::vector<int> count_;
};
prime_counter::prime_count... | l = PrimePi[Range[10^6]] - PrimePi[Range[10^6]/2];
Multicolumn[1 + Position[l, #][[-1, 1]] & /@ Range[0, 99], {Automatic, 10}, Appearance -> "Horizontal"]
1 + Position[l, 999][[-1, 1]]
1 + Position[l, 9999][[-1, 1]]
|
Produce a functionally identical Mathematica code for the snippet given in C++. | #include <future>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
#include <primesieve.hpp>
std::vector<uint64_t> repunit_primes(uint32_t base,
const std::vector<uint64_t>& primes) {
std::vector<uint64_t> result;
for (uint64_t prime : primes) {
... | ClearAll[RepUnitPrimeQ]
RepUnitPrimeQ[b_][n_] := PrimeQ[FromDigits[ConstantArray[1, n], b]]
ClearAll[RepUnitPrimeQ]
RepUnitPrimeQ[b_][n_] := PrimeQ[FromDigits[ConstantArray[1, n], b]]
Do[
Print["Base ", b, ": ", Select[Range[2700], RepUnitPrimeQ[b]]]
,
{b, 2, 16}
]
|
Write the same algorithm in Mathematica as shown in this C++ implementation. | #include <future>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
#include <primesieve.hpp>
std::vector<uint64_t> repunit_primes(uint32_t base,
const std::vector<uint64_t>& primes) {
std::vector<uint64_t> result;
for (uint64_t prime : primes) {
... | ClearAll[RepUnitPrimeQ]
RepUnitPrimeQ[b_][n_] := PrimeQ[FromDigits[ConstantArray[1, n], b]]
ClearAll[RepUnitPrimeQ]
RepUnitPrimeQ[b_][n_] := PrimeQ[FromDigits[ConstantArray[1, n], b]]
Do[
Print["Base ", b, ": ", Select[Range[2700], RepUnitPrimeQ[b]]]
,
{b, 2, 16}
]
|
Produce a functionally identical Mathematica code for the snippet given in C++. | #include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <primesieve.hpp>
class prime_sieve {
public:
explicit prime_sieve(uint64_t limit);
bool is_prime(uint64_t n) const {
return n == 2 || ((n & 1) ... | ClearAll[OtherBasePrimes, OtherBasePrimesPower]
OtherBasePrimes[n_Integer] := Module[{digs, minbase, bases},
digs = IntegerDigits[n];
minbase = Max[digs] + 1;
bases = Range[minbase, 36];
Pick[bases, PrimeQ[FromDigits[digs, #] & /@ bases], True]
]
OtherBasePrimesPower[p_] := Module[{min, max, out, maxlen},
m... |
Can you help me rewrite this code in Mathematica instead of C++, keeping it the same logically? | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <map>
#include <vector>
#include <primesieve.hpp>
class erdos_selfridge {
public:
explicit erdos_selfridge(int limit);
uint64_t get_prime(int index) const { return primes_[index].first; }
int get_category(int index);
... | ClearAll[SpecialPrimeFactors]
SpecialPrimeFactors[p_Integer] := FactorInteger[p + 1][[All, 1]]
ps = Prime[Range[200]];
cs = {{2, 3}};
Do[
If[Length[ps] > 0,
newc =
Select[ps,
Complement[SpecialPrimeFactors[#], Catenate[cs]] === {} &];
AppendTo[cs, newc];
ps = Complement[ps, newc];
,
Break[]... |
Please provide an equivalent version of this C++ code in Mathematica. | #include <primesieve.hpp>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <locale>
class composite_iterator {
public:
composite_iterator();
uint64_t next_composite();
private:
uint64_t composite;
uint64_t prime;
primesieve::iterator pi;
};
composite_iterator::composite_iterator... | $HistoryLength = 1;
ub = 10^8;
ps = Prime[Range[PrimePi[ub]]];
cs = Complement[Range[2, ub], ps];
cps = Accumulate[ps];
ccs = Accumulate[cs];
indices = Intersection[cps, ccs];
poss = {FirstPosition[cps, #], FirstPosition[ccs, #]} & /@ indices;
TableForm[MapThread[Prepend, {Flatten /@ poss, indices}],
TableHeadings ->... |
Translate the given C++ code snippet into Mathematica without altering its behavior. | #include <iostream>
#include <locale>
#include <unordered_map>
#include <primesieve.hpp>
class prime_gaps {
public:
prime_gaps() { last_prime_ = iterator_.next_prime(); }
uint64_t find_gap_start(uint64_t gap);
private:
primesieve::iterator iterator_;
uint64_t last_prime_;
std::unordered_map<uint64... | primes = Prime[Range[10^7]];
gaps = {Differences[primes], Most[primes]} // Transpose;
tmp = GatherBy[gaps, First][[All, 1]];
tmp = SortBy[tmp, First];
starts = Association[Rule @@@ tmp];
set = {Most[tmp[[All, 1]]], Abs@Differences[tmp[[All, 2]]]} // Transpose;
data = Table[{n, k} = SelectFirst[set, Last/*GreaterThan[10... |
Keep all operations the same but rewrite the snippet in Mathematica. | #include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using word_map = std::map<size_t, std::vector<std::string>>;
bool one_away(const std::string& s1, const std::string& s2) {
if (s1.size() != s2.size())
return false;
bool result = false;
... | db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[3]]]]];
sel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&];
g=Graph[db,UndirectedEdge@@@sel];
FindShortestPath[g,"boy","man"]
db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLen... |
Preserve the algorithm and functionality while converting the code from C++ to Mathematica. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type val... | a = N@{{1, 7, 5, 0}, {5, 8, 6, 9}, {2, 1, 6, 4}, {8, 1, 2, 4}};
elimmat = RowReduce[Join[a, IdentityMatrix[Length[a]], 2]];
inv = elimmat[[All, -Length[a] ;;]]
|
Maintain the same structure and functionality when rewriting this code in Mathematica. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type val... | a = N@{{1, 7, 5, 0}, {5, 8, 6, 9}, {2, 1, 6, 4}, {8, 1, 2, 4}};
elimmat = RowReduce[Join[a, IdentityMatrix[Length[a]], 2]];
inv = elimmat[[All, -Length[a] ;;]]
|
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version. | #include <ctime>
#include <iostream>
#include <string>
#include <algorithm>
class chessBoard {
public:
void generateRNDBoard( int brds ) {
int a, b, i; char c;
for( int cc = 0; cc < brds; cc++ ) {
memset( brd, 0, 64 );
std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk";... | g = ConstantArray["", {8, 8}];
While[Norm@First@Differences[r = RandomChoice[Tuples[Range[8], 2], 2]] <= Sqrt[2], Null];
g = ReplacePart[g, {r[[1]] -> "K", r[[2]] -> "k"}];
avail = Position[g, "", {2}];
n = RandomInteger[{2, 14}];
rls = Thread[RandomSample[avail, n] -> RandomChoice[Characters@"NBRQnbrq", n]];
g = Repla... |
Port the following code from C++ to Mathematica with equivalent syntax and logic. |
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class sierpinski_square {
public:
void write(std::ostream& out, int size, int length, int order);
private:
static std::string rewrite(const std::string& s);
void line(std::ostream& out);
void execute(std::ostream& out, const std... | Graphics[SierpinskiCurve[3]]
|
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version. | #include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::uint128_t;
template <typename T> void unique_sort(std::vector<T>& vector) {
std::sort(vector.begin(), vector... | ClearAll[PowerfulNumberQ, StrongAchillesNumberQ]
PowerfulNumberQ[n_Integer] := AllTrue[FactorInteger[n][[All, 2]], GreaterEqualThan[2]]
AchillesNumberQ[n_Integer] := Module[{divs},
If[PowerfulNumberQ[n],
divs = Divisors[n];
If[Length[divs] > 2,
divs = divs[[2 ;; -2]];
!AnyTrue[Log[#, n] & /@ divs, Integ... |
Change the following C++ code into Mathematica without altering its purpose. | #include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::uint128_t;
template <typename T> void unique_sort(std::vector<T>& vector) {
std::sort(vector.begin(), vector... | ClearAll[PowerfulNumberQ, StrongAchillesNumberQ]
PowerfulNumberQ[n_Integer] := AllTrue[FactorInteger[n][[All, 2]], GreaterEqualThan[2]]
AchillesNumberQ[n_Integer] := Module[{divs},
If[PowerfulNumberQ[n],
divs = Divisors[n];
If[Length[divs] > 2,
divs = divs[[2 ;; -2]];
!AnyTrue[Log[#, n] & /@ divs, Integ... |
Transform the following C++ implementation into Mathematica, maintaining the same output and logic. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int digit_product(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
int prime_factor_sum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
... | ClearAll[RhondaNumberQ]
RhondaNumberQ[b_Integer][n_Integer] := Module[{l, r},
l = Times @@ IntegerDigits[n, b];
r = Total[Catenate[ConstantArray @@@ FactorInteger[n]]];
l == b r
]
bases = Select[Range[2, 36], PrimeQ/*Not];
Do[
Print["base ", b, ":", Take[Select[Range[700000], RhondaNumberQ[b]], UpTo[15]]];
,
{... |
Write a version of this C++ function in Mathematica with identical behavior. | #include <algorithm>
#include <iostream>
int main() {
std::string str("AABBBC");
int count = 0;
do {
std::cout << str << (++count % 10 == 0 ? '\n' : ' ');
} while (std::next_permutation(str.begin(), str.end()));
}
| ClearAll[PermsFromFrequencies]
PermsFromFrequencies[l_List] := Module[{digs},
digs = Flatten[MapIndexed[ReverseApplied[ConstantArray], l]];
Permutations[digs]
]
PermsFromFrequencies[{2, 3, 1}] // Column
|
Port the following code from C++ to Mathematica with equivalent syntax and logic. | #include <cctype>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
struct number_names {
const char* cardinal;
const char* ordinal;
};
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "fou... |
IntNameWords[n_]:=(IntNameWords[n]=StringSplit[IntegerName[n,"Words"]])/;n<1000;
IntNameWords[n_]:=StringSplit[IntegerName[n,"Words"]]/;Divisible[n,1000];
IntNameWords[n_]:=Flatten[Riffle[IntNameWords/@QuotientRemainder[n,1000],"thousand"]]/;n<1000000;
IntNameWords[n_]:=Flatten[Riffle[IntNameWords/@QuotientRemaind... |
Rewrite the snippet below in Mathematica so it works the same as the original C++ code. | #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) ... | First[RealDigits[N[Exp[Pi Sqrt[163]], 200]]]
Table[
c = N[Exp[Pi Sqrt[h]], 40];
Log10[1 - FractionalPart[c]]
,
{h, {19, 43, 67, 163}}
]
|
Convert the following code from C++ to Mathematica, ensuring the logic remains intact. | #include <iomanip>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
using big_float = boost::multiprecision::cpp_dec_float_100;
big_float f(unsigned int n) {
big_float pi(boost::math::constants::pi<big_float>());
return exp(sqrt(big_float(n)) ... | First[RealDigits[N[Exp[Pi Sqrt[163]], 200]]]
Table[
c = N[Exp[Pi Sqrt[h]], 40];
Log10[1 - FractionalPart[c]]
,
{h, {19, 43, 67, 163}}
]
|
Write the same code in Mathematica as shown below in C++. | #include <cmath>
#include <fstream>
#include <iostream>
bool sunflower(const char* filename) {
std::ofstream out(filename);
if (!out)
return false;
constexpr int size = 600;
constexpr int seeds = 5 * size;
constexpr double pi = 3.14159265359;
constexpr double phi = 1.61803398875;
... | numseeds = 3000;
pts = Table[
i = N[ni];
r = i^GoldenRatio/numseeds;
t = 2 Pi GoldenRatio i;
Circle[AngleVector[{r, t}], i/(numseeds/3)]
,
{ni, numseeds}
];
Graphics[pts]
|
Can you help me rewrite this code in Mathematica instead of C++, keeping it the same logically? | #include <iomanip>
#include <iostream>
#include <vector>
std::vector<bool> prime_sieve(int limit) {
std::vector<bool> sieve(limit, true);
if (limit > 0)
sieve[0] = false;
if (limit > 1)
sieve[1] = false;
for (int i = 4; i < limit; i += 2)
sieve[i] = false;
for (int p = 3, sq... | UpperLimit = 10000;
SmallerTwinPrimes = Select[Range[UpperLimit], (PrimeQ[#] && PrimeQ[# + 2]) &];
AllTwinPrimes = Union[SmallerTwinPrimes, SmallerTwinPrimes + 2];
CheckIfNotSumOfNumbersInSet[n_, set_] := If[Intersection[(n - set), set] == {}, n, ## &[]]
ListOfNonTwinPrimeSums = Table[CheckIfNotSumOfNumbersInSet[n, A... |
Translate the given C++ code snippet into Mathematica without altering its behavior. | #include <algorithm>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
std::vector<uint64_t> divisors(uint64_t n) {
std::vector<uint64_t> result{1};
uint64_t power = 2;
for (; (n & 1) == 0; power <<= 1, n >>= 1)
result.push_back(power);
for (uint64_t p = 3; p * p <= n;... | ClearAll[zsigmondy]
Attributes[zsigmondy] = Listable;
zsigmondy[a_Integer, b_Integer, 1] := a - b /; a >= b;
zsigmondy[a_Integer, b_Integer, n_Integer] := (
hatvanyok = a^Range[n] - b^Range[n];
kishatvany = a^Range[n - 1] - b^Range[n - 1];
biggestelement = Part[hatvanyok, n];
divisors = Divisors[biggestele... |
Produce a functionally identical Mathematica code for the snippet given in C++. | #include <array>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <vector>
auto init_zc() {
std::array<int, 1000> zc;
zc.fill(0);
zc[0] = 3;
for (int x = 1; x <= 9; ++x) {
zc[x] = 2;
zc[10 * x] = 2;
zc[100 * x] = 2;
for (int y = 10; y <= 90; y += 10) {
... | ClearAll[ZeroDigitsFractionFactorial]
ZeroDigitsFractionFactorial[n_Integer] := Module[{m},
m = IntegerDigits[n!];
Count[m, 0]/Length[m]
]
ZeroDigitsFractionFactorial /@ Range[6] // Mean // N
ZeroDigitsFractionFactorial /@ Range[25] // Mean // N
ZeroDigitsFractionFactorial /@ Range[100] // Mean // N
ZeroDigitsFra... |
Write a version of this PHP function in Common_Lisp with identical behavior. | <?php
$colors = array(array( 0, 0, 0), // black
array(255, 0, 0), // red
array( 0, 255, 0), // green
array( 0, 0, 255), // blue
array(255, 0, 255), // magenta
array( 0, 255, 255), // cyan
array(... | (defun color-bars ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(dotimes (i (height scr))
(move scr i 0)
(dolist (color '(:red :green :yellow :blue :magenta :cyan :white :black))
(add-char scr #\space :bgcolor color :n (floor (/ (width scr) 8)))))
(refresh ... |
Generate a Common_Lisp translation of this PHP snippet without changing its computational steps. | <?php
$colors = array(array( 0, 0, 0), // black
array(255, 0, 0), // red
array( 0, 255, 0), // green
array( 0, 0, 255), // blue
array(255, 0, 255), // magenta
array( 0, 255, 255), // cyan
array(... | (defun color-bars ()
(with-screen (scr :input-blocking t :input-echoing nil :cursor-visible nil)
(dotimes (i (height scr))
(move scr i 0)
(dolist (color '(:red :green :yellow :blue :magenta :cyan :white :black))
(add-char scr #\space :bgcolor color :n (floor (/ (width scr) 8)))))
(refresh ... |
Convert this PHP snippet to Common_Lisp and keep its semantics consistent. | <?php
function contains($bounds, $lat, $lng)
{
$count = 0;
$bounds_count = count($bounds);
for ($b = 0; $b < $bounds_count; $b++) {
$vertex1 = $bounds[$b];
$vertex2 = $bounds[($b + 1) % $bounds_count];
if (west($vertex1, $vertex2, $lng, $lat))
$count++;
}
return... | (defun point-in-polygon (point polygon)
(do ((in-p nil)) ((endp polygon) in-p)
(when (ray-intersects-segment point (pop polygon))
(setf in-p (not in-p)))))
(defun ray-intersects-segment (point segment &optional (epsilon .001))
(destructuring-bind (px . py) point
(destructuring-bind ((ax . ay) . (bx .... |
Write the same code in Common_Lisp as shown below in PHP. | class MyException extends Exception
{
}
| (define-condition unexpected-odd-number (error)
((number :reader number :initarg :number))
(:report (lambda (condition stream)
(format stream "Unexpected odd number: ~w."
(number condition)))))
(defun get-number (&aux (n (random 100)))
(if (not (oddp n)) n
(error 'unexpected... |
Convert this PHP snippet to Common_Lisp and keep its semantics consistent. | #!/usr/bin/env php
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwi... | (define-condition choose-digits () ())
(define-condition bad-equation (error) ())
(defun 24-game ()
(let (chosen-digits)
(labels ((prompt ()
(format t "Chosen digits: ~{~D~^, ~}~%~
Enter expression (or `bye' to quit, `!' to choose new digits): "
cho... |
Generate an equivalent Common_Lisp version of this PHP code. | #!/usr/bin/env php
The 24 Game
Given any four digits in the range 1 to 9, which may have repetitions,
Using just the +, -, *, and / operators; and the possible use of
brackets, (), show how to make an answer of 24.
An answer of "q" will quit the game.
An answer of "!" will generate a new set of four digits.
Otherwi... | (define-condition choose-digits () ())
(define-condition bad-equation (error) ())
(defun 24-game ()
(let (chosen-digits)
(labels ((prompt ()
(format t "Chosen digits: ~{~D~^, ~}~%~
Enter expression (or `bye' to quit, `!' to choose new digits): "
cho... |
Transform the following PHP implementation into Common_Lisp, maintaining the same output and logic. | <?php
echo substr_count("the three truths", "th"), PHP_EOL; // prints "3"
echo substr_count("ababababab", "abab"), PHP_EOL; // prints "2"
| (defun count-sub (str pat)
(loop with z = 0 with s = 0 while s do
(when (setf s (search pat str :start2 s))
(incf z) (incf s (length pat)))
finally (return z)))
(count-sub "ababa" "ab")
(count-sub "ababa" "aba")
|
Write the same algorithm in Common_Lisp as shown in this PHP implementation. | <?php
header("Content-type: image/png");
$width = 512;
$height = 512;
$img = imagecreatetruecolor($width,$height);
$bg = imagecolorallocate($img,255,255,255);
imagefilledrectangle($img, 0, 0, $width, $width, $bg);
$depth = 8;
function drawTree($x1, $y1, $angle, $depth){
global $img;
if ($depth != 0)... |
(defun deg-to-radian (deg)
"converts degrees to radians"
(* deg pi 1/180))
(defun cos-deg (angle)
"returns cosin of the angle expressed in degress"
(cos (deg-to-radian angle)))
(defun sin-deg (angle)
"returns sin of the angle expressed in degress"
(sin (deg-to-radian angle)))
(defun draw-tree (surface ... |
Maintain the same structure and functionality when rewriting this code in Common_Lisp. | <?php
$conf = file_get_contents('parse-conf-file.txt');
$conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf);
$conf = preg_replace_callback(
'/^([a-z]+)\s*=((?=.*\,.*).*)$/mi',
function ($matches) {
$r = '';
foreach (explode(',', $matches[2]) AS $val) {
$r .= $matches[1] . '[]... | (ql:quickload :parser-combinators)
(defpackage :read-config
(:use :cl :parser-combinators))
(in-package :read-config)
(defun trim-space (string)
(string-trim '(#\space #\tab) string))
(defun any-but1? (except)
(named-seq? (<- res (many1? (except? (item) except)))
(coerce res 'string)))
(defun v... |
Convert the following code from PHP to Common_Lisp, ensuring the logic remains intact. | <?php
$dog = 'Benjamin';
$Dog = 'Samba';
$DOG = 'Bernie';
echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n";
function DOG() { return 'Bernie'; }
echo 'There is only 1 dog named ' . dog() . "\n";
| CL-USER> (let* ((dog "Benjamin") (Dog "Samba") (DOG "Bernie"))
(format nil "There is just one dog named ~a." dog))
"There is just one dog named Bernie."
|
Rewrite the snippet below in Common_Lisp so it works the same as the original PHP code. | function stoogeSort(&$arr, $i, $j)
{
if($arr[$j] < $arr[$i])
{
list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]);
}
if(($j - $i) > 1)
{
$t = ($j - $i + 1) / 3;
stoogesort($arr, $i, $j - $t);
stoogesort($arr, $i + $t, $j);
stoogesort($arr, $i, $j - $t);
}
}
| (defun stooge-sort (vector &optional (i 0) (j (1- (length vector))))
(when (> (aref vector i) (aref vector j))
(rotatef (aref vector i) (aref vector j)))
(when (> (- j i) 1)
(let ((third (floor (1+ (- j i)) 3)))
(stooge-sort vector i (- j third))
(stooge-sort vector (+ i third) j)
(stooge-... |
Keep all operations the same but rewrite the snippet in Common_Lisp. | function shellSort($arr)
{
$inc = round(count($arr)/2);
while($inc > 0)
{
for($i = $inc; $i < count($arr);$i++){
$temp = $arr[$i];
$j = $i;
while($j >= $inc && $arr[$j-$inc] > $temp)
{
$arr[$j] = $arr[$j - $inc];
$j -= $inc;
}
$arr[$j] = $temp;
}
$inc = round($inc/2.2);
}
return $ar... | (defun gap-insertion-sort (array predicate gap)
(let ((length (length array)))
(if (< length 2) array
(do ((i 1 (1+ i))) ((eql i length) array)
(do ((x (aref array i))
(j i (- j gap)))
((or (< (- j gap) 0)
(not (funcall predicate x (aref array (1- j)))))
... |
Generate an equivalent Common_Lisp version of this PHP code. | <?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOC... | (defun read-nth-line (file n &aux (line-number 0))
"Read the nth line from a text file. The first line has the number 1"
(assert (> n 0) (n))
(with-open-file (stream file)
(loop for line = (read-line stream nil nil)
if (and (null line) (< line-number n))
do (error "file ~a is too short, ... |
Convert this PHP block to Common_Lisp, preserving its control flow and logic. | <?php
$DOCROOT = $_SERVER['DOCUMENT_ROOT'];
function fileLine ($lineNum, $file) {
$count = 0;
while (!feof($file)) {
$count++;
$line = fgets($file);
if ($count == $lineNum) return $line;
}
die("Requested file has fewer than ".$lineNum." lines!");
}
@ $fp = fopen("$DOC... | (defun read-nth-line (file n &aux (line-number 0))
"Read the nth line from a text file. The first line has the number 1"
(assert (> n 0) (n))
(with-open-file (stream file)
(loop for line = (read-line stream nil nil)
if (and (null line) (< line-number n))
do (error "file ~a is too short, ... |
Write the same code in Common_Lisp as shown below in PHP. | <?php
$s = 'http://foo/bar/';
$s = rawurlencode($s);
?>
| (defun needs-encoding-p (char)
(not (digit-char-p char 36)))
(defun encode-char (char)
(format nil "%~2,'0X" (char-code char)))
(defun url-encode (url)
(apply #'concatenate 'string
(map 'list (lambda (char)
(if (needs-encoding-p char)
(encode-char char)
... |
Preserve the algorithm and functionality while converting the code from PHP to Common_Lisp. | <?php
$s = 'http://foo/bar/';
$s = rawurlencode($s);
?>
| (defun needs-encoding-p (char)
(not (digit-char-p char 36)))
(defun encode-char (char)
(format nil "%~2,'0X" (char-code char)))
(defun url-encode (url)
(apply #'concatenate 'string
(map 'list (lambda (char)
(if (needs-encoding-p char)
(encode-char char)
... |
Write a version of this PHP function in Common_Lisp with identical behavior. | <?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 = ... | (defun read-numbers ()
(princ "Enter 11 numbers (space-separated): ")
(let ((numbers '()))
(dotimes (i 11 numbers)
(push (read) numbers))))
(defun trabb-pardo-knuth (func overflowp)
(let ((S (read-numbers)))
(format T "~{~a~%~}"
(substitute-if "Overflow!" overflowp (mapcar func S)))))
... |
Can you help me rewrite this code in Common_Lisp instead of PHP, keeping it the same logically? | $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... | (defun odd-word (s)
(let ((stream (make-string-input-stream s)))
(loop for forwardp = t then (not forwardp)
while (if forwardp
(forward stream)
(funcall (backward stream)))) ))
(defun forward (stream)
(let ((ch (read-char stream)))
(write-char ch)
(if (... |
Write a version of this PHP function in Common_Lisp with identical behavior. | <?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;... | (defun to-ascii (str) (mapcar #'char-code (coerce str 'list)))
(defun to-digits (n)
(mapcar #'(lambda(v) (- v 48)) (to-ascii (princ-to-string n))))
(defun count-digits (n)
(do
((counts (make-array '(10) :initial-contents '(0 0 0 0 0 0 0 0 0 0)))
(curlist (to-digits n) (cdr curlist)))
((null cu... |
Write the same algorithm in Common_Lisp as shown in this PHP implementation. | <?php
$n = 9; // the number of rows
for ($i = 1; $i <= $n; $i++) {
for ($j = 1; $j <= $n; $j++) {
echo ($i == $j || $i == $n - $j + 1) ? ' 1' : ' 0';
}
echo "\n";
}
| TwoDiagonalMatrix
=LAMBDA(n,
LET(
ixs, SEQUENCE(n, n, 0, 1),
x, MOD(ixs, n),
y, QUOTIENT(ixs, n),
IF(x = y,
1,
IF(x = (n - y) - 1, 1, 0)
)
)
)
|
Change the following PHP code into Common_Lisp without altering its purpose. | <?php foreach(file("unixdict.txt") as $w) echo (strstr($w, "the") && strlen(trim($w)) > 11) ? $w : "";
| (defun print-words-containing-substring (str len path)
(with-open-file (s path :direction :input)
(do ((line (read-line s nil :eof) (read-line s nil :eof)))
((eql line :eof)) (when (and (> (length line) len)
(search str line))
(format t "~a~... |
Translate this program into Common_Lisp but keep the logic exactly as in PHP. | $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
|
(ql:quickload 'cl-heredoc)
(set-dispatch-macro-character #\# #\> #'cl-heredoc:read-heredoc)
(format t "~A~%" #>eof1>Write whatever (you) "want",
no matter how many lines or what characters until
the magic end sequence has been reached!eof1)
|
Transform the following PHP implementation into Common_Lisp, maintaining the same output and logic. | $address = <<<END
1, High Street,
$town_name,
West Midlands.
WM4 5HD.
END;
|
(ql:quickload 'cl-heredoc)
(set-dispatch-macro-character #\# #\> #'cl-heredoc:read-heredoc)
(format t "~A~%" #>eof1>Write whatever (you) "want",
no matter how many lines or what characters until
the magic end sequence has been reached!eof1)
|
Produce a functionally identical Common_Lisp code for the snippet given in PHP. | while(1)
echo "SPAM\n";
| (defun spam ()
(declare (xargs :mode :program))
(if nil
nil
(prog2$ (cw "SPAM~%")
(spam))))
|
Write the same algorithm in Common_Lisp as shown in this PHP implementation. | $server = "speedtest.tele2.net";
$user = "anonymous";
$pass = "ftptest@example.com";
$conn = ftp_connect($server);
if (!$conn) {
die('unable to connect to: '. $server);
}
$login = ftp_login($conn, $user, $pass);
if (!$login) {
echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass;
} e... | (use-package :ftp)
(with-ftp-connection (conn :hostname "ftp.hq.nasa.gov"
:passive-ftp-p t)
(send-cwd-command conn "/pub/issoutreach/Living in Space Stories (MP3 Files)")
(send-list-command conn t)
(let ((filename "Gravity in the Brain.mp3"))
(retrieve-file conn filename filename ... |
Produce a language-to-language conversion: from PHP to Common_Lisp, same semantics. | <?php
function Y($f) {
$g = function($w) use($f) {
return $f(function() use($w) {
return call_user_func_array($w($w), func_get_args());
});
};
return $g($g);
}
$fibonacci = Y(function($f) {
return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); };
});
echo $fibonacci(10), "... | (defn Y [f]
((fn [x] (x x))
(fn [x]
(f (fn [& args]
(apply (x x) args))))))
(def fac
(fn [f]
(fn [n]
(if (zero? n) 1 (* n (f (dec n)))))))
(def fib
(fn [f]
(fn [n]
(condp = n
0 0
1 1
(+ (f (dec n))
(f (dec (de... |
Convert this PHP block to Common_Lisp, preserving its control flow and logic. | <?php
function columns($arr) {
if (count($arr) == 0)
return array();
else if (count($arr) == 1)
return array_chunk($arr[0], 1);
array_unshift($arr, NULL);
$transpose = call_user_func_array('array_map', $arr);
return array_map('array_filter', $transpose);
}
function beadsort($arr) ... | (defun transpose (remain &optional (ret '()))
(if (null remain)
ret
(transpose (remove-if #'null (mapcar #'cdr remain))
(append ret (list (mapcar #'car remain))))))
(defun bead-sort (xs)
(mapcar #'length (transpose (transpose (mapcar (lambda (x) (make-list x :initial-element 1)) xs)))))
(be... |
Generate an equivalent Common_Lisp version of this PHP code. | class Card
{
protected static $suits = array( '♠', '♥', '♦', '♣' );
protected static $pips = array( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' );
protected $suit;
protected $suitOrder;
protected $pip;
protected $pipOrder;
protected $order;
public function __c... | (defun remove-nth (i xs)
(if (or (zp i) (endp (rest xs)))
(rest xs)
(cons (first xs)
(remove-nth (1- i) (rest xs)))))
(defthm remove-nth-shortens
(implies (consp xs)
(< (len (remove-nth i xs)) (len xs))))
:set-state-ok t
(defun shuffle-r (xs ys state)
(declare (xargs :... |
Generate an equivalent Common_Lisp version of this PHP code. | <?php
class Foo
{
public function __clone()
{
$this->child = clone $this->child;
}
}
$object = new Foo;
$object->some_value = 1;
$object->child = new stdClass;
$object->child->some_value = 1;
$deepcopy = clone $object;
$deepcopy->some_value++;
$deepcopy->child->some_value++;
echo "Object contains... | $ clisp -q
[1]> (setf *print-circle* t)
T
[2]> (let ((a (cons 1 nil))) (setf (cdr a) a))
#1=(1 . #1#)
[3]> (read-from-string "#1=(1 . #1#)")
#1=(1 . #1#)
|
Convert this PHP snippet to Common_Lisp and keep its semantics consistent. | <?php
class Foo
{
public function __clone()
{
$this->child = clone $this->child;
}
}
$object = new Foo;
$object->some_value = 1;
$object->child = new stdClass;
$object->child->some_value = 1;
$deepcopy = clone $object;
$deepcopy->some_value++;
$deepcopy->child->some_value++;
echo "Object contains... | $ clisp -q
[1]> (setf *print-circle* t)
T
[2]> (let ((a (cons 1 nil))) (setf (cdr a) a))
#1=(1 . #1#)
[3]> (read-from-string "#1=(1 . #1#)")
#1=(1 . #1#)
|
Change the following PHP code into Common_Lisp without altering its purpose. | function inOrder($arr){
for($i=0;$i<count($arr);$i++){
if(isset($arr[$i+1])){
if($arr[$i] > $arr[$i+1]){
return false;
}
}
}
return true;
}
function permute($items, $perms = array( )) {
if (empty($items)) {
if(inOrder($perms)){
return $perms;
}
} else {
for ($i = count($items) ... | (use '[clojure.contrib.combinatorics :only (permutations)])
(defn permutation-sort [s]
(first (filter (partial apply <=) (permutations s))))
(permutation-sort [2 3 5 3 5])
|
Write a version of this PHP function in Common_Lisp with identical behavior. | <?php
function printLastSundayOfAllMonth($year)
{
$months = array(
'January', 'February', 'March', 'April', 'June', 'July',
'August', 'September', 'October', 'November', 'December');
foreach ($months as $month) {
echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ... | (defun last-sundays (year)
(loop for month from 1 to 12
for last-month-p = (= month 12)
for next-month = (if last-month-p 1 (1+ month))
for year-of-next-month = (if last-month-p (1+ year) year)
for 1st-day-next-month = (encode-universal-time 0 0 0 1 next-month year-of-next-month 0)
... |
Please provide an equivalent version of this PHP code in Common_Lisp. | <?php
function printLastSundayOfAllMonth($year)
{
$months = array(
'January', 'February', 'March', 'April', 'June', 'July',
'August', 'September', 'October', 'November', 'December');
foreach ($months as $month) {
echo $month . ': ' . date('Y-m-d', strtotime('last sunday of ' . $month ... | (defun last-sundays (year)
(loop for month from 1 to 12
for last-month-p = (= month 12)
for next-month = (if last-month-p 1 (1+ month))
for year-of-next-month = (if last-month-p (1+ year) year)
for 1st-day-next-month = (encode-universal-time 0 0 0 1 next-month year-of-next-month 0)
... |
Produce a language-to-language conversion: from PHP to Common_Lisp, same semantics. | <?php
$attributesTotal = 0;
$count = 0;
while($attributesTotal < 75 || $count < 2) {
$attributes = [];
foreach(range(0, 5) as $attribute) {
$rolls = [];
foreach(range(0, 3) as $roll) {
$rolls[] = rand(1, 6);
}
sort($rolls);
array_shift... | (defpackage :rpg-generator
(:use :cl)
(:export :generate))
(in-package :rpg-generator)
(defun sufficient-scores-p (scores)
(and (>= (apply #'+ scores) 75)
(>= (count-if #'(lambda (n) (>= n 15)) scores) 2)))
(defun gen-score ()
(apply #'+ (rest (sort (loop repeat 4 collect (1+ (random 6))) #'<))))
(defu... |
Write the same algorithm in Common_Lisp as shown in this PHP implementation. | <?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)
$... | (defun longest-increasing-subseq (list)
(let ((subseqs nil))
(dolist (item list)
(let ((longest-so-far (longest-list-in-lists (remove-if-not #'(lambda (l) (> item (car l))) subseqs))))
(push (cons item longest-so-far) subseqs)))
(reverse (longest-list-in-lists subseqs))))
(defun longest-list-in-lists ... |
Transform the following PHP implementation into Common_Lisp, maintaining the same output and logic. | <?php
$varname = rtrim(fgets(STDIN)); # type in "foo" on standard input
$$varname = 42;
echo "$foo\n"; # prints "42"
?>
| (setq var-name (read))
(set var-name 1)
|
Preserve the algorithm and functionality while converting the code from PHP to Common_Lisp. | <?php
function eval_with_x($code, $a, $b) {
$x = $a;
$first = eval($code);
$x = $b;
$second = eval($code);
return $second - $first;
}
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>
| (defun eval-with-x (program a b)
(let ((at-a (eval `(let ((x ',a)) ,program)))
(at-b (eval `(let ((x ',b)) ,program))))
(- at-b at-a)))
|
Rewrite the snippet below in Common_Lisp so it works the same as the original PHP code. | <?php
function eval_with_x($code, $a, $b) {
$x = $a;
$first = eval($code);
$x = $b;
$second = eval($code);
return $second - $first;
}
echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>
| (defun eval-with-x (program a b)
(let ((at-a (eval `(let ((x ',a)) ,program)))
(at-b (eval `(let ((x ',b)) ,program))))
(- at-b at-a)))
|
Port the following code from PHP to Common_Lisp with equivalent syntax and logic. | <?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);
| (eval '(+ 4 5))
|
Change the programming language of this snippet from PHP to Common_Lisp without modifying what it does. | <?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);
| (eval '(+ 4 5))
|
Please provide an equivalent version of this PHP code in Common_Lisp. | 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 = [];
... | (defstruct alternation
(alternatives nil :type list))
(defun alternatives-end-positions (string start)
(assert (char= (char string start) #\{))
(loop with level = 0
with end-positions
with escapep and commap
for index from start below (length string)
for c = (char string index)
... |
Write the same algorithm in Common_Lisp as shown in this PHP implementation. | $img = imagegrabscreen();
$color = imagecolorat($im, 10, 50);
imagedestroy($im);
| (defn get-color-at [x y]
(.getPixelColor (java.awt.Robot.) x y))
|
Change the programming language of this snippet from PHP to Common_Lisp without modifying what it does. | $lst = new SplDoublyLinkedList();
foreach (array(1,20,64,72,48,75,96,55,42,74) as $v)
$lst->push($v);
foreach (strandSort($lst) as $v)
echo "$v ";
function strandSort(SplDoublyLinkedList $lst) {
$result = new SplDoublyLinkedList();
while (!$lst->isEmpty()) {
$sorted = new SplDoublyLinkedList();... | (defun strand-sort (l cmp)
(if l
(let* ((l (reverse l))
(o (list (car l))) n)
(loop for i in (cdr l) do
(push i (if (funcall cmp (car o) i) n o)))
(merge 'list o (strand-sort n cmp) #'<))))
(let ((r (loop repeat 15 collect (random 10))))
(print r)
(print (strand-sort r #'<)))
|
Generate a Common_Lisp translation of this PHP snippet without changing its computational steps. | <?php
$doc = DOMDocument::loadXML('<inventory title="OmniCorp Store #45x10^3">...</inventory>');
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query('//item');
$result = $nodelist->item(0);
$nodelist = $xpath->query('//price');
for($i = 0; $i < $nodelist->length; $i++)
{
print $doc->saveXML($nodelist->item($i... | (dolist (system '(:xpath :cxml-stp :cxml))
(asdf:oos 'asdf:load-op system))
(defparameter *doc* (cxml:parse-file "xml" (stp:make-builder)))
(xpath:first-node (xpath:evaluate "/inventory/section[1]/item[1]" *doc*))
(xpath:do-node-set (node (xpath:evaluate "/inventory/section/item/price/text()" *doc*))
(format t "... |
Ensure the translated Common_Lisp code behaves exactly like the original PHP snippet. | <?php
class Example {
function foo() {
echo "this is foo\n";
}
function bar() {
echo "this is bar\n";
}
function __call($name, $args) {
echo "tried to handle unknown method $name\n";
if ($args)
echo "it had arguments: ", implode(', ', $args), "\n";
}
}
$example = new Example();
$exam... | (defgeneric do-something (thing)
(:documentation "Do something to thing."))
(defmethod no-applicable-method ((method (eql #'do-something)) &rest args)
(format nil "No method for ~w on ~w." method args))
(defmethod do-something ((thing (eql 3)))
(format nil "Do something to ~w." thing))
|
Convert this PHP block to Common_Lisp, preserving its control flow and logic. | <?php
function hashJoin($table1, $index1, $table2, $index2) {
foreach ($table1 as $s)
$h[$s[$index1]][] = $s;
foreach ($table2 as $r)
foreach ($h[$r[$index2]] as $s)
$result[] = array($s, $r);
return $result;
}
$table1 = array(array(27, "Jonah"),
array(18, "Alan"),
... | (defparameter *table-A* '((27 "Jonah") (18 "Alan") (28 "Glory") (18 "Popeye") (28 "Alan")))
(defparameter *table-B* '(("Jonah" "Whales") ("Jonah" "Spiders") ("Alan" "Ghosts") ("Alan" "Zombies") ("Glory" "Buffy")))
(defparameter *hash-table* (make-hash-table :test #'equal))
(loop for (i r) in *table-A*
for value... |
Translate the given PHP code snippet into Common_Lisp without altering its behavior. | <?php
define('MINEGRID_WIDTH', 6);
define('MINEGRID_HEIGHT', 4);
define('MINESWEEPER_NOT_EXPLORED', -1);
define('MINESWEEPER_MINE', -2);
define('MINESWEEPER_FLAGGED', -3);
define('MINESWEEPER_FLAGGED_MINE', -4);
define('ACTIVATED_MINE', -5);
function check_field($field) {
if ($field === MI... | (defclass minefield ()
((mines :initform (make-hash-table :test #'equal))
(width :initarg :width)
(height :initarg :height)
(grid :initarg :grid)))
(defun make-minefield (width height num-mines)
(let ((minefield (make-instance 'minefield
:width width
... |
Write the same code in Common_Lisp as shown below in PHP. | <?php
class Example {
function foo($x) {
return 42 + $x;
}
}
$example = new Example();
$name = 'foo';
echo $example->$name(5), "\n"; // prints "47"
echo call_user_func(array($example, $name), 5), "\n";
?>
| (funcall (intern "SOME-METHOD") my-object a few arguments)
|
Generate an equivalent AutoHotKey version of this Java code. | import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class AbbreviationsEasy {
private static final Scanner input = new Scanner(System.in);
private static final String COMMAND_TABLE
= " Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy... |
str =
(
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix M... |
Rewrite this program in AutoHotKey while keeping its functionality equivalent to the Java version. | 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);
... | StoogeSort(L, i:=1, j:=""){
if !j
j := L.MaxIndex()
if (L[j] < L[i]){
temp := L[i]
L[i] := L[j]
L[j] := temp
}
if (j - i > 1){
t := floor((j - i + 1)/3)
StoogeSort(L, i, j-t)
StoogeSort(L, i+t, j)
StoogeSort(L, i, j-t)
}
return L
}
|
Change the programming language of this snippet from Java to AutoHotKey without modifying what it does. | import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TruncFile {
public static void main(String[] args) throws IOException{
if(args.length < 2){
System.out.println("Usage: java TruncFile fileName newSize");
return;
}
FileChannel outChan = new F... | truncFile("S:\Portables\AutoHotkey\My Scripts\Other_Codes\motion2.ahk", 1200)
return
truncFile(file, length_bytes){
if !FileExist(file)
msgbox, File doesn't exists.
FileGetSize, fsize, % file, B
if (length_bytes>fsize)
msgbox, New truncated size more than current file size
f := FileOpen(file, "rw")
f.length :... |
Write a version of this Java function in AutoHotKey with identical behavior. | import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TruncFile {
public static void main(String[] args) throws IOException{
if(args.length < 2){
System.out.println("Usage: java TruncFile fileName newSize");
return;
}
FileChannel outChan = new F... | truncFile("S:\Portables\AutoHotkey\My Scripts\Other_Codes\motion2.ahk", 1200)
return
truncFile(file, length_bytes){
if !FileExist(file)
msgbox, File doesn't exists.
FileGetSize, fsize, % file, B
if (length_bytes>fsize)
msgbox, New truncated size more than current file size
f := FileOpen(file, "rw")
f.length :... |
Convert this Java snippet to AutoHotKey and keep its semantics consistent. | public static void shell(int[] a) {
int increment = a.length / 2;
while (increment > 0) {
for (int i = increment; i < a.length; i++) {
int j = i;
int temp = a[i];
while (j >= increment && a[j - increment] > temp) {
a[j] = a[j - increment];
j = j - increment;
}
a[j] = temp;
}
if (increment... | MsgBox % ShellSort("")
MsgBox % ShellSort("xxx")
MsgBox % ShellSort("3,2,1")
MsgBox % ShellSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z")
MsgBox % ShellSort("12,11,10,9,8,4,5,6,7,3,2,1,10,13,14,15,19,17,18,16,20,10")
ShellSort(var) {
StringSplit a, var, `,
inc := a0
... |
Generate an equivalent AutoHotKey version of this Java code. | 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 FileRe... | FileReadLine, OutputVar, filename.txt, 7
if ErrorLevel
MsgBox, There was an error reading the 7th line of the file
|
Convert the following code from Java to AutoHotKey, ensuring the logic remains intact. | 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 FileRe... | FileReadLine, OutputVar, filename.txt, 7
if ErrorLevel
MsgBox, There was an error reading the 7th line of the file
|
Translate this program into AutoHotKey but keep the logic exactly as in Java. | import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class Main
{
public static void main(String[] args) throws UnsupportedEncodingException
{
String normal = "http:
String encoded = URLEncoder.encode(normal, "utf-8");
System.out.println(encoded);
}
}
| MsgBox, % UriEncode("http://foo bar/")
UriEncode(Uri)
{
VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0)
StrPut(Uri, &Var, "UTF-8")
f := A_FormatInteger
SetFormat, IntegerFast, H
While Code := NumGet(Var, A_Index - 1, "UChar")
If (Code >= 0x30 && Code <= 0x39
|| Code >= 0x41 && Code <= 0x5A
|| Code >= 0x61... |
Write the same code in AutoHotKey as shown below in Java. | import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class Main
{
public static void main(String[] args) throws UnsupportedEncodingException
{
String normal = "http:
String encoded = URLEncoder.encode(normal, "utf-8");
System.out.println(encoded);
}
}
| MsgBox, % UriEncode("http://foo bar/")
UriEncode(Uri)
{
VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0)
StrPut(Uri, &Var, "UTF-8")
f := A_FormatInteger
SetFormat, IntegerFast, H
While Code := NumGet(Var, A_Index - 1, "UChar")
If (Code >= 0x30 && Code <= 0x39
|| Code >= 0x41 && Code <= 0x5A
|| Code >= 0x61... |
Convert this Java snippet to AutoHotKey and keep its semantics consistent. | 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[... |
LU_decomposition(A){
P := Pivot(A)
A_ := Multiply_Matrix(P, A)
U := [], L := [], n := A_.Count()
loop % n {
i := A_Index
loop % n {
j := A_Index
Sigma := 0, k := 1
while (k <= i-1)
Sigma += (U[k, j] * L[i, k]), k++
... |
Translate the given Java code snippet into AutoHotKey without altering its behavior. | module OptionalParameters
{
typedef Type<String >.Orderer as ColumnOrderer;
typedef Type<String[]>.Orderer as RowOrderer;
static String[][] sort(String[][] table,
ColumnOrderer? orderer = Null,
Int column = 0,
... | Gosub start
sort_table("Text", column := 2, reverse := 1)
Sleep, 2000
sort_table("Integer", column := 2, reverse := 1)
Return
start:
Gui, Add, ListView, r20 w200, 1|2|3
data =
(
1,2,3
b,q,z
c,z,z
)
Loop, Parse, data, `n
{
StringSplit, row, A_LoopField, `,
LV_Add(row, row1, row2, row3)
... |
Convert this Java snippet to AutoHotKey and keep its semantics consistent. |
import java.util.*;
import java.io.*;
public class TPKA {
public static void main(String... args) {
double[] input = new double[11];
double userInput = 0.0;
Scanner in = new Scanner(System.in);
for(int i = 0; i < 11; i++) {
System.out.print("Please enter a number: ");
String s = in.nextLine();
try ... | seq := [1,2,3,4,5,6,7,8,9,10,11]
MsgBox % result := TPK(seq, 400)
return
TPK(s, num){
for i, v in reverse(s)
res .= v . " : " . ((x:=f(v)) > num ? "OVERFLOW" : x ) . "`n"
return res
}
reverse(s){
Loop % s.Count()
s.InsertAt(A_Index, s.pop())
return s
}
f(x){
return Sqrt(x) + 5* (x**... |
Write the same algorithm in AutoHotKey as shown in this Java implementation. | import java.util.function.Consumer;
public class RateCounter {
public static void main(String[] args) {
for (double d : benchmark(10, x -> System.out.print(""), 10))
System.out.println(d);
}
static double[] benchmark(int n, Consumer<Integer> f, int arg) {
double[] timings = ne... | SetBatchLines, -1
Tick := A_TickCount
Loop, 1000000 {
Random, x, 1, 1000000
Random, y, 1, 1000000
gcd(x, y)
}
t := A_TickCount - Tick
MsgBox, % t / 1000 " Seconds elapsed.`n" Round(1 / (t / 1000000000), 0) " Loop iterations per second."
gcd(a, b) {
while b
t := b, b := Mod(a, b), a ... |
Generate an equivalent AutoHotKey version of this Java code. | public static void main(String[] args) {
int[][] matrix = {{1, 3, 7, 8, 10},
{2, 4, 16, 14, 4},
{3, 1, 9, 18, 11},
{12, 14, 17, 18, 20},
{7, 1, 3, 9, 5}};
int sum = 0;
for (int row = 1; row < matrix.length; row++) {
... | matrx :=[[1,3,7,8,10]
,[2,4,16,14,4]
,[3,1,9,18,11]
,[12,14,17,18,20]
,[7,1,3,9,5]]
sumA := sumB := sumD := sumAll := 0
for r, obj in matrx
for c, val in obj
sumAll += val
,sumA += r<c ? val : 0
,sumB += r>c ? val : 0
,sumD += r=c ? val : 0
MsgBox % result := "sum above diagonal = " sumA
. "`nsum be... |
Write the same algorithm in AutoHotKey as shown in this Java implementation. | import java.awt.*;
import java.awt.geom.Path2D;
import javax.swing.*;
public class PythagorasTree extends JPanel {
final int depthLimit = 7;
float hue = 0.15f;
public PythagorasTree() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
}
private void drawTree(... | pToken := Gdip_Startup()
gdip1()
Pythagoras_tree(600, 600, 712, 600, 1)
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
OnExit, Exit
return
Pythagoras_tree(x1, y1, x2, y2, depth){
global G, hwnd1, hdc, Width, Height
if (depth > 7)
Return
Pen := Gdip_CreatePen(0xFF808080, 1)
Brush1 := Gdip... |
Can you help me rewrite this code in AutoHotKey instead of Java, keeping it the same logically? | public class RepString {
static final String[] input = {"1001110011", "1110111011", "0010010010",
"1010101010", "1111111111", "0100101101", "0100100", "101", "11",
"00", "1", "0100101"};
public static void main(String[] args) {
for (String s : input)
System.out.printf("%s :... | In := ["1001110011", "1110111011", "0010010010", "1010101010"
, "1111111111", "0100101101", "0100100", "101", "11", "00", "1"]
for k, v in In
Out .= RepString(v) "`t" v "`n"
MsgBox, % Out
RepString(s) {
Loop, % StrLen(s) // 2 {
i := A_Index
Loop, Parse, s
{
pos := Mod(A_Index, i)
if (A_LoopField !=... |
Convert this Java block to AutoHotKey, preserving its control flow and logic. | public class Topswops {
static final int maxBest = 32;
static int[] best;
static private void trySwaps(int[] deck, int f, int d, int n) {
if (d > best[n])
best[n] = d;
for (int i = n - 1; i >= 0; i--) {
if (deck[i] == -1 || deck[i] == i)
break;
... | Topswops(Obj, n){
R := []
for i, val in obj{
if (i <=n)
res := val (A_Index=1?"":",") res
else
res .= "," val
}
Loop, Parse, res, `,
R[A_Index]:= A_LoopField
return R
}
|
Convert this Java snippet to AutoHotKey and keep its semantics consistent. | public class AntiPrimesPlus {
static int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
if (i == n / i)
count++;
else
count += 2;
}
}
return c... | MAX := 15
next := 1, i := 1
while (next <= MAX)
if (next = countDivisors(A_Index))
Res.= A_Index ", ", next++
MsgBox % "The first " MAX " terms of the sequence are:`n" Trim(res, ", ")
return
countDivisors(n){
while (A_Index**2 <= n)
if !Mod(n, A_Index)
count += (A_Index = n/A_Index) ? 1 : 2
return count
}
|
Preserve the algorithm and functionality while converting the code from Java to AutoHotKey. | import java.awt.*;
import java.awt.geom.Path2D;
import static java.lang.Math.pow;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.event.*;
public class SuperEllipse extends JPanel implements ChangeListener {
private double exp = 2.5;
public SuperEllipse() {
setPreferredSize(new Di... | n := 2.5
a := 200
b := 200
SuperEllipse(n, a, b)
return
SuperEllipse(n, a, b){
global
pToken := Gdip_Startup()
π := 3.141592653589793, oCoord := [], oX := [], oY := []
nn := 2/n
loop 361
{
t := (A_Index-1) * π/180
x := abs(cos(t))**nn * a * sgn(cos(t))
y := a... |
Port the following code from Java to AutoHotKey with equivalent syntax and logic. | public class OddWord {
interface CharHandler {
CharHandler handle(char c) throws Exception;
}
final CharHandler fwd = new CharHandler() {
public CharHandler handle(char c) {
System.out.print(c);
return (Character.isLetter(c) ? fwd : rev);
}
};
class Reverser extends Thread implements Ch... | str := "what,is,the
loop, parse, str
if (A_LoopField ~= "[[:punct:]]")
res .= A_LoopField, toggle:=!toggle
else
res := toggle ? RegExReplace(res, ".*[[:punct:]]\K", A_LoopField ) : res A_LoopField
MsgBox % res
|
Write a version of this Java function in AutoHotKey with identical behavior. | import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
public class SelfReferentialSequence {
static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);
public static void main(String[] args) {
Seeds res = IntStream.range(0, 1000_000)
... |
#NoEnv
SetBatchlines -1
ListLines Off
Process, Priority,, high
iterations := 0, seed := "Seeds: "
Loop 1000000
If (newIterations := CountSubString(list := ListSequence(A_Index), "`n")) > iterations
iterations := newiterations
,final := "`nIterations: " iterations+1 "`nSequence:`n`n" A_Index "`n" list
,seed :=... |
Can you help me rewrite this code in AutoHotKey instead of Java, keeping it the same logically? | int l = 300;
void setup() {
size(400, 400);
background(0, 0, 255);
stroke(255);
translate(width/2.0, height/2.0);
translate(-l/2.0, l*sqrt(3)/6.0);
for (int i = 1; i <= 3; i++) {
kcurve(0, l);
rotate(radians(120));
translate(-l, 0);
}
}
void kcurve(float x1, float x2) {
float s = (x2... | gdip1()
KochX := 0, KochY := 0
Koch(0, 0, A_ScreenWidth, A_ScreenHeight, 4, Arr:=[])
xmin := xmax := ymin := ymax := 0
for i, point in Arr
{
xmin := A_Index = 1 ? point.x : xmin < point.x ? xmin : point.x
xmax := point.x > xmax ? point.x : xmax
ymin := A_Index = 1 ? point.y : ymin < point.y ? ymin : point.y
ymax :=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.