Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#include <windows.h> #include <iostream> #include <string> using namespace std; class lastSunday { public: lastSunday() { m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: "; m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";...
LastSundays[year_] := Table[Last@ DayRange[{year, i}, DatePlus[{year, i}, {{1, "Month"}, {-1, "Day"}}], Sunday], {i, 12}] LastSundays[2013]
Transform the following C++ implementation into Mathematica, maintaining the same output and logic.
#include <algorithm> #include <chrono> #include <iostream> #include <random> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it...
Clear[RandomLatinSquare] RandomLatinSquare[n_] := Module[{out, ord}, out = Table[RotateLeft[Range[n], i], {i, n}]; out = RandomSample[out]; ord = RandomSample[Range[n]]; out = out[[All, ord]]; out ] RandomLatinSquare[5] // Grid
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#include <algorithm> #include <fstream> #include <iostream> #include <set> #include <string> #include <vector> std::set<std::string> load_dictionary(const std::string& filename) { std::ifstream in(filename); if (!in) throw std::runtime_error("Cannot open file " + filename); std::set<std::string> w...
ClearAll[Teacuppable] TeacuppableHelper[set_List] := Module[{f, s}, f = First[set]; s = StringRotateLeft[f, #] & /@ Range[Length[set]]; Sort[s] == Sort[set] ] Teacuppable[set_List] := Module[{ss, l}, l = StringLength[First[set]]; ss = Subsets[set, {l}]; Select[ss, TeacuppableHelper] ] s = Import["http:/...
Convert this C++ snippet to Mathematica and keep its semantics consistent.
#include <iostream> #include <vector> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { printf("Base %2d:", base); for (int i = 0; i < count; i++) { ...
ClearAll[Fairshare] Fairshare[n_List, b_Integer : 2] := Fairshare[#, b] & /@ n Fairshare[n_Integer, b_Integer : 2] := Mod[Total[IntegerDigits[n, b]], b] Fairshare[Range[0, 24], 2] Fairshare[Range[0, 24], 3] Fairshare[Range[0, 24], 5] Fairshare[Range[0, 24], 11]
Write a version of this C++ function in Mathematica with identical behavior.
#include <functional> #include <iostream> #include <sstream> #include <vector> std::string to(int n, int b) { static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::stringstream ss; while (n > 0) { auto rem = n % b; n = n / b; ss << BASE[rem]; } auto fwd = ss.str(...
ClearAll[EstheticNumbersRangeHelper, EstheticNumbersRange] EstheticNumbersRangeHelper[power_, mima : {mi_, max_}, b_ : 10] := Module[{steps, cands}, steps = Tuples[{-1, 1}, power - 1]; steps = Accumulate[Prepend[#, 0]] & /@ steps; cands = Table[Select[# + ConstantArray[s, power] & /@ steps, AllTrue[Between[{0, b ...
Write the same code in Mathematica as shown below in C++.
#include <iostream> bool ispr(unsigned int n) { if ((n & 1) == 0 || n < 2) return n == 2; for (unsigned int j = 3; j * j <= n; j += 2) if (n % j == 0) return false; return true; } int main() { unsigned int c = 0, nc, pc = 9, i, a, b, l, ps[128]{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, nxt[128]; while (true...
Sort[Select[FromDigits/@Subsets[Range[9,1,-1],{1,\[Infinity]}],PrimeQ]]
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#include <algorithm> #include <ctime> #include <iostream> #include <cstdlib> #include <string> using namespace std; int main() { srand(time(0)); unsigned int attributes_total = 0; unsigned int count = 0; int attributes[6] = {}; int rolls[4] = {}; while(attributes_total < 75 || count ...
valid = False; While[! valid, try = Map[Total[TakeLargest[#, 3]] &, RandomInteger[{1, 6}, {6, 4}]]; If[Total[try] > 75 && Count[try, _?(GreaterEqualThan[15])] >= 2, valid = True; ] ] {Total[try], try}
Generate an equivalent Mathematica version of this C++ code.
#include <iostream> #include <vector> using Sequence = std::vector<int>; std::ostream& operator<<(std::ostream& os, const Sequence& v) { os << "[ "; for (const auto& e : v) { std::cout << e << ", "; } os << "]"; return os; } int next_in_cycle(const Sequence& s, size_t i) { return s[i % s.size()]; } ...
ClearAll[KolakoskiGen] KolakoskiGen[start_List, its_Integer] := Module[{c, s, k, cnext, sk}, s = {}; k = 1; c = start; Do[ cnext = First[c]; c = RotateLeft[c]; AppendTo[s, cnext]; sk = s[[k]]; If[sk > 1, s = Join[s, ConstantArray[cnext, sk - 1]] ]; k += 1; , {its} ]; s ] ...
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { ...
Take[SplitBy[SortBy[{DivisorSigma[0, #], #} & /@ Range[100000], First], First][[All, 1]], 15] // Grid
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <algorithm> #include <locale> class Sparkline { public: Sparkline(std::wstring &cs) : charset( cs ){ } virtual ~Sparkline(){ } void print(std::string spark){ const char *delim = "...
toSparkline[data_String] := FromCharacterCode[Round[7 Rescale@Flatten@ImportString[data, "Table", "FieldSeparators" -> {" ", ","}]] + 16^^2581];
Produce a functionally identical Mathematica code for the snippet given in C++.
#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 ...
LongestAscendingSequence/@{{3,2,6,4,5,1},{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}}
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int main(int argc, char** argv) { const int min_length = 9; const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std...
dict = Once[Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]]; dict //= StringSplit[#,"\n"]&; dict //= Select[StringLength/*GreaterEqualThan[9]]; firsts9 = Characters[dict][[All,;;9]]; words = StringJoin[Diagonal[firsts9,-#]]&/@Range[0,Length[firsts9]-9]; Intersect...
Write a version of this C++ function in Mathematica with identical behavior.
#include <iomanip> #include <iostream> bool odd_square_free_semiprime(int n) { if ((n & 1) == 0) return false; int count = 0; for (int i = 3; i * i <= n; i += 2) { for (; n % i == 0; n /= i) { if (++count > 1) return false; } } return count == 1; ...
n = 1000; primes = Most@NestWhileList[NextPrime, 3, # < n/3 &]; reduceList[x_List, n_] := TakeWhile[Rest[x], # < n/First[x] &]; q = Rest /@ NestWhileList[reduceList[#, n] &, primes, Length@# > 2 &]; semiPrimes = Sort@Flatten@MapThread[Times, {q, primes[[;; Length@q]]}]; Partition[TakeWhile[semiPrimes, # < 1000 &],...
Keep all operations the same but rewrite the snippet in Mathematica.
#include <iomanip> #include <iostream> bool odd_square_free_semiprime(int n) { if ((n & 1) == 0) return false; int count = 0; for (int i = 3; i * i <= n; i += 2) { for (; n % i == 0; n /= i) { if (++count > 1) return false; } } return count == 1; ...
n = 1000; primes = Most@NestWhileList[NextPrime, 3, # < n/3 &]; reduceList[x_List, n_] := TakeWhile[Rest[x], # < n/First[x] &]; q = Rest /@ NestWhileList[reduceList[#, n] &, primes, Length@# > 2 &]; semiPrimes = Sort@Flatten@MapThread[Times, {q, primes[[;; Length@q]]}]; Partition[TakeWhile[semiPrimes, # < 1000 &],...
Transform the following C++ implementation into Mathematica, maintaining the same output and logic.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <vector> #include <primesieve.hpp> auto get_primes_by_digits(uint64_t limit) { primesieve::iterator pi; std::vector<std::vector<uint64_t>> primes_by_digits; std::vector<uint64_t> primes; for (uint6...
ClearAll[PrimesDecade] PrimesDecade[n_Integer] := Module[{bounds}, bounds = {PrimePi[10^n] + 1, PrimePi[10^(n + 1) - 1]}; Prime[Range @@ bounds] ] ds = Union @@ Table[Union[Times @@@ Tuples[PrimesDecade[d], 2]], {d, 0, 4}]; Multicolumn[Take[ds, 100], {Automatic, 8}, Appearance -> "Horizontal"] sel = Min /@ Gath...
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <vector> #include <primesieve.hpp> auto get_primes_by_digits(uint64_t limit) { primesieve::iterator pi; std::vector<std::vector<uint64_t>> primes_by_digits; std::vector<uint64_t> primes; for (uint6...
ClearAll[PrimesDecade] PrimesDecade[n_Integer] := Module[{bounds}, bounds = {PrimePi[10^n] + 1, PrimePi[10^(n + 1) - 1]}; Prime[Range @@ bounds] ] ds = Union @@ Table[Union[Times @@@ Tuples[PrimesDecade[d], 2]], {d, 0, 4}]; Multicolumn[Take[ds, 100], {Automatic, 8}, Appearance -> "Horizontal"] sel = Min /@ Gath...
Can you help me rewrite this code in Mathematica instead of C++, keeping it the same logically?
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<u...
ClearAll[a] a[1] = 1; a[n_?(GreaterThan[1])] := a[n] = 1/(2 Floor[a[n - 1]] + 1 - a[n - 1]) a /@ Range[20] ClearAll[a] a = 1; n = 1; Dynamic[n] done = False; While[! done, a = 1/(2 Floor[a] + 1 - a); n++; If[a == 83116/51639, Print[n]; Break[]; ] ]
Translate this program into Mathematica but keep the logic exactly as in C++.
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<u...
ClearAll[a] a[1] = 1; a[n_?(GreaterThan[1])] := a[n] = 1/(2 Floor[a[n - 1]] + 1 - a[n - 1]) a /@ Range[20] ClearAll[a] a = 1; n = 1; Dynamic[n] done = False; While[! done, a = 1/(2 Floor[a] + 1 - a); n++; If[a == 83116/51639, Print[n]; Break[]; ] ]
Generate an equivalent Mathematica version of this C++ code.
#include <iostream> #include <vector> #include <algorithm> #include <string> template <typename T> void print(const std::vector<T> v) { std::cout << "{ "; for (const auto& e : v) { std::cout << e << " "; } std::cout << "}"; } template <typename T> auto orderDisjointArrayItems(std::vector<T> M, std::vector...
order[m_, n_] := ReplacePart[m, MapThread[ Rule, {Position[m, Alternatives @@ n][[;; Length[n]]], n}]]; Print[StringRiffle[ order[{"the", "cat", "sat", "on", "the", "mat"}, {"mat", "cat"}]]]; Print[StringRiffle[ order[{"the", "cat", "sat", "on", "the", "mat"}, {"cat", "mat"}]]]; Print[Strin...
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot ope...
dict=Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt","String"]; dict//=StringSplit[#,"\n"]&; chars=CharacterRange["A","Z"]~Join~CharacterRange["a","z"]; chars//=Select[ToCharacterCode/*First/*PrimeQ]; Select[dict,StringMatchQ[Repeated[Alternatives@@chars]]]//Column...
Generate an equivalent Mathematica version of this C++ code.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot ope...
dict=Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt","String"]; dict//=StringSplit[#,"\n"]&; chars=CharacterRange["A","Z"]~Join~CharacterRange["a","z"]; chars//=Select[ToCharacterCode/*First/*PrimeQ]; Select[dict,StringMatchQ[Repeated[Alternatives@@chars]]]//Column...
Write a version of this C++ function in Mathematica with identical behavior.
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> unsigned int reverse(unsigned int base, unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= base) rev = rev * base + (n % base); return rev; } class palindrome_generator { public: explicit pal...
Select[Range[999], PrimeQ[#] \[And] PalindromeQ[#] &]
Convert the following code from C++ to Mathematica, ensuring the logic remains intact.
#include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <string> unsigned int reverse(unsigned int base, unsigned int n) { unsigned int rev = 0; for (; n > 0; n /= base) rev = rev * base + (n % base); return rev; } class palindrome_generator { public: explicit pal...
Select[Range[999], PrimeQ[#] \[And] PalindromeQ[#] &]
Translate the given C++ code snippet into Mathematica without altering its behavior.
#include <iomanip> #include <iostream> #include <numeric> #include <sstream> bool duffinian(int n) { if (n == 2) return false; int total = 1, power = 2, m = n; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (int p = 3; p * p <= n; p += 2) { int sum = 1; f...
ClearAll[DuffianQ] DuffianQ[n_Integer] := CompositeQ[n] \[And] CoprimeQ[DivisorSigma[1, n], n] dns = Select[DuffianQ][Range[1000000]]; Take[dns, UpTo[50]] triplets = ToString[dns[[#]]] <> "\[LongDash]" <> ToString[dns[[# + 2]]] & /@ SequencePosition[Differences[dns], {1, 1}][[All, 1]] Multicolumn[triplets, {Automatic, ...
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#include <iomanip> #include <iostream> #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> using integer = boost::multiprecision::cpp_int; using rational = boost::rational<integer>; integer sylvester_next(const integer& n) { return n * n - n + 1; } int main() { std::cout << "First 10 el...
Rest[Nest[Append[#, (Times @@ #) + 1] &, {1}, 10]] N[Total[1/%], 250]
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#include <iomanip> #include <iostream> #include <boost/rational.hpp> #include <boost/multiprecision/gmp.hpp> using integer = boost::multiprecision::mpz_int; using rational = boost::rational<integer>; class harmonic_generator { public: rational next() { rational result = term_; term_ += rational(1,...
nums = HarmonicNumber[Range[15000]]; nums[[;; 20]] LengthWhile[nums, LessEqualThan[#]] + 1 & /@ Range[10]
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#include <fstream> #include <iostream> #include <locale> using namespace std; int main(void) { std::locale::global(std::locale("")); std::cout.imbue(std::locale()); ifstream in("input.txt"); wchar_t c; while ((c = in.get()) != in.eof()) wcout<<c; in.close(); return EXIT_...
str = OpenRead["file.txt"]; ToString[Read[str, "Character"], CharacterEncoding -> "UTF-8"]
Change the following C++ code into Mathematica without altering its purpose.
#include "stdafx.h" #include <windows.h> #include <stdlib.h> const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject(...
ClearAll[MakePathFunction] MakePathFunction[{path_, acumpath_}] := Module[{f1, f2, f3, pf, n = Length[path]}, f1 = MapThread[{#1/2, #2 + 0.5 < z <= #2 + 1} &, {acumpath, n - Range[n + 1]}]; f2 = MapThread[{#1/2 + #2 Sqrt[1/4 - (z - #3)^2], #3 < z <= #3 + 1/2} &, {acumpath // Most, path, n - Range[n]...
Translate this program into Mathematica but keep the logic exactly as in C++.
#include <iostream> void f(int n) { if (n < 1) { return; } int i = 1; while (true) { int sq = i * i; while (sq > n) { sq /= 10; } if (sq == n) { printf("%3d %9d %4d\n", n, i * i, i); return; } i++; } } int...
max = 49; maxlen = IntegerLength[max]; results = <||>; Do[ sq = i^2; id = IntegerDigits[sq]; starts = DeleteDuplicates[Take[id, UpTo[#]] & /@ Range[maxlen]]; starts //= Map[FromDigits]; starts //= Select[LessEqualThan[max]]; Do[ If[! KeyExistsQ[results, s], results = AssociateTo[results, s -> i^2] ] ...
Port the following code from C++ to Mathematica with equivalent syntax and logic.
#include <iostream> void f(int n) { if (n < 1) { return; } int i = 1; while (true) { int sq = i * i; while (sq > n) { sq /= 10; } if (sq == n) { printf("%3d %9d %4d\n", n, i * i, i); return; } i++; } } int...
max = 49; maxlen = IntegerLength[max]; results = <||>; Do[ sq = i^2; id = IntegerDigits[sq]; starts = DeleteDuplicates[Take[id, UpTo[#]] & /@ Range[maxlen]]; starts //= Map[FromDigits]; starts //= Select[LessEqualThan[max]]; Do[ If[! KeyExistsQ[results, s], results = AssociateTo[results, s -> i^2] ] ...
Convert this C++ block to Mathematica, preserving its control flow and logic.
#include <iostream> int circlesort(int* arr, int lo, int hi, int swaps) { if(lo == hi) { return swaps; } int high = hi; int low = lo; int mid = (high - low) / 2; while(lo < hi) { if(arr[lo] > arr[hi]) { int temp = arr[lo]; arr[lo] = arr[hi]; a...
ClearAll[CircleSort, NestedCircleSort] CircleSort[d_List, l_, h_] := Module[{high, low, mid, lo = l, hi = h, data = d}, If[lo == hi, Return[data]]; high = hi; low = lo; mid = Floor[(hi - lo)/2]; While[lo < hi, If[data[[lo]] > data[[hi]], data[[{lo, hi}]] //= Reverse; ]; lo++; hi-- ]; I...
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <array> #include <iostream> #include <fstream> #include <map> #include <string> #include <vector> #include <boost/program_options.hpp> class letterset { public: letterset() { count_.fill(0); } explicit letterset(const std::string& str) { count_.fill(0); for (char c : str)...
ClearAll[possible] possible[letters_List][word_String] := Module[{c1, c2, m}, c1 = Counts[Characters@word]; c2 = Counts[letters]; m = Merge[{c1, c2}, Identity]; Length[Select[Select[m, Length /* GreaterThan[1]], Apply[Greater]]] == 0 ] chars = Characters@"ndeokgelw"; words = Import["http://wiki.puzzlers.org/p...
Convert this C++ snippet to Mathematica and keep its semantics consistent.
#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...
EscapeToken="\\"; LeftBraceToken="{"; RightBraceToken="}"; CaptureEscapes[exp:{___String}]:=SequenceReplace[exp,{EscapeToken,x_}:>EscapeToken<>x]; CaptureBraces[exp:{___String}]:=ReplaceAll[exp,{LeftBraceToken->LeftBrace,RightBraceToken->RightBrace}]; CaptureBraceTrees[exp:{(_String|LeftBrace|RightBrace)...}]:...
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; [STAThreadAttribute] int main() { Point^ MousePoint = gcnew Point(); Control^ TempControl = gcnew Control(); MousePoint = TempControl->MousePosition; Bitmap^ TempBitmap = gcnew Bitmap(1,1); Graphics^ g = Graphics::Fro...
getPixel[{x_?NumberQ, y_?NumberQ}, screenNumber_Integer: 1] := ImageValue[CurrentScreenImage[n], {x, y}]
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_categor...
Off[Solve::ratnz]; circs::invrad = "The radius is invalid."; circs::equpts = "The given points (`1`, `2`) are equivalent."; circs::dist = "The given points (`1`, `2`) and (`3`, `4`) are too far apart for \ radius `5`."; circs[_, _, 0.] := Message[circs::invrad]; circs[{p1x_, p1y_}, {p1x_, p1y_}, _] := Message[cir...
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_categor...
Off[Solve::ratnz]; circs::invrad = "The radius is invalid."; circs::equpts = "The given points (`1`, `2`) are equivalent."; circs::dist = "The given points (`1`, `2`) and (`3`, `4`) are too far apart for \ radius `5`."; circs[_, _, 0.] := Message[circs::invrad]; circs[{p1x_, p1y_}, {p1x_, p1y_}, _] := Message[cir...
Transform the following C++ implementation into Mathematica, maintaining the same output and logic.
#include <iostream> #include <string> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) using namespace std; class recorder { public: void start() { paused = rec = false; action = "IDLE"; while( true ) { cout << endl << "==" << action << "==" << endl << endl; cout <<...
SystemDialogInput["RecordSound"]
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#include <vector> #include <utility> #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <cmath> bool isVampireNumber( long number, std::vector<std::pair<long, long> > & solution ) { std::ostringstream numberstream ; numberstream << number ; std::string numberstring( number...
ClearAll[VampireQ] VampireQ[num_Integer] := Module[{poss, divs}, divs = Select[Divisors[num], # <= Sqrt[num] &]; poss = {#, num/#} & /@ divs; If[Length[poss] > 0, poss = Select[poss, Mod[#, 10] =!= {0, 0} &]; If[Length[poss] > 0, poss = Select[poss, Length[IntegerDigits[First[#]]] == Length[IntegerDigit...
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); ...
ClearAll[CistercianNumberEncodeHelper, CistercianNumberEncode] \[Delta] = 0.25; CistercianNumberEncodeHelper[0] := {} CistercianNumberEncodeHelper[1] := Line[{{0, 1}, {\[Delta], 1}}] CistercianNumberEncodeHelper[2] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1 - \[Delta]}}] CistercianNumberEncodeHelper[3] := Line[{{0, 1}, {...
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); ...
ClearAll[CistercianNumberEncodeHelper, CistercianNumberEncode] \[Delta] = 0.25; CistercianNumberEncodeHelper[0] := {} CistercianNumberEncodeHelper[1] := Line[{{0, 1}, {\[Delta], 1}}] CistercianNumberEncodeHelper[2] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1 - \[Delta]}}] CistercianNumberEncodeHelper[3] := Line[{{0, 1}, {...
Generate an equivalent Mathematica version of this C++ code.
#include <windows.h> #include <string> using namespace std; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, siz...
Module[{FibonacciWord, step}, FibonacciWord[1] = "1"; FibonacciWord[2] = "0"; FibonacciWord[n_Integer?(# > 2 &)] := (FibonacciWord[n] = FibonacciWord[n - 1] <> FibonacciWord[n - 2]); step["0", {_?EvenQ}] = N@RotationTransform[Pi/2]; step["0", {_?OddQ}] = N@RotationTransform[-Pi/2]; step[___] = Identi...
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( ...
Sierpinski[n_] := Nest[Join @@ Table[With[{a = #[[i, 1]], b = #[[i, 2]], c = #[[i, 3]]}, {{a, (a + b)/2, (c + a)/2}, {(a + b)/2, b, (b + c)/2}, {(c + a)/2, (b + c)/2, c}}], {i, Length[#]}] &, {{{0, 0}, {1/2, 1}, {1, 0}}}, n] Graphics[{Black, Polygon /@ Sierpinski[8]}]
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( ...
Sierpinski[n_] := Nest[Join @@ Table[With[{a = #[[i, 1]], b = #[[i, 2]], c = #[[i, 3]]}, {{a, (a + b)/2, (c + a)/2}, {(a + b)/2, b, (b + c)/2}, {(c + a)/2, (b + c)/2, c}}], {i, Length[#]}] &, {{{0, 0}, {1/2, 1}, {1, 0}}}, n] Graphics[{Black, Polygon /@ Sierpinski[8]}]
Keep all operations the same but rewrite the snippet in Mathematica.
#include <iomanip> #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <vector> typedef std::pair<int, std::vector<int> > puzzle; class nonoblock { public: void solve( std::vector<puzzle>& p ) { for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) { ...
ClearAll[SpacesDistributeOverN, Possibilities] SpacesDistributeOverN[s_, p_] := Flatten[ Permutations /@ (Join[#, ConstantArray[0, p - Length[#]]] & /@ IntegerPartitions[s, p]), 1] Possibilities[hint_, len_] := Module[{p = hint, l = len, b = Length[hint], Spaces, out}, Spaces = # + (Prepend[Append[Constan...
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#include <iomanip> #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <vector> typedef std::pair<int, std::vector<int> > puzzle; class nonoblock { public: void solve( std::vector<puzzle>& p ) { for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) { ...
ClearAll[SpacesDistributeOverN, Possibilities] SpacesDistributeOverN[s_, p_] := Flatten[ Permutations /@ (Join[#, ConstantArray[0, p - Length[#]]] & /@ IntegerPartitions[s, p]), 1] Possibilities[hint_, len_] := Module[{p = hint, l = len, b = Length[hint], Spaces, out}, Spaces = # + (Prepend[Append[Constan...
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <iostream> struct Interval { int start, end; bool print; }; int main() { Interval intervals[] = { {2, 1000, true}, {1000, 4000, true}, {2, 10000, false}, {2, 100000, false}, {2, 1000000, false}, {2, 10000000, false}, {2, 100000000, false}, ...
ClearAll[ZeroTwoFourSixQ, EbanNumbers] ZeroTwoFourSixQ[n_Integer] := (n == 0 || n == 2 || n == 4 || n == 6) EbanNumbers[min_, max_, show : (False | True)] := Module[{counter, output, i, b, r, t, m}, counter = 0; output = ""; i = min; While[(i += 2) <= max, {b, r} = QuotientRemainder[i, 10^9]; {m, r} = Q...
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <iostream> struct Interval { int start, end; bool print; }; int main() { Interval intervals[] = { {2, 1000, true}, {1000, 4000, true}, {2, 10000, false}, {2, 100000, false}, {2, 1000000, false}, {2, 10000000, false}, {2, 100000000, false}, ...
ClearAll[ZeroTwoFourSixQ, EbanNumbers] ZeroTwoFourSixQ[n_Integer] := (n == 0 || n == 2 || n == 4 || n == 6) EbanNumbers[min_, max_, show : (False | True)] := Module[{counter, output, i, b, r, t, m}, counter = 0; output = ""; i = min; While[(i += 2) <= max, {b, r} = QuotientRemainder[i, 10^9]; {m, r} = Q...
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <iostream> bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { ...
ClearAll[SequenceOk] SequenceOk[n_, k_] := Module[{m = n, q, r, valid = True}, Do[ {q, r} = QuotientRemainder[m, k]; If[r != 1, valid = False; Break[]; ]; m -= q + 1 , {k} ]; If[Mod[m, k] != 0, valid = False ]; valid ] i = 1; While[! SequenceOk[i, 5], i++] i i = 1; While[! S...
Keep all operations the same but rewrite the snippet in Mathematica.
#include <iostream> bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { ...
ClearAll[SequenceOk] SequenceOk[n_, k_] := Module[{m = n, q, r, valid = True}, Do[ {q, r} = QuotientRemainder[m, k]; If[r != 1, valid = False; Break[]; ]; m -= q + 1 , {k} ]; If[Mod[m, k] != 0, valid = False ]; valid ] i = 1; While[! SequenceOk[i, 5], i++] i i = 1; While[! S...
Please provide an equivalent version of this C++ code in Mathematica.
#include <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; cou...
LocalSubmit[ScheduledTask[ EmitSound[Sound[Table[{ SoundNote["C",750/1000,"TubularBells"],SoundNote[None,500/1000,"TubularBells"] },Mod[Round[Total[DateList[][[{4,5}]]{2,1/30}]],8,1]]]] ,DateObject[{_,_,_,_,_,30|0}]]]
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#include <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; cou...
LocalSubmit[ScheduledTask[ EmitSound[Sound[Table[{ SoundNote["C",750/1000,"TubularBells"],SoundNote[None,500/1000,"TubularBells"] },Mod[Round[Total[DateList[][[{4,5}]]{2,1/30}]],8,1]]]] ,DateObject[{_,_,_,_,_,30|0}]]]
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOER...
EmitSound@Sound[SoundNote /@ {0, 2, 4, 5, 7, 9, 11, 12}]
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOER...
EmitSound@Sound[SoundNote /@ {0, 2, 4, 5, 7, 9, 11, 12}]
Convert this C++ block to Mathematica, preserving its control flow and logic.
#include <windows.h> #include <sstream> #include <ctime> const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s = s...
linedata = {}; Dynamic[Graphics[Line[linedata], PlotRange -> 1000]] Do[ linedata = AnglePath[{#, \[Theta]} & /@ Range[5, 300, 3]]; Pause[0.1]; , {\[Theta], Subdivide[0.1, 1, 100]} ]
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#include <windows.h> #include <sstream> #include <ctime> const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s = s...
linedata = {}; Dynamic[Graphics[Line[linedata], PlotRange -> 1000]] Do[ linedata = AnglePath[{#, \[Theta]} & /@ Range[5, 300, 3]]; Pause[0.1]; , {\[Theta], Subdivide[0.1, 1, 100]} ]
Generate an equivalent Mathematica version of this C++ code.
#include <iostream> #include <optional> #include <ranges> #include <string> #include <vector> using namespace std; struct Patient { string ID; string LastName; }; struct Visit { string PatientID; string Date; optional<float> Score; }; int main(void) { auto patients = vector<Patient> { ...
a = ImportString["PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 5005,Kurtz", "CSV"]; b = ImportString["PATIENT_ID,VISIT_DATE,SCORE 2002,2020-09-10,6.8 1001,2020-09-17,5.5 4004,2020-09-24,8.4 2002,2020-10-08, 1001,,6.6 3003,2020-11-12, 4004,2020-11-05,7.0 1001,2020-11-19,5.3", "CSV"]; a = <|a[[1, 1...
Translate the given C++ code snippet into Mathematica without altering its behavior.
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); } bool Create(int w, int h) { BITMAPINFO bi; ZeroMem...
Needs["ComputationalGeometry`"] DiagramPlot[{{4.4, 14}, {6.7, 15.25}, {6.9, 12.8}, {2.1, 11.1}, {9.5, 14.9}, {13.2, 11.9}, {10.3, 12.3}, {6.8, 9.5}, {3.3, 7.7}, {0.6, 5.1}, {5.3, 2.4}, {8.45, 4.7}, {11.5, 9.6}, {13.8, 7.3}, {12.9, 3.1}, {11, 1.1}}]
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); } bool Create(int w, int h) { BITMAPINFO bi; ZeroMem...
Needs["ComputationalGeometry`"] DiagramPlot[{{4.4, 14}, {6.7, 15.25}, {6.9, 12.8}, {2.1, 11.1}, {9.5, 14.9}, {13.2, 11.9}, {10.3, 12.3}, {6.8, 9.5}, {3.3, 7.7}, {0.6, 5.1}, {5.3, 2.4}, {8.45, 4.7}, {11.5, 9.6}, {13.8, 7.3}, {12.9, 3.1}, {11, 1.1}}]
Convert this C++ snippet to Mathematica and keep its semantics consistent.
#include <iostream> #include <vector> #include <algorithm> #include <stdexcept> #include <memory> #include <sys/time.h> using std::cout; using std::endl; class StopTimer { public: StopTimer(): begin_(getUsec()) {} unsigned long long getTime() const { return getUsec() - begin_; } private: static unsigned l...
Transpose@{#[[;; , 1]], LinearProgramming[-#[[;; , 3]], -{#[[;; , 2]]}, -{400}, {0, #[[4]]} & /@ #, Integers]} &@{{"map", 9, 150, 1}, {"compass", 13, 35, 1}, {"water", 153, 200, 2}, {"sandwich", 50, 60, 2}, {"glucose", 15, 60, 2}, {"tin", 68, 45, 3}, {"banana", 27, 60, 3}, {"apple", 39, 40, 3}, ...
Translate this program into Mathematica but keep the logic exactly as in C++.
#include <list> template <typename T> std::list<T> strandSort(std::list<T> lst) { if (lst.size() <= 1) return lst; std::list<T> result; std::list<T> sorted; while (!lst.empty()) { sorted.push_back(lst.front()); lst.pop_front(); for (typename std::list<T>::iterator it = lst.begin(); it != lst.en...
StrandSort[ input_ ] := Module[ {results = {}, A = input}, While[Length@A > 0, sublist = {A[[1]]}; A = A[[2;;All]]; For[i = 1, i < Length@A, i++, If[ A[[i]] > Last@sublist, AppendTo[sublist, A[[i]]]; A = Delete[A, i];] ]; results = #[[Ordering@#]]&@Join[sublist, results];]; results ] StrandSort[{2, 3, 7, 5, 1...
Port the following code from C++ to Mathematica with equivalent syntax and logic.
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(doub...
ClearAll[NormalizeAngle, NormalizeDegree, NormalizeGradian, NormalizeMil, NormalizeRadian] NormalizeAngle[d_, full_] := Module[{a = d}, If[Abs[a/full] > 4, a = a - Sign[a] full (Quotient[Abs[a], full] - 4) ]; While[a < -full, a += full]; While[a > full, a -= full]; a ] ClearAll[Degree2Gradian, Degree2Mil...
Translate the given C++ code snippet into Mathematica without altering its behavior.
#include <cassert> #include <cstdlib> #include <iostream> #include <stdexcept> #include <utility> #include <vector> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlerror.h> #include <libxml/xmlstring.h> #include <libxml/xmlversion.h> #include <libxml/xpath.h> #ifndef LIBXML_XPATH_ENABLED # e...
example = Import["test.txt", "XML"]; Cases[example, XMLElement["item", _ , _] , Infinity] // First Cases[example, XMLElement["price", _, List[n_]] -> n, Infinity] // Column Cases[example, XMLElement["name", _, List[n_]] -> n, Infinity] // Column
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& print(std::ostream& os, const T& src) { auto it = src.cbegin(); auto end = src.cend(); os << "["; if (it != end) { os << *it; ...
data = Transpose@{{44, 42, 42, 41, 41, 41, 39}, {"Solomon", "Jason", "Errol", "Garry", "Bernard", "Barry", "Stephen"}}; rank[data_, type_] := Module[{t = Transpose@{Sort@data, Range[Length@data, 1, -1]}}, Switch[type, "standard", data/.Rule@@@First/@SplitBy[t, First], "modified", data/.Rule@@@Last/@Spli...
Translate the given C++ code snippet into Mathematica without altering its behavior.
#include <iostream> #include <fstream> #include <string> #include <tuple> #include <vector> #include <stdexcept> #include <boost/regex.hpp> struct Claim { Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() { } void add_pro(const std::string...
wordlist = Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "Words"]; Print["The number of words in unixdict.txt = " <> ToString[Length[wordlist]]] StringMatchQ[#, ___ ~~ "c" ~~ "i" ~~ "e" ~~ ___] & /@ wordlist ; cie = Count[%, True]; StringMatchQ[#, ___ ~~ "c" ~~ "e" ~~ "i" ~~ ___] & /@ wordlist...
Port the provided C++ code into Mathematica while preserving the original functionality.
#include <iostream> #include <fstream> #include <string> #include <tuple> #include <vector> #include <stdexcept> #include <boost/regex.hpp> struct Claim { Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() { } void add_pro(const std::string...
wordlist = Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "Words"]; Print["The number of words in unixdict.txt = " <> ToString[Length[wordlist]]] StringMatchQ[#, ___ ~~ "c" ~~ "i" ~~ "e" ~~ ___] & /@ wordlist ; cie = Count[%, True]; StringMatchQ[#, ___ ~~ "c" ~~ "e" ~~ "i" ~~ ___] & /@ wordlist...
Write the same algorithm in Mathematica as shown in this C++ implementation.
#include <iostream> #include "xtensor/xarray.hpp" #include "xtensor/xio.hpp" #include "xtensor-io/ximage.hpp" xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim) { xt::xarray<int>::shape_type shape = { x_dim, y_dim }; xt::xarray<int> grid(shape); grid(x_dim/2, y_dim/2) = 64000; r...
ClearAll[sp] sp[s_List] + sp[n_Integer] ^:= sp[s] + sp[ConstantArray[n, Dimensions[s]]] sp[s_List] + sp[t_List] ^:= Module[{dim, r, tmp, neighbours}, dim = Dimensions[s]; r = s + t; While[Max[r] > 3, r = ArrayPad[r, 1, 0]; tmp = Quotient[r, 4]; r -= 4 tmp; r += RotateLeft[tmp, {0, 1}] + RotateLeft[tmp, {1,...
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <iostream> #include "xtensor/xarray.hpp" #include "xtensor/xio.hpp" #include "xtensor-io/ximage.hpp" xt::xarray<int> init_grid (unsigned long x_dim, unsigned long y_dim) { xt::xarray<int>::shape_type shape = { x_dim, y_dim }; xt::xarray<int> grid(shape); grid(x_dim/2, y_dim/2) = 64000; r...
ClearAll[sp] sp[s_List] + sp[n_Integer] ^:= sp[s] + sp[ConstantArray[n, Dimensions[s]]] sp[s_List] + sp[t_List] ^:= Module[{dim, r, tmp, neighbours}, dim = Dimensions[s]; r = s + t; While[Max[r] > 3, r = ArrayPad[r, 1, 0]; tmp = Quotient[r, 4]; r -= 4 tmp; r += RotateLeft[tmp, {0, 1}] + RotateLeft[tmp, {1,...
Please provide an equivalent version of this C++ code in Mathematica.
#include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> using integer = mpz_class; std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } integer next_highest(const integer& n) { std::string str(to_string(n)); if (!std::next_permuta...
ClearAll[NextHighestIntFromDigits] NextHighestIntFromDigits[n_Integer?NonNegative]:=Module[{digs}, digs=IntegerDigits[n]; digs=FromDigits/@Permutations[digs]; digs=Select[digs,GreaterEqualThan[n]]; If[Length[digs]==1,First[digs],RankedMin[digs,2]] ] NextHighestIntFromDigits/@{0,9,12,21,12453,738440,45072010,9532202...
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> using integer = mpz_class; std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } integer next_highest(const integer& n) { std::string str(to_string(n)); if (!std::next_permuta...
ClearAll[NextHighestIntFromDigits] NextHighestIntFromDigits[n_Integer?NonNegative]:=Module[{digs}, digs=IntegerDigits[n]; digs=FromDigits/@Permutations[digs]; digs=Select[digs,GreaterEqualThan[n]]; If[Length[digs]==1,First[digs],RankedMin[digs,2]] ] NextHighestIntFromDigits/@{0,9,12,21,12453,738440,45072010,9532202...
Convert the following code from C++ to Mathematica, ensuring the logic remains intact.
#include <iostream> #include <string> #include <cctype> #include <cstdint> typedef std::uint64_t integer; const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen"...
magic[num_] := Capitalize[ StringRiffle[ Partition[ FixedPointList[IntegerName[StringLength[#], "Cardinal"] &, IntegerName[num, "Cardinal"]], 2, 1] /. {n_, n_} :> {n, "magic"}, ", ", " is "] <> "."]
Please provide an equivalent version of this C++ code in Mathematica.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <sstream> class Roulette { private: std::array<bool, 6> cylinder; std::mt19937 gen; std::uniform_int_distribution<> distrib; int next_int() { return distrib(gen); } void rshift() { std::rotate(...
ClearAll[Unload, Load, Spin, Fire] Unload[] := ConstantArray[False, 6] Load[state_List] := Module[{s = state}, While[s[[2]], s = RotateRight[s, 1] ]; s[[2]] = True; s ] Spin[state_List] := RotateRight[state, RandomInteger[{1, 6}]] Fire[state_List] := Module[{shot}, shot = First[state]; {RotateRight[st...
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { doubl...
pentaFlake[0] = RegularPolygon[5]; pentaFlake[n_] := GeometricTransformation[pentaFlake[n - 1], TranslationTransform /@ CirclePoints[{GoldenRatio^(2 n - 1), Pi/10}, 5]] Graphics@pentaFlake[4]
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#include <iostream> #include <string> #include <sstream> #include <valarray> const std::string input { "................................" ".#########.......########......." ".###...####.....####..####......" ".###....###.....###....###......" ".###...####.....###............." ".#########......###............." ".###.#...
nB[mat_] := Delete[mat // Flatten, 5] // Total; nA[mat_] := Module[{l}, l = Flatten[mat][[{2, 3, 6, 9, 8, 7, 4, 1, 2}]]; Total[Map[If[#[[1]] == 0 && #[[2]] == 1, 1, 0] &, Partition[l, 2, 1]]] ]; iW1[mat_] := Module[{l = Flatten[mat]}, If[Apply[Times, l[[{2, 6, 8}]]] + Apply[Times, l[[{4, 6, 8}]]...
Write the same algorithm in Mathematica as shown in this C++ implementation.
#include <iostream> #include <string> #include <time.h> using namespace std; namespace { void placeRandomly(char* p, char c) { int loc = rand() % 8; if (!p[loc]) p[loc] = c; else placeRandomly(p, c); } int placeFirst(char* p, char c, int loc = 0) { while (p[loc]) ++loc; p[loc] = ...
Print[StringJoin[ RandomChoice[ Select[Union[ Permutations[{"\[WhiteKing]", "\[WhiteQueen]", "\[WhiteRook]", "\[WhiteRook]", "\[WhiteBishop]", "\[WhiteBishop]", "\[WhiteKnight]", "\[WhiteKnight]"}]], MatchQ[#, {___, "\[WhiteRook]", ___, "\[WhiteKing]", ___, "\[WhiteRook]",...
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <iostream> #include <locale> #include <map> #include <vector> std::string trim(const std::string &str) { auto s = str; auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(it1.base(), s.end()); auto it2 = st...
s=" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # ###...
Write the same algorithm in Mathematica as shown in this C++ implementation.
#include <iostream> #include <utility> #include <vector> using Point = std::pair<double, double>; constexpr auto eps = 1e-14; std::ostream &operator<<(std::ostream &os, const Point &p) { auto x = p.first; if (x == 0.0) { x = 0.0; } auto y = p.second; if (y == 0.0) { y = 0.0; } ...
LineCircleIntersections[p1_, p2_, c_, r_, type_] := RegionIntersection[Circle[c, r], type[{p1, p2}]] LineCircleIntersections[{-1, 1}, {1, 1}, {0, 0}, 1, Line] LineCircleIntersections[{-1, 0}, {2, 0.4}, {0, 0}, 1, Line] LineCircleIntersections[{-1.5, 0}, {-2, 0.4}, {0, 0}, 1, Line] LineCircleIntersections[{-1.5, 0}, {-2...
Convert this C++ snippet to Mathematica and keep its semantics consistent.
#include <iostream> #include <cstring> int findNumOfDec(const char *s) { int pos = 0; while (s[pos] && s[pos++] != '.') {} return strlen(s + pos); } void test(const char *s) { int num = findNumOfDec(s); const char *p = num != 1 ? "s" : ""; std::cout << s << " has " << num << " decimal" << p <...
ClearAll[DecimalDigits] DecimalDigits[r_String] := Module[{pos}, If[StringContainsQ[r, "."], pos = StringPosition[r, "."][[-1, 1]]; StringLength[StringDrop[r, pos]] , 0 ] ] DecimalDigits["12.345"] DecimalDigits["12.3450"] DecimalDigits["8"] DecimalDigits["3128"] DecimalDigits["13."] DecimalDigits["13...
Translate the given C++ code snippet into Mathematica without altering its behavior.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx...
puzz = ".00.00.\n0000000\n0000000\n.00000.\n..000..\n...0..."; puzz //= StringSplit[#, "\n"] & /* Map[Characters]; puzz //= Transpose /* Map[Reverse]; pos = Position[puzz, "0", {2}]; moves = Select[Select[Tuples[pos, 2], MatchQ[EuclideanDistance @@ #, 2 Sqrt[2] | 3] &], OrderedQ]; g = Graph[UndirectedEdge @@@ moves]; o...
Please provide an equivalent version of this C++ code in Mathematica.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx...
puzz = ".00.00.\n0000000\n0000000\n.00000.\n..000..\n...0..."; puzz //= StringSplit[#, "\n"] & /* Map[Characters]; puzz //= Transpose /* Map[Reverse]; pos = Position[puzz, "0", {2}]; moves = Select[Select[Tuples[pos, 2], MatchQ[EuclideanDistance @@ #, 2 Sqrt[2] | 3] &], OrderedQ]; g = Graph[UndirectedEdge @@@ moves]; o...
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
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(); }
obj[foo] = "This is foo."; obj[bar] = "This is bar."; obj[f_Symbol] := "What is " <> SymbolName[f] <> "?"; Print[obj@foo]; Print[obj@bar]; Print[obj@baz];
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_no...
parse[string_] := Module[{e}, StringCases[string, "+" | "-" | "*" | "/" | "(" | ")" | DigitCharacter ..] //. {a_String?DigitQ :> e[ToExpression@a], {x___, PatternSequence["(", a_e, ")"], y___} :> {x, a, y}, {x : PatternSequence[] | PatternSequence[___, "(" | ...
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_no...
parse[string_] := Module[{e}, StringCases[string, "+" | "-" | "*" | "/" | "(" | ")" | DigitCharacter ..] //. {a_String?DigitQ :> e[ToExpression@a], {x___, PatternSequence["(", a_e, ")"], y___} :> {x, a, y}, {x : PatternSequence[] | PatternSequence[___, "(" | ...
Can you help me rewrite this code in Mathematica instead of C++, keeping it the same logically?
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_curve { 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]]
Can you help me rewrite this code in Mathematica instead of C++, keeping it the same logically?
#include <cmath> #include <fstream> #include <iostream> #include <string> class sierpinski_curve { 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]]
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#include <stdio.h> #include <stdlib.h> void clear() { for(int n = 0;n < 10; n++) { printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n"); } } #define UP "00^00\r\n00|00\r\n00000\r\n" #define DOWN "00000\r\n00|00\r\n00v00\r\n" #define LEFT "00000\r\n<--00\r\n00000\r\n" #define RIGHT "00000\r\n00-->\r\n00000\r\...
Slider2D[Dynamic[ControllerState[{"X", "Y"}]], ImageSize -> {500, 500}]
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#include <iostream> #include <set> #include <tuple> #include <vector> using namespace std; template<typename P> void PrintPayloads(const P &payloads, int index, bool isLast) { if(index < 0 || index >= (int)size(payloads)) cout << "null"; else cout << "'" << payloads[index] << "'"; if (!isLast) co...
t = ToExpression[StringReplace["[[[1,2],[3,4,1],5]]", {"[" -> "{", "]" -> "}"}]]; p = "Payload#" <> ToString[#] & /@ Range[6]; Map[p[[#]] &, t, {-1}]
Convert this C++ block to Mathematica, preserving its control flow and logic.
#include <iostream> struct fraction { fraction(int n, int d) : numerator(n), denominator(d) {} int numerator; int denominator; }; std::ostream& operator<<(std::ostream& out, const fraction& f) { out << f.numerator << '/' << f.denominator; return out; } class farey_sequence { public: explicit ...
farey[n_]:=StringJoin@@Riffle[ToString@Numerator[#]<>"/"<>ToString@Denominator[#]&/@FareySequence[n],", "] TableForm[farey/@Range[11]] Table[Length[FareySequence[n]], {n, 100, 1000, 100}]
Convert the following code from C++ to Mathematica, ensuring the logic remains intact.
#include <iostream> struct fraction { fraction(int n, int d) : numerator(n), denominator(d) {} int numerator; int denominator; }; std::ostream& operator<<(std::ostream& out, const fraction& f) { out << f.numerator << '/' << f.denominator; return out; } class farey_sequence { public: explicit ...
farey[n_]:=StringJoin@@Riffle[ToString@Numerator[#]<>"/"<>ToString@Denominator[#]&/@FareySequence[n],", "] TableForm[farey/@Range[11]] Table[Length[FareySequence[n]], {n, 100, 1000, 100}]
Convert the following code from C++ to Mathematica, ensuring the logic remains intact.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power ...
seq[n_] := NestList[If[# == 0, 0, DivisorSum[#, # &, Function[div, div != #]]] &, n, 16]; class[seq_] := Which[Length[seq] < 2, "Non-terminating", MemberQ[seq, 0], "Terminating", seq[[1]] == seq[[2]], "Perfect", Length[seq] > 2 && seq[[1]] == seq[[3]], "Amicable", Length[seq] > 3 && MemberQ[seq[...
Generate an equivalent Mathematica version of this C++ code.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power ...
seq[n_] := NestList[If[# == 0, 0, DivisorSum[#, # &, Function[div, div != #]]] &, n, 16]; class[seq_] := Which[Length[seq] < 2, "Non-terminating", MemberQ[seq, 0], "Terminating", seq[[1]] == seq[[2]], "Perfect", Length[seq] > 2 && seq[[1]] == seq[[3]], "Amicable", Length[seq] > 3 && MemberQ[seq[...
Convert the following code from C++ to Mathematica, ensuring the logic remains intact.
#include <iomanip> #include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; ...
Clear[MagnanimousNumberQ] MagnanimousNumberQ[Alternatives @@ Range[0, 9]] = True; MagnanimousNumberQ[n_Integer] := AllTrue[Range[IntegerLength[n] - 1], PrimeQ[Total[FromDigits /@ TakeDrop[IntegerDigits[n], #]]] &] sel = Select[Range[0, 1000000], MagnanimousNumberQ]; sel[[;; 45]] sel[[241 ;; 250]] sel[[391 ;; 400]]
Port the provided C++ code into Mathematica while preserving the original functionality.
#include <iostream> bool isPrime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; uint64_t test = 5; while (test * test < n) { if (n % test == 0) return false; test += 2; if (n % test == 0) return false; test += 4;...
MersennePrimeExponent /@ Range[40]
Port the following code from C++ to Mathematica with equivalent syntax and logic.
#include <iostream> bool isPrime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; uint64_t test = 5; while (test * test < n) { if (n % test == 0) return false; test += 2; if (n % test == 0) return false; test += 4;...
MersennePrimeExponent /@ Range[40]
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#include <array> #include <iostream> #include <vector> #include <boost/circular_buffer.hpp> #include "prime_sieve.hpp" int main() { using std::cout; using std::vector; using boost::circular_buffer; using group_buffer = circular_buffer<vector<int>>; const int max = 1000035; const int max_group_...
ClearAll[AllSublengths] AllSublengths[l_List] := If[Length[l] > 2, Catenate[Partition[l, #, 1] & /@ Range[2, Length[l]]] , {l} ] primes = Prime[Range[PrimePi[1000035]]]; ps = Union[Intersection[primes + 6, primes] - 6, Intersection[primes - 6, primes] + 6]; a = Intersection[ps + 6, ps] - 6; b = Intersection[ps ...
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <sstream> #include <vector> template <typename T> size_t indexOf(const std::vector<T> &v, const T &k) { auto it = std::find(v.cbegin(), v.cend(), k); if (it != v.cend()) { return it - v.cbegin(); } return -1; }...
findTaxi[n_] := Sort[Keys[Select[Counts[Flatten[Table[x^3 + y^3, {x, 1, n}, {y, x, n}]]], GreaterThan[1]]]]; Take[findTaxiNumbers[100], 25] found=findTaxiNumbers[1200][[2000 ;; 2005]] Map[Reduce[x^3 + y^3 == # && x >= y && x > 0 && y > 0, {x, y}, Integers] &, found]
Write the same code in Mathematica as shown below in C++.
#include <algorithm> #include <iostream> #include <iterator> #include <locale> #include <vector> #include "prime_sieve.hpp" const int limit1 = 1000000; const int limit2 = 10000000; class prime_info { public: explicit prime_info(int max) : max_print(max) {} void add_prime(int prime); void print(std::ostrea...
p = Prime[Range[PrimePi[10^3]]]; SequenceCases[p, ({a_, b_, c_}) /; (a + c < 2 b) :> b, 36, Overlaps -> True] SequenceCases[p, ({a_, b_, c_}) /; (a + c > 2 b) :> b, 37, Overlaps -> True] p = Prime[Range[PrimePi[10^6] + 1]]; Length[Select[Partition[p, 3, 1], #[[3]] + #[[1]] < 2 #[[2]] &]] Length[Select[Partition[p, 3, 1...
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#include <vector> #include <string> #include <algorithm> #include <iostream> #include <sstream> using namespace std; #if 1 typedef unsigned long usingle; typedef unsigned long long udouble; const int word_len = 32; #else typedef unsigned short usingle; typedef unsigned long udouble; const int word_len = 16; #endif ...
left[n_] := left[n] = Sum[k!, {k, 0, n - 1}] Print["left factorials 0 through 10:"] Print[left /@ Range[0, 10] // TableForm] Print["left factorials 20 through 110, by tens:"] Print[left /@ Range[20, 110, 10] // TableForm] Print["Digits in left factorials 1,000 through 10,000, by thousands:"] Print[Length[IntegerDigits[...
Write the same code in Mathematica as shown below in C++.
#include <vector> #include <string> #include <algorithm> #include <iostream> #include <sstream> using namespace std; #if 1 typedef unsigned long usingle; typedef unsigned long long udouble; const int word_len = 32; #else typedef unsigned short usingle; typedef unsigned long udouble; const int word_len = 16; #endif ...
left[n_] := left[n] = Sum[k!, {k, 0, n - 1}] Print["left factorials 0 through 10:"] Print[left /@ Range[0, 10] // TableForm] Print["left factorials 20 through 110, by tens:"] Print[left /@ Range[20, 110, 10] // TableForm] Print["Digits in left factorials 1,000 through 10,000, by thousands:"] Print[Length[IntegerDigits[...
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#include <iomanip> #include <iostream> #include <vector> std::vector<bool> prime_sieve(size_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (size_t i = 4; i < limit; i += 2) sieve[i] = false; for (size_t ...
p = Prime[Range@PrimePi[30]]; Select[Subsets[p, {3}], Total/*PrimeQ] p = Prime[Range@PrimePi[1000]]; Length[Select[Subsets[p, {3}], Total/*PrimeQ]]
Write the same algorithm in Mathematica as shown in this C++ implementation.
#include <iomanip> #include <iostream> #include <vector> std::vector<bool> prime_sieve(size_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (size_t i = 4; i < limit; i += 2) sieve[i] = false; for (size_t ...
p = Prime[Range@PrimePi[30]]; Select[Subsets[p, {3}], Total/*PrimeQ] p = Prime[Range@PrimePi[1000]]; Length[Select[Subsets[p, {3}], Total/*PrimeQ]]