Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Produce a functionally identical C++ code for the snippet given in C#. | using System;
class Program
{
static void Main(string[] args)
{
var cube = new Func<double, double>(x => Math.Pow(x, 3.0));
var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));
var functionTuples = new[]
{
(forward: Math.Sin, backward: Math.Asin),
(forward: Math.Cos, backward: Math.Acos),
(forward: cube, backward: croot)
};
foreach (var ft in functionTuples)
{
Console.WriteLine(ft.backward(ft.forward(0.5)));
}
}
}
| #include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;
typedef function<double(double)> FunType;
vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };
vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };
template <typename A, typename B, typename C>
function<C(A)> compose(function<C(B)> f, function<B(A)> g) {
return [f,g](A x) { return f(g(x)); };
}
int main() {
vector<FunType> composedFuns;
auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};
transform(B.begin(), B.end(),
A.begin(),
back_inserter(composedFuns),
compose<double, double, double>);
for (auto num: exNums)
for (auto fun: composedFuns)
cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;
return 0;
}
|
Change the following C# code into C++ without altering its purpose. | namespace RosettaCode.ProperDivisors
{
using System;
using System.Collections.Generic;
using System.Linq;
internal static class Program
{
private static IEnumerable<int> ProperDivisors(int number)
{
return
Enumerable.Range(1, number / 2)
.Where(divisor => number % divisor == 0);
}
private static void Main()
{
foreach (var number in Enumerable.Range(1, 10))
{
Console.WriteLine("{0}: {{{1}}}", number,
string.Join(", ", ProperDivisors(number)));
}
var record = Enumerable.Range(1, 20000).Select(number => new
{
Number = number,
Count = ProperDivisors(number).Count()
}).OrderByDescending(currentRecord => currentRecord.Count).First();
Console.WriteLine("{0}: {1}", record.Number, record.Count);
}
}
}
| #include <vector>
#include <iostream>
#include <algorithm>
std::vector<int> properDivisors ( int number ) {
std::vector<int> divisors ;
for ( int i = 1 ; i < number / 2 + 1 ; i++ )
if ( number % i == 0 )
divisors.push_back( i ) ;
return divisors ;
}
int main( ) {
std::vector<int> divisors ;
unsigned int maxdivisors = 0 ;
int corresponding_number = 0 ;
for ( int i = 1 ; i < 11 ; i++ ) {
divisors = properDivisors ( i ) ;
std::cout << "Proper divisors of " << i << ":\n" ;
for ( int number : divisors ) {
std::cout << number << " " ;
}
std::cout << std::endl ;
divisors.clear( ) ;
}
for ( int i = 11 ; i < 20001 ; i++ ) {
divisors = properDivisors ( i ) ;
if ( divisors.size( ) > maxdivisors ) {
maxdivisors = divisors.size( ) ;
corresponding_number = i ;
}
divisors.clear( ) ;
}
std::cout << "Most divisors has " << corresponding_number <<
" , it has " << maxdivisors << " divisors!\n" ;
return 0 ;
}
|
Change the following C# code into C++ without altering its purpose. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
class Program
{
static string CreateXML(Dictionary<string, string> characterRemarks)
{
var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key)));
var xml = new XElement("CharacterRemarks", remarks);
return xml.ToString();
}
static void Main(string[] args)
{
var characterRemarks = new Dictionary<string, string>
{
{ "April", "Bubbly: I'm > Tam and <= Emily" },
{ "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" },
{ "Emily", "Short & shrift" }
};
string xml = CreateXML(characterRemarks);
Console.WriteLine(xml);
}
}
| #include <vector>
#include <utility>
#include <iostream>
#include <boost/algorithm/string.hpp>
std::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;
int main( ) {
std::vector<std::string> names , remarks ;
names.push_back( "April" ) ;
names.push_back( "Tam O'Shantor" ) ;
names.push_back ( "Emily" ) ;
remarks.push_back( "Bubbly, I'm > Tam and <= Emily" ) ;
remarks.push_back( "Burns: \"When chapman billies leave the street ...\"" ) ;
remarks.push_back( "Short & shrift" ) ;
std::cout << "This is in XML:\n" ;
std::cout << create_xml( names , remarks ) << std::endl ;
return 0 ;
}
std::string create_xml( std::vector<std::string> & names ,
std::vector<std::string> & remarks ) {
std::vector<std::pair<std::string , std::string> > entities ;
entities.push_back( std::make_pair( "&" , "&" ) ) ;
entities.push_back( std::make_pair( "<" , "<" ) ) ;
entities.push_back( std::make_pair( ">" , ">" ) ) ;
std::string xmlstring ( "<CharacterRemarks>\n" ) ;
std::vector<std::string>::iterator vsi = names.begin( ) ;
typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ;
for ( ; vsi != names.end( ) ; vsi++ ) {
for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
boost::replace_all ( *vsi , vs->first , vs->second ) ;
}
}
for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) {
for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) {
boost::replace_all ( *vsi , vs->first , vs->second ) ;
}
}
for ( int i = 0 ; i < names.size( ) ; i++ ) {
xmlstring.append( "\t<Character name=\"").append( names[ i ] ).append( "\">")
.append( remarks[ i ] ).append( "</Character>\n" ) ;
}
xmlstring.append( "</CharacterRemarks>" ) ;
return xmlstring ;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the C# version. | using System;
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string str = "I am a string";
if (new Regex("string$").IsMatch(str)) {
Console.WriteLine("Ends with string.");
}
str = new Regex(" a ").Replace(str, " another ");
Console.WriteLine(str);
}
}
| #include <iostream>
#include <string>
#include <iterator>
#include <regex>
int main()
{
std::regex re(".* string$");
std::string s = "Hi, I am a string";
if (std::regex_match(s, re))
std::cout << "The string matches.\n";
else
std::cout << "Oops - not found?\n";
std::regex re2(" a.*a");
std::smatch match;
if (std::regex_search(s, match, re2))
{
std::cout << "Matched " << match.length()
<< " characters starting at " << match.position() << ".\n";
std::cout << "Matched character sequence: \""
<< match.str() << "\"\n";
}
else
{
std::cout << "Oops - not found?\n";
}
std::string dest_string;
std::regex_replace(std::back_inserter(dest_string),
s.begin(), s.end(),
re2,
"'m now a changed");
std::cout << dest_string << std::endl;
}
|
Ensure the translated C++ code behaves exactly like the original C# snippet. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class RealisticGuess
{
private int max;
private int min;
private int guess;
public void Start()
{
Console.Clear();
string input;
try
{
Console.WriteLine("Please enter the lower boundary");
input = Console.ReadLine();
min = Convert.ToInt32(input);
Console.WriteLine("Please enter the upper boundary");
input = Console.ReadLine();
max = Convert.ToInt32(input);
}
catch (FormatException)
{
Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again.");
Console.ReadKey(true);
Start();
}
Console.WriteLine("Think of a number between {0} and {1}.", min, max);
Thread.Sleep(2500);
Console.WriteLine("Ready?");
Console.WriteLine("Press any key to begin.");
Console.ReadKey(true);
Guess(min, max);
}
public void Guess(int min, int max)
{
int counter = 1;
string userAnswer;
bool correct = false;
Random rand = new Random();
while (correct == false)
{
guess = rand.Next(min, max);
Console.Clear();
Console.WriteLine("{0}", guess);
Console.WriteLine("Is this number correct? {Y/N}");
userAnswer = Console.ReadLine();
if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N")
{
Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'");
Console.WriteLine("Is the number correct? {Y/N}");
userAnswer = Console.ReadLine();
}
if (userAnswer == "y" || userAnswer == "Y")
{
correct = true;
}
if (userAnswer == "n" || userAnswer == "N")
{
counter++;
if (max == min)
{
Console.WriteLine("Error: Range Intersect. Press enter to restart the game.");
Console.ReadKey(true);
Guess(1, 101);
}
Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}");
userAnswer = Console.ReadLine();
if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H")
{
Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'");
Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}");
userAnswer = Console.ReadLine();
}
if (userAnswer == "l" || userAnswer == "L")
{
max = guess;
}
if (userAnswer == "h" || userAnswer == "H")
{
min = guess;
}
}
}
if (correct == true)
{
EndAndLoop(counter);
}
}
public void EndAndLoop(int iterations)
{
string userChoice;
bool loop = false;
Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations);
while (loop == false)
{
Console.WriteLine("Would you like to play again? {Y/N}");
userChoice = Console.ReadLine();
if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n")
{
Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit.");
}
if (userChoice == "Y" || userChoice == "y")
{
Start();
}
if (userChoice == "N" || userChoice == "n")
{
Environment.Exit(1);
}
}
}
}
class Program
{
static void Main(string[] args)
{
Console.Title = "Random Number";
RealisticGuess game = new RealisticGuess();
game.Start();
}
}
}
| #include <iostream>
#include <algorithm>
#include <string>
#include <iterator>
struct GuessNumberIterator : std::iterator<std::random_access_iterator_tag, int> {
int i;
GuessNumberIterator() { }
GuessNumberIterator(int _i) : i(_i) { }
GuessNumberIterator& operator++() { ++i; return *this; }
GuessNumberIterator operator++(int) {
GuessNumberIterator tmp = *this; ++(*this); return tmp; }
bool operator==(const GuessNumberIterator& y) { return i == y.i; }
bool operator!=(const GuessNumberIterator& y) { return i != y.i; }
int operator*() {
std::cout << "Is your number less than or equal to " << i << "? ";
std::string s;
std::cin >> s;
return (s != "" && (s[0] == 'y' || s[0] == 'Y')) ? 0 : -1;
}
GuessNumberIterator& operator--() { --i; return *this; }
GuessNumberIterator operator--(int) {
GuessNumberIterator tmp = *this; --(*this); return tmp; }
GuessNumberIterator& operator+=(int n) { i += n; return *this; }
GuessNumberIterator& operator-=(int n) { i -= n; return *this; }
GuessNumberIterator operator+(int n) {
GuessNumberIterator tmp = *this; return tmp += n; }
GuessNumberIterator operator-(int n) {
GuessNumberIterator tmp = *this; return tmp -= n; }
int operator-(const GuessNumberIterator &y) { return i - y.i; }
int operator[](int n) { return *(*this + n); }
bool operator<(const GuessNumberIterator &y) { return i < y.i; }
bool operator>(const GuessNumberIterator &y) { return i > y.i; }
bool operator<=(const GuessNumberIterator &y) { return i <= y.i; }
bool operator>=(const GuessNumberIterator &y) { return i >= y.i; }
};
inline GuessNumberIterator operator+(int n, GuessNumberIterator &i) { return i + n; }
const int lower = 0;
const int upper = 100;
int main() {
std::cout << "Instructions:\n"
<< "Think of integer number from " << lower << " (inclusive) to "
<< upper << " (exclusive) and\n"
<< "I will guess it. After each guess, I will ask you if it is less than\n"
<< "or equal to some number, and you will respond with \"yes\" or \"no\".\n";
int answer = std::lower_bound(GuessNumberIterator(lower), GuessNumberIterator(upper), 0).i;
std::cout << "Your number is " << answer << ".\n";
return 0;
}
|
Convert this C# snippet to C++ and keep its semantics consistent. | static class Program
{
static void Main()
{
System.Collections.Hashtable h = new System.Collections.Hashtable();
string[] keys = { "foo", "bar", "val" };
string[] values = { "little", "miss", "muffet" };
System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length.");
for (int i = 0; i < keys.Length; i++)
{
h.Add(keys[i], values[i]);
}
}
}
| #include <unordered_map>
#include <string>
int main()
{
std::string keys[] = { "1", "2", "3" };
std::string vals[] = { "a", "b", "c" };
std::unordered_map<std::string, std::string> hash;
for( int i = 0 ; i < 3 ; i++ )
hash[ keys[i] ] = vals[i] ;
}
|
Generate a C++ translation of this C# snippet without changing its computational steps. | using System;
public class Program
{
static void Main()
{
PrintBins(new [] { 23, 37, 43, 53, 67, 83 },
95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55
);
Console.WriteLine();
PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },
445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,
253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,
622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,
945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759,
898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,
736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,
892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749);
}
static void PrintBins(int[] limits, params int[] data)
{
int[] bins = Bins(limits, data);
Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}");
for (int i = 0; i < limits.Length-1; i++) {
Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}");
}
Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}");
}
static int[] Bins(int[] limits, params int[] data)
{
Array.Sort(limits);
int[] bins = new int[limits.Length + 1];
foreach (int n in data) {
int i = Array.BinarySearch(limits, n);
i = i < 0 ? ~i : i+1;
bins[i]++;
}
return bins;
}
}
| #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> bins(const std::vector<int>& limits,
const std::vector<int>& data) {
std::vector<int> result(limits.size() + 1, 0);
for (int n : data) {
auto i = std::upper_bound(limits.begin(), limits.end(), n);
++result[i - limits.begin()];
}
return result;
}
void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {
size_t n = limits.size();
if (n == 0)
return;
assert(n + 1 == bins.size());
std::cout << " < " << std::setw(3) << limits[0] << ": "
<< std::setw(2) << bins[0] << '\n';
for (size_t i = 1; i < n; ++i)
std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < "
<< std::setw(3) << limits[i] << ": " << std::setw(2)
<< bins[i] << '\n';
std::cout << ">= " << std::setw(3) << limits[n - 1] << " : "
<< std::setw(2) << bins[n] << '\n';
}
int main() {
const std::vector<int> limits1{23, 37, 43, 53, 67, 83};
const std::vector<int> data1{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
std::cout << "Example 1:\n";
print_bins(limits1, bins(limits1, data1));
const std::vector<int> limits2{14, 18, 249, 312, 389,
392, 513, 591, 634, 720};
const std::vector<int> data2{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
std::cout << "\nExample 2:\n";
print_bins(limits2, bins(limits2, data2));
}
|
Rewrite this program in C# while keeping its functionality equivalent to the C++ version. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> bins(const std::vector<int>& limits,
const std::vector<int>& data) {
std::vector<int> result(limits.size() + 1, 0);
for (int n : data) {
auto i = std::upper_bound(limits.begin(), limits.end(), n);
++result[i - limits.begin()];
}
return result;
}
void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {
size_t n = limits.size();
if (n == 0)
return;
assert(n + 1 == bins.size());
std::cout << " < " << std::setw(3) << limits[0] << ": "
<< std::setw(2) << bins[0] << '\n';
for (size_t i = 1; i < n; ++i)
std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < "
<< std::setw(3) << limits[i] << ": " << std::setw(2)
<< bins[i] << '\n';
std::cout << ">= " << std::setw(3) << limits[n - 1] << " : "
<< std::setw(2) << bins[n] << '\n';
}
int main() {
const std::vector<int> limits1{23, 37, 43, 53, 67, 83};
const std::vector<int> data1{
95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65,
17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19,
30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};
std::cout << "Example 1:\n";
print_bins(limits1, bins(limits1, data1));
const std::vector<int> limits2{14, 18, 249, 312, 389,
392, 513, 591, 634, 720};
const std::vector<int> data2{
445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525,
570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391,
913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213,
799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981,
480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898,
576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374,
101, 684, 727, 749};
std::cout << "\nExample 2:\n";
print_bins(limits2, bins(limits2, data2));
}
| using System;
public class Program
{
static void Main()
{
PrintBins(new [] { 23, 37, 43, 53, 67, 83 },
95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55
);
Console.WriteLine();
PrintBins(new [] { 14, 18, 249, 312, 389, 392, 513, 591, 634, 720 },
445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,416,589,930,373,202,
253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,655,267,248,477,549,238, 62,678, 98,534,
622,907,406,714,184,391,913, 42,560,247,346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,
945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,787,942,456,242,759,
898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,698,765,331,487,251,600,879,342,982,527,
736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,
892,443,198,988,791,466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749);
}
static void PrintBins(int[] limits, params int[] data)
{
int[] bins = Bins(limits, data);
Console.WriteLine($"-∞ .. {limits[0]} => {bins[0]}");
for (int i = 0; i < limits.Length-1; i++) {
Console.WriteLine($"{limits[i]} .. {limits[i+1]} => {bins[i+1]}");
}
Console.WriteLine($"{limits[^1]} .. ∞ => {bins[^1]}");
}
static int[] Bins(int[] limits, params int[] data)
{
Array.Sort(limits);
int[] bins = new int[limits.Length + 1];
foreach (int n in data) {
int i = Array.BinarySearch(limits, n);
i = i < 0 ? ~i : i+1;
bins[i]++;
}
return bins;
}
}
|
Port the following code from C# to C++ with equivalent syntax and logic. | using System;
using System.Drawing;
using System.Windows.Forms;
class CSharpPendulum
{
Form _form;
Timer _timer;
double _angle = Math.PI / 2,
_angleAccel,
_angleVelocity = 0,
_dt = 0.1;
int _length = 50;
[STAThread]
static void Main()
{
var p = new CSharpPendulum();
}
public CSharpPendulum()
{
_form = new Form() { Text = "Pendulum", Width = 200, Height = 200 };
_timer = new Timer() { Interval = 30 };
_timer.Tick += delegate(object sender, EventArgs e)
{
int anchorX = (_form.Width / 2) - 12,
anchorY = _form.Height / 4,
ballX = anchorX + (int)(Math.Sin(_angle) * _length),
ballY = anchorY + (int)(Math.Cos(_angle) * _length);
_angleAccel = -9.81 / _length * Math.Sin(_angle);
_angleVelocity += _angleAccel * _dt;
_angle += _angleVelocity * _dt;
Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);
Graphics g = Graphics.FromImage(dblBuffer);
Graphics f = Graphics.FromHwnd(_form.Handle);
g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));
g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);
g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);
f.Clear(Color.White);
f.DrawImage(dblBuffer, new Point(0, 0));
};
_timer.Start();
Application.Run(_form);
}
}
| #ifndef __wxPendulumDlg_h__
#define __wxPendulumDlg_h__
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/dialog.h>
#else
#include <wx/wxprec.h>
#endif
#include <wx/timer.h>
#include <wx/dcbuffer.h>
#include <cmath>
class wxPendulumDlgApp : public wxApp
{
public:
bool OnInit();
int OnExit();
};
class wxPendulumDlg : public wxDialog
{
public:
wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("wxPendulum"),
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);
virtual ~wxPendulumDlg();
void wxPendulumDlgPaint(wxPaintEvent& event);
void wxPendulumDlgSize(wxSizeEvent& event);
void OnTimer(wxTimerEvent& event);
private:
wxTimer *m_timer;
unsigned int m_uiLength;
double m_Angle;
double m_AngleVelocity;
enum wxIDs
{
ID_WXTIMER1 = 1001,
ID_DUMMY_VALUE_
};
void OnClose(wxCloseEvent& event);
void CreateGUIControls();
DECLARE_EVENT_TABLE()
};
#endif
|
Keep all operations the same but rewrite the snippet in C++. | using System;
using System.Collections.Generic;
using System.Text;
public class HeapSortClass
{
public static void HeapSort<T>(T[] array)
{
HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);
}
public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)
{
HeapSort<T>(array, offset, length, comparer.Compare);
}
public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)
{
for (int i = 0; i < length; i++)
{
int index = i;
T item = array[offset + i];
while (index > 0 &&
comparison(array[offset + (index - 1) / 2], item) < 0)
{
int top = (index - 1) / 2;
array[offset + index] = array[offset + top];
index = top;
}
array[offset + index] = item;
}
for (int i = length - 1; i > 0; i--)
{
T last = array[offset + i];
array[offset + i] = array[offset];
int index = 0;
while (index * 2 + 1 < i)
{
int left = index * 2 + 1, right = left + 1;
if (right < i && comparison(array[offset + left], array[offset + right]) < 0)
{
if (comparison(last, array[offset + right]) > 0) break;
array[offset + index] = array[offset + right];
index = right;
}
else
{
if (comparison(last, array[offset + left]) > 0) break;
array[offset + index] = array[offset + left];
index = left;
}
}
array[offset + index] = last;
}
}
static void Main()
{
byte[] r = {5, 4, 1, 2};
HeapSort(r);
string[] s = { "-", "D", "a", "33" };
HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);
}
}
| #include <algorithm>
#include <iterator>
#include <iostream>
template<typename RandomAccessIterator>
void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {
std::make_heap(begin, end);
std::sort_heap(begin, end);
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
heap_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
|
Ensure the translated C++ code behaves exactly like the original C# snippet. | using System;
using System.Linq;
using System.Collections.Generic;
public struct Card
{
public Card(string rank, string suit) : this()
{
Rank = rank;
Suit = suit;
}
public string Rank { get; }
public string Suit { get; }
public override string ToString() => $"{Rank} of {Suit}";
}
public class Deck : IEnumerable<Card>
{
static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
readonly List<Card> cards;
public Deck() {
cards = (from suit in suits
from rank in ranks
select new Card(rank, suit)).ToList();
}
public int Count => cards.Count;
public void Shuffle() {
var random = new Random();
for (int i = 0; i < cards.Count; i++) {
int r = random.Next(i, cards.Count);
var temp = cards[i];
cards[i] = cards[r];
cards[r] = temp;
}
}
public Card Deal() {
int last = cards.Count - 1;
Card card = cards[last];
cards.RemoveAt(last);
return card;
}
public IEnumerator<Card> GetEnumerator() {
for (int i = cards.Count - 1; i >= 0; i--)
yield return cards[i];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
| #include <deque>
#include <algorithm>
#include <ostream>
#include <iterator>
namespace cards
{
class card
{
public:
enum pip_type { two, three, four, five, six, seven, eight, nine, ten,
jack, queen, king, ace, pip_count };
enum suite_type { hearts, spades, diamonds, clubs, suite_count };
enum { unique_count = pip_count * suite_count };
card(suite_type s, pip_type p): value(s + suite_count * p) {}
explicit card(unsigned char v = 0): value(v) {}
pip_type pip() { return pip_type(value / suite_count); }
suite_type suite() { return suite_type(value % suite_count); }
private:
unsigned char value;
};
const char* const pip_names[] =
{ "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
"jack", "queen", "king", "ace" };
std::ostream& operator<<(std::ostream& os, card::pip_type pip)
{
return os << pip_names[pip];
}
const char* const suite_names[] =
{ "hearts", "spades", "diamonds", "clubs" };
std::ostream& operator<<(std::ostream& os, card::suite_type suite)
{
return os << suite_names[suite];
}
std::ostream& operator<<(std::ostream& os, card c)
{
return os << c.pip() << " of " << c.suite();
}
class deck
{
public:
deck()
{
for (int i = 0; i < card::unique_count; ++i) {
cards.push_back(card(i));
}
}
void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }
card deal() { card c = cards.front(); cards.pop_front(); return c; }
typedef std::deque<card>::const_iterator const_iterator;
const_iterator begin() const { return cards.cbegin(); }
const_iterator end() const { return cards.cend(); }
private:
std::deque<card> cards;
};
inline std::ostream& operator<<(std::ostream& os, const deck& d)
{
std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n"));
return os;
}
}
|
Change the programming language of this snippet from C# to C++ without modifying what it does. | int[] numbers = new int[10];
| #include <array>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
template <typename Array>
void demonstrate(Array& array)
{
array[2] = "Three";
array.at(1) = "Two";
std::reverse(begin(array), end(array));
std::for_each(begin(array), end(array),
[](typename Array::value_type const& element)
{
std::cout << element << ' ';
});
std::cout << '\n';
}
int main()
{
auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" };
auto dynamic_array = std::vector<std::string>{ "One", "Four" };
dynamic_array.push_back("Eight");
demonstrate(fixed_size_array);
demonstrate(dynamic_array);
}
|
Generate a C++ translation of this C# snippet without changing its computational steps. | int[] numbers = new int[10];
| #include <array>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
template <typename Array>
void demonstrate(Array& array)
{
array[2] = "Three";
array.at(1) = "Two";
std::reverse(begin(array), end(array));
std::for_each(begin(array), end(array),
[](typename Array::value_type const& element)
{
std::cout << element << ' ';
});
std::cout << '\n';
}
int main()
{
auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" };
auto dynamic_array = std::vector<std::string>{ "One", "Four" };
dynamic_array.push_back("Eight");
demonstrate(fixed_size_array);
demonstrate(dynamic_array);
}
|
Please provide an equivalent version of this C# code in C++. | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List<string> NextCarpet(List<string> carpet)
{
return carpet.Select(x => x + x + x)
.Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))
.Concat(carpet.Select(x => x + x + x)).ToList();
}
static List<string> SierpinskiCarpet(int n)
{
return Enumerable.Range(1, n).Aggregate(new List<string> { "#" }, (carpet, _) => NextCarpet(carpet));
}
static void Main(string[] args)
{
foreach (string s in SierpinskiCarpet(3))
Console.WriteLine(s);
}
}
|
#include <cstdint>
#include <cstdlib>
#include <cstdio>
static constexpr int32_t bct_low_bits = 0x55555555;
static int32_t bct_decrement(int32_t v) {
--v;
return v ^ (v & (v>>1) & bct_low_bits);
}
int main (int argc, char *argv[])
{
const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;
if (n < 0 || 9 < n) {
std::printf("N out of range (use 0..9): %ld\n", long(n));
return 1;
}
const int32_t size_bct = 1<<(n*2);
int32_t y = size_bct;
do {
y = bct_decrement(y);
int32_t x = size_bct;
do {
x = bct_decrement(x);
std::putchar((x & y & bct_low_bits) ? ' ' : '#');
} while (0 < x);
std::putchar('\n');
} while (0 < y);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | using System;
using System.Collections.Generic;
namespace RosettaCode.BogoSort
{
public static class BogoSorter
{
public static void Sort<T>(List<T> list) where T:IComparable
{
while (!list.isSorted())
{
list.Shuffle();
}
}
private static bool isSorted<T>(this IList<T> list) where T:IComparable
{
if(list.Count<=1)
return true;
for (int i = 1 ; i < list.Count; i++)
if(list[i].CompareTo(list[i-1])<0) return false;
return true;
}
private static void Shuffle<T>(this IList<T> list)
{
Random rand = new Random();
for (int i = 0; i < list.Count; i++)
{
int swapIndex = rand.Next(list.Count);
T temp = list[swapIndex];
list[swapIndex] = list[i];
list[i] = temp;
}
}
}
class TestProgram
{
static void Main()
{
List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };
BogoSorter.Sort(testList);
foreach (int i in testList) Console.Write(i + " ");
}
}
}
| #include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
template <typename RandomAccessIterator, typename Predicate>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,
Predicate p) {
std::random_device rd;
std::mt19937 generator(rd());
while (!std::is_sorted(begin, end, p)) {
std::shuffle(begin, end, generator);
}
}
template <typename RandomAccessIterator>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {
bogo_sort(
begin, end,
std::less<
typename std::iterator_traits<RandomAccessIterator>::value_type>());
}
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
bogo_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
|
Convert this C# snippet to C++ and keep its semantics consistent. | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
public static class MergeAndAggregateDatasets
{
public static void Main()
{
string patientsCsv = @"
PATIENT_ID,LASTNAME
1001,Hopper
4004,Wirth
3003,Kemeny
2002,Gosling
5005,Kurtz";
string visitsCsv = @"
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";
string format = "yyyy-MM-dd";
var formatProvider = new DateTimeFormat(format).FormatProvider;
var patients = ParseCsv(
patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),
line => (PatientId: int.Parse(line[0]), LastName: line[1]));
var visits = ParseCsv(
visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),
line => (
PatientId: int.Parse(line[0]),
VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),
Score: double.TryParse(line[2], out double score) ? score : default(double?)
)
);
var results =
patients.GroupJoin(visits,
p => p.PatientId,
v => v.PatientId,
(p, vs) => (
p.PatientId,
p.LastName,
LastVisit: vs.Max(v => v.VisitDate),
ScoreSum: vs.Sum(v => v.Score),
ScoreAvg: vs.Average(v => v.Score)
)
).OrderBy(r => r.PatientId);
Console.WriteLine("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |");
foreach (var r in results) {
Console.WriteLine($"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format) ?? "",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |");
}
}
private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)
{
for (int i = 1; i < contents.Length; i++) {
var line = contents[i].Split(',');
yield return constructor(line);
}
}
}
| #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> {
{"1001", "Hopper"},
{"4004", "Wirth"},
{"3003", "Kemeny"},
{"2002", "Gosling"},
{"5005", "Kurtz"}};
auto visits = vector<Visit> {
{"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}};
sort(patients.begin(), patients.end(),
[](const auto& a, const auto&b){ return a.ID < b.ID;});
cout << "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n";
for(const auto& patient : patients)
{
string lastVisit;
float sum = 0;
int numScores = 0;
auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};
for(const auto& visit : visits | views::filter( patientFilter ))
{
if(visit.Score)
{
sum += *visit.Score;
numScores++;
}
lastVisit = max(lastVisit, visit.Date);
}
cout << "| " << patient.ID << " | ";
cout.width(8); cout << patient.LastName << " | ";
cout.width(10); cout << lastVisit << " | ";
if(numScores > 0)
{
cout.width(9); cout << sum << " | ";
cout.width(9); cout << (sum / float(numScores));
}
else cout << " | ";
cout << " |\n";
}
}
|
Keep all operations the same but rewrite the snippet in C++. | using System;
namespace prog
{
class MainClass
{
const float T0 = 100f;
const float TR = 20f;
const float k = 0.07f;
readonly static float[] delta_t = {2.0f,5.0f,10.0f};
const int n = 100;
public delegate float func(float t);
static float NewtonCooling(float t)
{
return -k * (t-TR);
}
public static void Main (string[] args)
{
func f = new func(NewtonCooling);
for(int i=0; i<delta_t.Length; i++)
{
Console.WriteLine("delta_t = " + delta_t[i]);
Euler(f,T0,n,delta_t[i]);
}
}
public static void Euler(func f, float y, int n, float h)
{
for(float x=0; x<=n; x+=h)
{
Console.WriteLine("\t" + x + "\t" + y);
y += h * f(y);
}
}
}
}
| #include <iomanip>
#include <iostream>
typedef double F(double,double);
void euler(F f, double y0, double a, double b, double h)
{
double y = y0;
for (double t = a; t < b; t += h)
{
std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n";
y += h * f(t, y);
}
std::cout << "done\n";
}
double newtonCoolingLaw(double, double t)
{
return -0.07 * (t - 20);
}
int main()
{
euler(newtonCoolingLaw, 100, 0, 100, 2);
euler(newtonCoolingLaw, 100, 0, 100, 5);
euler(newtonCoolingLaw, 100, 0, 100, 10);
}
|
Change the following C# code into C++ without altering its purpose. | using System;
using System.Diagnostics;
namespace sons
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i < 23; i++)
Console.WriteLine(nonsqr(i));
for (int i = 1; i < 1000000; i++)
{
double j = Math.Sqrt(nonsqr(i));
Debug.Assert(j != Math.Floor(j),"Square");
}
}
static int nonsqr(int i)
{
return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));
}
}
}
| #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <boost/bind.hpp>
#include <iterator>
double nextNumber( double number ) {
return number + floor( 0.5 + sqrt( number ) ) ;
}
int main( ) {
std::vector<double> non_squares ;
typedef std::vector<double>::iterator SVI ;
non_squares.reserve( 1000000 ) ;
for ( double i = 1.0 ; i < 100001.0 ; i += 1 )
non_squares.push_back( nextNumber( i ) ) ;
std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,
std::ostream_iterator<double>(std::cout, " " ) ) ;
std::cout << '\n' ;
SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,
boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;
if ( found != non_squares.end( ) ) {
std::cout << "Found a square number in the sequence!\n" ;
std::cout << "It is " << *found << " !\n" ;
}
else {
std::cout << "Up to 1000000, found no square number in the sequence!\n" ;
}
return 0 ;
}
|
Convert this C# snippet to C++ and keep its semantics consistent. | using System;
namespace SubString
{
class Program
{
static void Main(string[] args)
{
string s = "0123456789";
const int n = 3;
const int m = 2;
const char c = '3';
const string z = "345";
Console.WriteLine(s.Substring(n, m));
Console.WriteLine(s.Substring(n, s.Length - n));
Console.WriteLine(s.Substring(0, s.Length - 1));
Console.WriteLine(s.Substring(s.IndexOf(c), m));
Console.WriteLine(s.Substring(s.IndexOf(z), m));
}
}
}
| #include <iostream>
#include <string>
int main()
{
std::string s = "0123456789";
int const n = 3;
int const m = 4;
char const c = '2';
std::string const sub = "456";
std::cout << s.substr(n, m)<< "\n";
std::cout << s.substr(n) << "\n";
std::cout << s.substr(0, s.size()-1) << "\n";
std::cout << s.substr(s.find(c), m) << "\n";
std::cout << s.substr(s.find(sub), m) << "\n";
}
|
Write the same algorithm in C++ as shown in this C# implementation. | using System;
class Program
{
public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>
{
T[] originalArray = (T[]) array.Clone();
Array.Sort(array);
for (var i = 0; i < originalArray.Length; i++)
{
if (!Equals(originalArray[i], array[i]))
{
return false;
}
}
return true;
}
}
| #include <algorithm>
#include <string>
#include <iostream>
#include <iterator>
class jortSort {
public:
template<class T>
bool jort_sort( T* o, size_t s ) {
T* n = copy_array( o, s );
sort_array( n, s );
bool r = false;
if( n ) {
r = check( o, n, s );
delete [] n;
}
return r;
}
private:
template<class T>
T* copy_array( T* o, size_t s ) {
T* z = new T[s];
memcpy( z, o, s * sizeof( T ) );
return z;
}
template<class T>
void sort_array( T* n, size_t s ) {
std::sort( n, n + s );
}
template<class T>
bool check( T* n, T* o, size_t s ) {
for( size_t x = 0; x < s; x++ )
if( n[x] != o[x] ) return false;
return true;
}
};
jortSort js;
template<class T>
void displayTest( T* o, size_t s ) {
std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) );
std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n";
}
int main( int argc, char* argv[] ) {
const size_t s = 5;
std::string oStr[] = { "5", "A", "D", "R", "S" };
displayTest( oStr, s );
std::swap( oStr[0], oStr[1] );
displayTest( oStr, s );
int oInt[] = { 1, 2, 3, 4, 5 };
displayTest( oInt, s );
std::swap( oInt[0], oInt[1] );
displayTest( oInt, s );
return 0;
}
|
Please provide an equivalent version of this C# code in C++. | using System;
class Program
{
static void Main()
{
foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })
{
Console.WriteLine("{0} is {1}a leap year.",
year,
DateTime.IsLeapYear(year) ? string.Empty : "not ");
}
}
}
| #include <iostream>
bool is_leap_year(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
int main() {
for (auto year : {1900, 1994, 1996, 1997, 2000}) {
std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n";
}
}
|
Generate a C++ translation of this C# snippet without changing its computational steps. | using static System.Console;
using static System.Linq.Enumerable;
public class Program
{
public static void Main() {
foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($"{n}: {string.Join(", ", LexOrder(n))}");
}
public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());
}
| #include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
void lexicographical_sort(std::vector<int>& numbers) {
std::vector<std::string> strings(numbers.size());
std::transform(numbers.begin(), numbers.end(), strings.begin(),
[](int i) { return std::to_string(i); });
std::sort(strings.begin(), strings.end());
std::transform(strings.begin(), strings.end(), numbers.begin(),
[](const std::string& s) { return std::stoi(s); });
}
std::vector<int> lexicographically_sorted_vector(int n) {
std::vector<int> numbers(n >= 1 ? n : 2 - n);
std::iota(numbers.begin(), numbers.end(), std::min(1, n));
lexicographical_sort(numbers);
return numbers;
}
template <typename T>
void print_vector(std::ostream& out, const std::vector<T>& v) {
out << '[';
if (!v.empty()) {
auto i = v.begin();
out << *i++;
for (; i != v.end(); ++i)
out << ',' << *i;
}
out << "]\n";
}
int main(int argc, char** argv) {
for (int i : { 0, 5, 13, 21, -22 }) {
std::cout << i << ": ";
print_vector(std::cout, lexicographically_sorted_vector(i));
}
return 0;
}
|
Change the following C# code into C++ without altering its purpose. | using System;
class NumberNamer {
static readonly string[] incrementsOfOne =
{ "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
static readonly string[] incrementsOfTen =
{ "", "", "twenty", "thirty", "fourty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
const string millionName = "million",
thousandName = "thousand",
hundredName = "hundred",
andName = "and";
public static string GetName( int i ) {
string output = "";
if( i >= 1000000 ) {
output += ParseTriplet( i / 1000000 ) + " " + millionName;
i %= 1000000;
if( i == 0 ) return output;
}
if( i >= 1000 ) {
if( output.Length > 0 ) {
output += ", ";
}
output += ParseTriplet( i / 1000 ) + " " + thousandName;
i %= 1000;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += ", ";
}
output += ParseTriplet( i );
return output;
}
static string ParseTriplet( int i ) {
string output = "";
if( i >= 100 ) {
output += incrementsOfOne[i / 100] + " " + hundredName;
i %= 100;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += " " + andName + " ";
}
if( i >= 20 ) {
output += incrementsOfTen[i / 10];
i %= 10;
if( i == 0 ) return output;
}
if( output.Length > 0 ) {
output += " ";
}
output += incrementsOfOne[i];
return output;
}
}
class Program {
static void Main( string[] args ) {
Console.WriteLine( NumberNamer.GetName( 1 ) );
Console.WriteLine( NumberNamer.GetName( 234 ) );
Console.WriteLine( NumberNamer.GetName( 31337 ) );
Console.WriteLine( NumberNamer.GetName( 987654321 ) );
}
}
| #include <string>
#include <iostream>
using std::string;
const char* smallNumbers[] = {
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten",
"eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"
};
string spellHundreds(unsigned n) {
string res;
if (n > 99) {
res = smallNumbers[n/100];
res += " hundred";
n %= 100;
if (n) res += " and ";
}
if (n >= 20) {
static const char* Decades[] = {
"", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"
};
res += Decades[n/10];
n %= 10;
if (n) res += "-";
}
if (n < 20 && n > 0)
res += smallNumbers[n];
return res;
}
const char* thousandPowers[] = {
" billion", " million", " thousand", "" };
typedef unsigned long Spellable;
string spell(Spellable n) {
if (n < 20) return smallNumbers[n];
string res;
const char** pScaleName = thousandPowers;
Spellable scaleFactor = 1000000000;
while (scaleFactor > 0) {
if (n >= scaleFactor) {
Spellable h = n / scaleFactor;
res += spellHundreds(h) + *pScaleName;
n %= scaleFactor;
if (n) res += ", ";
}
scaleFactor /= 1000;
++pScaleName;
}
return res;
}
int main() {
#define SPELL_IT(x) std::cout << #x " " << spell(x) << std::endl;
SPELL_IT( 99);
SPELL_IT( 300);
SPELL_IT( 310);
SPELL_IT( 1501);
SPELL_IT( 12609);
SPELL_IT( 512609);
SPELL_IT(43112609);
SPELL_IT(1234567890);
return 0;
}
|
Generate a C++ translation of this C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
namespace example
{
class Program
{
static void Main(string[] args)
{
var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(strings);
}
private static void compareAndReportStringsLength(string[] strings)
{
if (strings.Length > 0)
{
char Q = '"';
string hasLength = " has length ";
string predicateMax = " and is the longest string";
string predicateMin = " and is the shortest string";
string predicateAve = " and is neither the longest nor the shortest string";
string predicate;
(int, int)[] li = new (int, int)[strings.Length];
for (int i = 0; i < strings.Length; i++)
li[i] = (strings[i].Length, i);
Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);
int maxLength = li[0].Item1;
int minLength = li[strings.Length - 1].Item1;
for (int i = 0; i < strings.Length; i++)
{
int length = li[i].Item1;
string str = strings[li[i].Item2];
if (length == maxLength)
predicate = predicateMax;
else if (length == minLength)
predicate = predicateMin;
else
predicate = predicateAve;
Console.WriteLine(Q + str + Q + hasLength + length + predicate);
}
}
}
}
}
| #include <iostream>
#include <algorithm>
#include <string>
#include <list>
using namespace std;
bool cmp(const string& a, const string& b)
{
return b.length() < a.length();
}
void compareAndReportStringsLength(list<string> listOfStrings)
{
if (!listOfStrings.empty())
{
char Q = '"';
string has_length(" has length ");
string predicate_max(" and is the longest string");
string predicate_min(" and is the shortest string");
string predicate_ave(" and is neither the longest nor the shortest string");
list<string> ls(listOfStrings);
ls.sort(cmp);
int max = ls.front().length();
int min = ls.back().length();
for (list<string>::iterator s = ls.begin(); s != ls.end(); s++)
{
int length = s->length();
string* predicate;
if (length == max)
predicate = &predicate_max;
else if (length == min)
predicate = &predicate_min;
else
predicate = &predicate_ave;
cout << Q << *s << Q << has_length << length << *predicate << endl;
}
}
}
int main(int argc, char* argv[])
{
list<string> listOfStrings{ "abcd", "123456789", "abcdef", "1234567" };
compareAndReportStringsLength(listOfStrings);
return EXIT_SUCCESS;
}
|
Generate a C++ translation of this C# snippet without changing its computational steps. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Program
{
static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)
{
var dictionary = new SortedDictionary<TItem, int>();
foreach (var item in items)
{
if (dictionary.ContainsKey(item))
{
dictionary[item]++;
}
else
{
dictionary[item] = 1;
}
}
return dictionary;
}
static void Main(string[] arguments)
{
var file = arguments.FirstOrDefault();
if (File.Exists(file))
{
var text = File.ReadAllText(file);
foreach (var entry in GetFrequencies(text))
{
Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
}
}
}
}
| #include <fstream>
#include <iostream>
int main()
{
std::ifstream input("filename.txt", std::ios_base::binary);
if (!input)
{
std::cerr << "error: can't open file\n";
return -1;
}
size_t count[256];
std::fill_n(count, 256, 0);
for (char c; input.get(c); ++count[uint8_t(c)])
;
for (size_t i = 0; i < 256; ++i)
{
if (count[i] && isgraph(i))
{
std::cout << char(i) << " = " << count[i] << '\n';
}
}
}
|
Translate the given C# code snippet into C++ without altering its behavior. | string s = "12345";
s = (int.Parse(s) + 1).ToString();
using System.Numerics;
string bis = "123456789012345678999999999";
bis = (BigInteger.Parse(bis) + 1).ToString();
|
#include <cstdlib>
#include <string>
#include <sstream>
std::string s = "12345";
int i;
std::istringstream(s) >> i;
i++;
std::ostringstream oss;
if (oss << i) s = oss.str();
|
Produce a functionally identical C++ code for the snippet given in C#. | using System;
public static string RemoveCharactersFromString(string testString, string removeChars)
{
char[] charAry = removeChars.ToCharArray();
string returnString = testString;
foreach (char c in charAry)
{
while (returnString.IndexOf(c) > -1)
{
returnString = returnString.Remove(returnString.IndexOf(c), 1);
}
}
return returnString;
}
| #include <algorithm>
#include <iostream>
#include <string>
std::string stripchars(std::string str, const std::string &chars)
{
str.erase(
std::remove_if(str.begin(), str.end(), [&](char c){
return chars.find(c) != std::string::npos;
}),
str.end()
);
return str;
}
int main()
{
std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n';
return 0;
}
|
Can you help me rewrite this code in C++ instead of C#, keeping it the same logically? | using System;
using System.Linq;
class Program
{
static void Main()
{
Console.WriteLine(new[] { 1, 2, 3 }.Average());
}
}
| #include <vector>
double mean(const std::vector<double>& numbers)
{
if (numbers.size() == 0)
return 0;
double sum = 0;
for (std::vector<double>::iterator i = numbers.begin(); i != numbers.end(); i++)
sum += *i;
return sum / numbers.size();
}
|
Write the same code in C++ as shown below in C#. | using System;
using System.Collections.Generic;
namespace Entropy
{
class Program
{
public static double logtwo(double num)
{
return Math.Log(num)/Math.Log(2);
}
public static void Main(string[] args)
{
label1:
string input = Console.ReadLine();
double infoC=0;
Dictionary<char,double> table = new Dictionary<char, double>();
foreach (char c in input)
{
if (table.ContainsKey(c))
table[c]++;
else
table.Add(c,1);
}
double freq;
foreach (KeyValuePair<char,double> letter in table)
{
freq=letter.Value/input.Length;
infoC+=freq*logtwo(freq);
}
infoC*=-1;
Console.WriteLine("The Entropy of {0} is {1}",input,infoC);
goto label1;
}
}
}
| #include <string>
#include <map>
#include <iostream>
#include <algorithm>
#include <cmath>
double log2( double number ) {
return log( number ) / log( 2 ) ;
}
int main( int argc , char *argv[ ] ) {
std::string teststring( argv[ 1 ] ) ;
std::map<char , int> frequencies ;
for ( char c : teststring )
frequencies[ c ] ++ ;
int numlen = teststring.length( ) ;
double infocontent = 0 ;
for ( std::pair<char , int> p : frequencies ) {
double freq = static_cast<double>( p.second ) / numlen ;
infocontent -= freq * log2( freq ) ;
}
std::cout << "The information content of " << teststring
<< " is " << infocontent << std::endl ;
return 0 ;
}
|
Generate an equivalent C++ version of this C# code. | using System;
using System.Text;
using System.Collections.Generic;
public class TokenizeAStringWithEscaping
{
public static void Main() {
string testcase = "one^|uno||three^^^^|four^^^|^cuatro|";
foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {
Console.WriteLine(": " + token);
}
}
}
public static class Extensions
{
public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {
if (input == null) yield break;
var buffer = new StringBuilder();
bool escaping = false;
foreach (char c in input) {
if (escaping) {
buffer.Append(c);
escaping = false;
} else if (c == escape) {
escaping = true;
} else if (c == separator) {
yield return buffer.Flush();
} else {
buffer.Append(c);
}
}
if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();
}
public static string Flush(this StringBuilder stringBuilder) {
string result = stringBuilder.ToString();
stringBuilder.Clear();
return result;
}
}
| #include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
vector<string> tokenize(const string& input, char seperator, char escape) {
vector<string> output;
string token;
bool inEsc = false;
for (char ch : input) {
if (inEsc) {
inEsc = false;
} else if (ch == escape) {
inEsc = true;
continue;
} else if (ch == seperator) {
output.push_back(token);
token = "";
continue;
}
token += ch;
}
if (inEsc)
throw new invalid_argument("Invalid terminal escape");
output.push_back(token);
return output;
}
int main() {
string sample = "one^|uno||three^^^^|four^^^|^cuatro|";
cout << sample << endl;
cout << '[';
for (auto t : tokenize(sample, '|', '^')) {
cout << '"' << t << "\", ";
}
cout << ']' << endl;
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original C# snippet. | Using System;
namespace HelloWorld {
class Program
{
static void Main()
{
Console.Writeln("Hello World!");
}
}
}
| #include <iostream>
int main () {
std::cout << "Hello world!" << std::endl;
}
|
Translate this program into C++ but keep the logic exactly as in C#. | using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)
{
switch (order)
{
case 0u:
return sequence;
case 1u:
return sequence.Skip(1).Zip(sequence, (next, current) => next - current);
default:
return ForwardDifference(ForwardDifference(sequence), order - 1u);
}
}
static void Main()
{
IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };
do
{
Console.WriteLine(string.Join(", ", sequence));
} while ((sequence = ForwardDifference(sequence)).Any());
}
}
| #include <vector>
#include <iterator>
#include <algorithm>
template<typename InputIterator, typename OutputIterator>
OutputIterator forward_difference(InputIterator first, InputIterator last,
OutputIterator dest)
{
if (first == last)
return dest;
typedef typename std::iterator_traits<InputIterator>::value_type value_type;
value_type temp = *first++;
while (first != last)
{
value_type temp2 = *first++;
*dest++ = temp2 - temp;
temp = temp2;
}
return dest;
}
template<typename InputIterator, typename OutputIterator>
OutputIterator nth_forward_difference(int order,
InputIterator first, InputIterator last,
OutputIterator dest)
{
if (order == 0)
return std::copy(first, last, dest);
if (order == 1)
return forward_difference(first, last, dest);
typedef typename std::iterator_traits<InputIterator>::value_type value_type;
std::vector<value_type> temp_storage;
forward_difference(first, last, std::back_inserter(temp_storage));
typename std::vector<value_type>::iterator begin = temp_storage.begin(),
end = temp_storage.end();
for (int i = 1; i < order-1; ++i)
end = forward_difference(begin, end, begin);
return forward_difference(begin, end, dest);
}
#include <iostream>
int main()
{
double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 };
std::vector<double> dest;
nth_forward_difference(1, array, array+10, std::back_inserter(dest));
std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
double* end = nth_forward_difference(3, array, array+10, array);
for (double* p = array; p < end; ++p)
std::cout << *p << " ";
std::cout << std::endl;
return 0;
}
|
Write the same algorithm in C++ as shown in this C# implementation. | static bool isPrime(int n)
{
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
| #include <cmath>
bool is_prime(unsigned int n)
{
if (n <= 1)
return false;
if (n == 2)
return true;
for (unsigned int i = 2; i <= sqrt(n); ++i)
if (n % i == 0)
return false;
return true;
}
|
Produce a functionally identical C++ code for the snippet given in C#. | using System;
namespace BinomialCoefficients
{
class Program
{
static void Main(string[] args)
{
ulong n = 1000000, k = 3;
ulong result = biCoefficient(n, k);
Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result);
Console.ReadLine();
}
static int fact(int n)
{
if (n == 0) return 1;
else return n * fact(n - 1);
}
static ulong biCoefficient(ulong n, ulong k)
{
if (k > n - k)
{
k = n - k;
}
ulong c = 1;
for (uint i = 0; i < k; i++)
{
c = c * (n - i);
c = c / (i + 1);
}
return c;
}
}
}
| double Factorial(double nValue)
{
double result = nValue;
double result_next;
double pc = nValue;
do
{
result_next = result*(pc-1);
result = result_next;
pc--;
}while(pc>2);
nValue = result;
return nValue;
}
double binomialCoefficient(double n, double k)
{
if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0;
if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;
return Factorial(n) /(Factorial(k)*Factorial((n - k)));
}
|
Convert the following code from C# to C++, ensuring the logic remains intact. |
int[] intArray = new int[5] { 1, 2, 3, 4, 5 };
int[] intArray = new int[]{ 1, 2, 3, 4, 5 };
int[] intArray = { 1, 2, 3, 4, 5 };
string[] stringArr = new string[5];
stringArr[0] = "string";
| int a[5];
a[0] = 1;
int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
#include <string>
std::string strings[4];
|
Rewrite the snippet below in C++ so it works the same as the original C# code. | var current = [head of list to traverse]
while(current != null)
{
current = current.Next;
}
| #include <iostream>
#include <forward_list>
int main()
{
std::forward_list<int> list{1, 2, 3, 4, 5};
for (int e : list)
std::cout << e << std::endl;
}
|
Convert this C# snippet to C++ and keep its semantics consistent. | using System;
using System.IO;
class PPMWriter
{
public static void WriteBitmapToPPM(string file, Bitmap bitmap)
{
var writer = new StreamWriter(file);
writer.WriteLine("P6");
writer.WriteLine($"{bitmap.Width} {bitmap.Height}");
writer.WriteLine("255");
writer.Close();
var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));
for (int x = 0; x < bitmap.Height; x++)
for (int y = 0; y < bitmap.Width; y++)
{
Color color = bitmap.GetPixel(y, x);
writerB.Write(color.R);
writerB.Write(color.G);
writerB.Write(color.B);
}
writerB.Close();
}
}
| #include <fstream>
#include <cstdio>
int main() {
constexpr auto dimx = 800u, dimy = 800u;
using namespace std;
ofstream ofs("first.ppm", ios_base::out | ios_base::binary);
ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl;
for (auto j = 0u; j < dimy; ++j)
for (auto i = 0u; i < dimx; ++i)
ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256);
ofs.close();
return EXIT_SUCCESS;
}
|
Can you help me rewrite this code in C++ instead of C#, keeping it the same logically? | using System;
using System.IO;
namespace DeleteFile {
class Program {
static void Main() {
File.Delete("input.txt");
Directory.Delete("docs");
File.Delete("/input.txt");
Directory.Delete("/docs");
}
}
}
| #include <cstdio>
#include <direct.h>
int main() {
remove( "input.txt" );
remove( "/input.txt" );
_rmdir( "docs" );
_rmdir( "/docs" );
return 0;
}
|
Port the following code from C# to C++ with equivalent syntax and logic. | using System;
public static class DiscordianDate
{
static readonly string[] seasons = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" };
static readonly string[] weekdays = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" };
static readonly string[] apostles = { "Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" };
static readonly string[] holidays = { "Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux" };
public static string Discordian(this DateTime date) {
string yold = $" in the YOLD {date.Year + 1166}.";
int dayOfYear = date.DayOfYear;
if (DateTime.IsLeapYear(date.Year)) {
if (dayOfYear == 60) return "St. Tib's day" + yold;
else if (dayOfYear > 60) dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
int seasonNr = dayOfYear / 73;
int weekdayNr = dayOfYear % 5;
string holyday = "";
if (seasonDay == 5) holyday = $" Celebrate {apostles[seasonNr]}!";
else if (seasonDay == 50) holyday = $" Celebrate {holidays[seasonNr]}!";
return $"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}";
}
public static void Main() {
foreach (var (day, month, year) in new [] {
(1, 1, 2010),
(5, 1, 2010),
(19, 2, 2011),
(28, 2, 2012),
(29, 2, 2012),
(1, 3, 2012),
(19, 3, 2013),
(3, 5, 2014),
(31, 5, 2015),
(22, 6, 2016),
(15, 7, 2016),
(12, 8, 2017),
(19, 9, 2018),
(26, 9, 2018),
(24, 10, 2019),
(8, 12, 2020),
(31, 12, 2020)
})
{
Console.WriteLine($"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}");
}
}
}
| #include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
class myTuple
{
public:
void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }
bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }
string second() { return t.second; }
private:
pair<pair<int, int>, string> t;
};
class discordian
{
public:
discordian() {
myTuple t;
t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t );
t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t );
t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t );
t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t );
t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t );
t.set( 8, 12, "Afflux" ); holyday.push_back( t );
seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" );
seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" );
wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" );
wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" );
}
void convert( int d, int m, int y ) {
if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) {
cout << "\nThis is not a date!";
return;
}
vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) );
int dd = d, day, wday, sea, yr = y + 1166;
for( int x = 1; x < m; x++ )
dd += getMaxDay( x, 1 );
day = dd % 73; if( !day ) day = 73;
wday = dd % 5;
sea = ( dd - 1 ) / 73;
if( d == 29 && m == 2 && isLeap( y ) ) {
cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr;
return;
}
cout << wdays[wday] << " " << seasons[sea] << " " << day;
if( day > 10 && day < 14 ) cout << "th";
else switch( day % 10) {
case 1: cout << "st"; break;
case 2: cout << "nd"; break;
case 3: cout << "rd"; break;
default: cout << "th";
}
cout << ", Year of Our Lady of Discord " << yr;
if( f != holyday.end() ) cout << " - " << ( *f ).second();
}
private:
int getMaxDay( int m, int y ) {
int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m];
}
bool isLeap( int y ) {
bool l = false;
if( !( y % 4 ) ) {
if( y % 100 ) l = true;
else if( !( y % 400 ) ) l = true;
}
return l;
}
vector<myTuple> holyday; vector<string> seasons, wdays;
};
int main( int argc, char* argv[] ) {
string date; discordian disc;
while( true ) {
cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break;
if( date.length() == 10 ) {
istringstream iss( date );
vector<string> vc;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );
disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) );
cout << "\n\n\n";
} else cout << "\nIs this a date?!\n\n";
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | #include <random>
#include <random>
#include <vector>
#include <iostream>
#define MAX_N 20
#define TIMES 1000000
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<> dis;
int randint(int n) {
int r, rmax = RAND_MAX / n * n;
dis=std::uniform_int_distribution<int>(0,rmax) ;
r = dis(gen);
return r / (RAND_MAX / n);
}
unsigned long long factorial(size_t n) {
static std::vector<unsigned long long>factorials{1,1,2};
for (;factorials.size() <= n;)
factorials.push_back(((unsigned long long) factorials.back())*factorials.size());
return factorials[n];
}
long double expected(size_t n) {
long double sum = 0;
for (size_t i = 1; i <= n; i++)
sum += factorial(n) / pow(n, i) / factorial(n - i);
return sum;
}
int test(int n, int times) {
int i, count = 0;
for (i = 0; i < times; i++) {
unsigned int x = 1, bits = 0;
while (!(bits & x)) {
count++;
bits |= x;
x = static_cast<unsigned int>(1 << randint(n));
}
}
return count;
}
int main() {
puts(" n\tavg\texp.\tdiff\n-------------------------------");
int n;
for (n = 1; n <= MAX_N; n++) {
int cnt = test(n, TIMES);
long double avg = (double)cnt / TIMES;
long double theory = expected(static_cast<size_t>(n));
long double diff = (avg / theory - 1) * 100;
printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));
}
return 0;
}
| public class AverageLoopLength {
private static int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.Next(n);
}
var seen = new HashSet<double>(n);
int current = 0;
int length = 0;
while (seen.Add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void Main(string[] args) {
Console.WriteLine(" N average analytical (error)");
Console.WriteLine("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
var average = AverageLoopLength.average(i);
var analytical = AverageLoopLength.analytical(i);
Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100);
}
}
}
|
Ensure the translated C++ code behaves exactly like the original C# snippet. | public class AverageLoopLength {
private static int N = 100000;
private static double analytical(int n) {
double[] factorial = new double[n + 1];
double[] powers = new double[n + 1];
powers[0] = 1.0;
factorial[0] = 1.0;
for (int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
powers[i] = powers[i - 1] * n;
}
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial[n] / factorial[n - i] / powers[i];
}
return sum;
}
private static double average(int n) {
Random rnd = new Random();
double sum = 0.0;
for (int a = 0; a < N; a++) {
int[] random = new int[n];
for (int i = 0; i < n; i++) {
random[i] = rnd.Next(n);
}
var seen = new HashSet<double>(n);
int current = 0;
int length = 0;
while (seen.Add(current)) {
length++;
current = random[current];
}
sum += length;
}
return sum / N;
}
public static void Main(string[] args) {
Console.WriteLine(" N average analytical (error)");
Console.WriteLine("=== ========= ============ =========");
for (int i = 1; i <= 20; i++) {
var average = AverageLoopLength.average(i);
var analytical = AverageLoopLength.analytical(i);
Console.WriteLine("{0,3} {1,10:N4} {2,13:N4} {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100);
}
}
}
| #include <random>
#include <random>
#include <vector>
#include <iostream>
#define MAX_N 20
#define TIMES 1000000
static std::random_device rd;
static std::mt19937 gen(rd());
static std::uniform_int_distribution<> dis;
int randint(int n) {
int r, rmax = RAND_MAX / n * n;
dis=std::uniform_int_distribution<int>(0,rmax) ;
r = dis(gen);
return r / (RAND_MAX / n);
}
unsigned long long factorial(size_t n) {
static std::vector<unsigned long long>factorials{1,1,2};
for (;factorials.size() <= n;)
factorials.push_back(((unsigned long long) factorials.back())*factorials.size());
return factorials[n];
}
long double expected(size_t n) {
long double sum = 0;
for (size_t i = 1; i <= n; i++)
sum += factorial(n) / pow(n, i) / factorial(n - i);
return sum;
}
int test(int n, int times) {
int i, count = 0;
for (i = 0; i < times; i++) {
unsigned int x = 1, bits = 0;
while (!(bits & x)) {
count++;
bits |= x;
x = static_cast<unsigned int>(1 << randint(n));
}
}
return count;
}
int main() {
puts(" n\tavg\texp.\tdiff\n-------------------------------");
int n;
for (n = 1; n <= MAX_N; n++) {
int cnt = test(n, TIMES);
long double avg = (double)cnt / TIMES;
long double theory = expected(static_cast<size_t>(n));
long double diff = (avg / theory - 1) * 100;
printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));
}
return 0;
}
|
Ensure the translated C++ code behaves exactly like the original C# snippet. | class Program
{
static void Main()
{
string extra = "little";
string formatted = $"Mary had a {extra} lamb.";
System.Console.WriteLine(formatted);
}
}
| #include <string>
#include <iostream>
int main( ) {
std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) ,
replacement ( "little" ) ;
std::string newString = original.replace( original.find( "X" ) ,
toBeReplaced.length( ) , replacement ) ;
std::cout << "String after replacement: " << newString << " \n" ;
return 0 ;
}
|
Generate a C++ translation of this C# snippet without changing its computational steps. | class Program
{
static void Main()
{
string extra = "little";
string formatted = $"Mary had a {extra} lamb.";
System.Console.WriteLine(formatted);
}
}
| #include <string>
#include <iostream>
int main( ) {
std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) ,
replacement ( "little" ) ;
std::string newString = original.replace( original.find( "X" ) ,
toBeReplaced.length( ) , replacement ) ;
std::cout << "String after replacement: " << newString << " \n" ;
return 0 ;
}
|
Change the programming language of this snippet from C# to C++ without modifying what it does. | using System;
class Program {
const long Lm = (long)1e18;
const string Fm = "D18";
struct LI { public long lo, ml, mh, hi, tp; }
static void inc(ref LI d, LI s) {
if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }
if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }
if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }
if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }
d.tp += s.tp;
}
static void dec(ref LI d, LI s) {
if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }
if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }
if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }
if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }
d.tp -= s.tp;
}
static LI set(long s) { LI d;
d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }
static string fmt(LI x) {
if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);
return x.lo.ToString();
}
static LI partcount(int n) {
var P = new LI[n + 1]; P[0] = set(1);
for (int i = 1; i <= n; i++) {
int k = 0, d = -2, j = i;
LI x = set(0);
while (true) {
if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;
if ((j -= ++k) >= 0) inc(ref x, P[j]); else break;
if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;
if ((j -= ++k) >= 0) dec(ref x, P[j]); else break;
}
P[i] = x;
}
return P[n];
}
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew ();
var res = partcount(6666); sw.Stop();
Console.Write("{0} {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds);
}
}
| #include <chrono>
#include <iostream>
#include <vector>
#include <gmpxx.h>
using big_int = mpz_class;
big_int partitions(int n) {
std::vector<big_int> p(n + 1);
p[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int k = 1;; ++k) {
int j = (k * (3*k - 1))/2;
if (j > i)
break;
if (k & 1)
p[i] += p[i - j];
else
p[i] -= p[i - j];
j = (k * (3*k + 1))/2;
if (j > i)
break;
if (k & 1)
p[i] += p[i - j];
else
p[i] -= p[i - j];
}
}
return p[n];
}
int main() {
auto start = std::chrono::steady_clock::now();
auto result = partitions(6666);
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double, std::milli> ms(end - start);
std::cout << result << '\n';
std::cout << "elapsed time: " << ms.count() << " milliseconds\n";
}
|
Convert the following code from C# to C++, ensuring the logic remains intact. | using System;
class Program {
const long Lm = (long)1e18;
const string Fm = "D18";
struct LI { public long lo, ml, mh, hi, tp; }
static void inc(ref LI d, LI s) {
if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }
if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }
if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }
if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }
d.tp += s.tp;
}
static void dec(ref LI d, LI s) {
if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }
if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }
if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }
if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }
d.tp -= s.tp;
}
static LI set(long s) { LI d;
d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }
static string fmt(LI x) {
if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);
if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);
return x.lo.ToString();
}
static LI partcount(int n) {
var P = new LI[n + 1]; P[0] = set(1);
for (int i = 1; i <= n; i++) {
int k = 0, d = -2, j = i;
LI x = set(0);
while (true) {
if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;
if ((j -= ++k) >= 0) inc(ref x, P[j]); else break;
if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;
if ((j -= ++k) >= 0) dec(ref x, P[j]); else break;
}
P[i] = x;
}
return P[n];
}
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew ();
var res = partcount(6666); sw.Stop();
Console.Write("{0} {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds);
}
}
| #include <chrono>
#include <iostream>
#include <vector>
#include <gmpxx.h>
using big_int = mpz_class;
big_int partitions(int n) {
std::vector<big_int> p(n + 1);
p[0] = 1;
for (int i = 1; i <= n; ++i) {
for (int k = 1;; ++k) {
int j = (k * (3*k - 1))/2;
if (j > i)
break;
if (k & 1)
p[i] += p[i - j];
else
p[i] -= p[i - j];
j = (k * (3*k + 1))/2;
if (j > i)
break;
if (k & 1)
p[i] += p[i - j];
else
p[i] -= p[i - j];
}
}
return p[n];
}
int main() {
auto start = std::chrono::steady_clock::now();
auto result = partitions(6666);
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double, std::milli> ms(end - start);
std::cout << result << '\n';
std::cout << "elapsed time: " << ms.count() << " milliseconds\n";
}
|
Translate this program into C++ but keep the logic exactly as in C#. | using System;
using static System.Console;
using LI = System.Collections.Generic.SortedSet<int>;
class Program {
static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {
if (lft == 0) res.Add(vlu);
else if (lft > 0) foreach (int itm in set)
res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);
return res; }
static void Main(string[] args) { WriteLine(string.Join(" ",
unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }
}
| #include <cstdio>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum;
for (int x : lst) w.push_back({x, x});
while (w.size() > 0) { auto i = w[0]; w.erase(w.begin());
for (int x : lst) if ((sum = get<1>(i) + x) == 13)
printf("%d%d ", get<0>(i), x);
else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }
return 0; }
|
Generate an equivalent C++ version of this Python code. | def bitwise_built_ins(width, a, b):
mask = (1 << width) - 1
print(f)
def rotr(width, a, n):
"Rotate a, n times to the right"
if n < 0:
return rotl(width, a, -n)
elif n == 0:
return a
else:
mask = (1 << width) - 1
a, n = a & mask, n % width
return ((a >> n)
| ((a & ((1 << n) - 1))
<< (width - n)))
def rotl(width, a, n):
"Rotate a, n times to the left"
if n < 0:
return rotr(width, a, -n)
elif n == 0:
return a
else:
mask = (1 << width) - 1
a, n = a & mask, n % width
return (((a << n) & mask)
| (a >> (width - n)))
def asr(width, a, n):
"Arithmetic shift a, n times to the right. (sign preserving)."
mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)
if n < 0:
return (a << -n) & mask
elif n == 0:
return a
elif n >= width:
return mask if a & top_bit_mask else 0
else:
a = a & mask
if a & top_bit_mask:
signs = (1 << n) - 1
return a >> n | (signs << width - n)
else:
return a >> n
def helper_funcs(width, a):
mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1)
aa = a | top_bit_mask
print(f)
if __name__ == '__main__':
bitwise_built_ins(8, 27, 125)
helper_funcs(8, 27)
| #include <iostream>
void bitwise(int a, int b)
{
std::cout << "a and b: " << (a & b) << '\n';
std::cout << "a or b: " << (a | b) << '\n';
std::cout << "a xor b: " << (a ^ b) << '\n';
std::cout << "not a: " << ~a << '\n';
std::cout << "a shl b: " << (a << b) << '\n';
std::cout << "a shr b: " << (a >> b) << '\n';
unsigned int ua = a;
std::cout << "a lsr b: " << (ua >> b) << '\n';
std::cout << "a rol b: " << std::rotl(ua, b) << '\n';
std::cout << "a ror b: " << std::rotr(ua, b) << '\n';
}
|
Produce a functionally identical C++ code for the snippet given in Python. | l = 3
ints = 13
def setup():
size(700, 600)
background(0, 0, 255)
translate(150, 100)
stroke(255)
turn_left(l, ints)
turn_right(l, ints)
def turn_right(l, ints):
if ints == 0:
line(0, 0, 0, -l)
translate(0, -l)
else:
turn_left(l, ints - 1)
rotate(radians(90))
turn_right(l, ints - 1)
def turn_left(l, ints):
if ints == 0:
line(0, 0, 0, -l)
translate(0, -l)
else:
turn_left(l, ints - 1)
rotate(radians(-90))
turn_right(l, ints - 1)
| #include <windows.h>
#include <iostream>
using namespace std;
const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;
class myBitmap
{
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap()
{
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h )
{
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 )
{
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr )
{
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c )
{
clr = c; createPen();
}
void setPenWidth( int w )
{
wid = w; createPen();
}
void saveBitmap( string path )
{
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen()
{
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp;
HDC hdc;
HPEN pen;
HBRUSH brush;
void *pBits;
int width, height, wid;
DWORD clr;
};
class dragonC
{
public:
dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }
void draw( int iterations ) { generate( iterations ); draw(); }
private:
void generate( int it )
{
generator.push_back( 1 );
string temp;
for( int y = 0; y < it - 1; y++ )
{
temp = generator; temp.push_back( 1 );
for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )
temp.push_back( !( *x ) );
generator = temp;
}
}
void draw()
{
HDC dc = bmp.getDC();
unsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };
int mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;
for( int t = 0; t < 4; t++ )
{
int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];
MoveToEx( dc, a, b, NULL );
bmp.setPenColor( clr[t] );
for( string::iterator x = generator.begin(); x < generator.end(); x++ )
{
switch( dir )
{
case NORTH:
if( *x ) { a += LEN; dir = EAST; }
else { a -= LEN; dir = WEST; }
break;
case EAST:
if( *x ) { b += LEN; dir = SOUTH; }
else { b -= LEN; dir = NORTH; }
break;
case SOUTH:
if( *x ) { a -= LEN; dir = WEST; }
else { a += LEN; dir = EAST; }
break;
case WEST:
if( *x ) { b -= LEN; dir = NORTH; }
else { b += LEN; dir = SOUTH; }
}
LineTo( dc, a, b );
}
}
bmp.saveBitmap( "f:/rc/dragonCpp.bmp" );
}
int dir;
myBitmap bmp;
string generator;
};
int main( int argc, char* argv[] )
{
dragonC d; d.draw( 17 );
return system( "pause" );
}
|
Generate an equivalent C++ version of this Python code. | for line in lines open('input.txt'):
print line
| #include <fstream>
#include <string>
#include <iostream>
int main( int argc , char** argv ) {
int linecount = 0 ;
std::string line ;
std::ifstream infile( argv[ 1 ] ) ;
if ( infile ) {
while ( getline( infile , line ) ) {
std::cout << linecount << ": "
<< line << '\n' ;
linecount++ ;
}
}
infile.close( ) ;
return 0 ;
}
|
Generate a C++ translation of this Python snippet without changing its computational steps. | def insert(anchor, new):
new.next = anchor.next
new.prev = anchor
anchor.next.prev = new
anchor.next = new
| template <typename T>
void insert_after(Node<T>* N, T&& data)
{
auto node = new Node<T>{N, N->next, std::forward(data)};
if(N->next != nullptr)
N->next->prev = node;
N->next = node;
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | def insert(anchor, new):
new.next = anchor.next
new.prev = anchor
anchor.next.prev = new
anchor.next = new
| template <typename T>
void insert_after(Node<T>* N, T&& data)
{
auto node = new Node<T>{N, N->next, std::forward(data)};
if(N->next != nullptr)
N->next->prev = node;
N->next = node;
}
|
Convert this Python block to C++, preserving its control flow and logic. | def divisors(n):
divs = [1]
for ii in range(2, int(n ** 0.5) + 3):
if n % ii == 0:
divs.append(ii)
divs.append(int(n / ii))
divs.append(n)
return list(set(divs))
def is_prime(n):
return len(divisors(n)) == 2
def digit_check(n):
if len(str(n))<2:
return True
else:
for digit in str(n):
if not is_prime(int(digit)):
return False
return True
def sequence(max_n=None):
ii = 0
n = 0
while True:
ii += 1
if is_prime(ii):
if max_n is not None:
if n>max_n:
break
if digit_check(ii):
n += 1
yield ii
if __name__ == '__main__':
generator = sequence(100)
for index, item in zip(range(1, 16), generator):
print(index, item)
for index, item in zip(range(16, 100), generator):
pass
print(100, generator.__next__())
| #include <iostream>
#include <cstdint>
using integer = uint32_t;
integer next_prime_digit_number(integer n) {
if (n == 0)
return 2;
switch (n % 10) {
case 2:
return n + 1;
case 3:
case 5:
return n + 2;
default:
return 2 + next_prime_digit_number(n/10) * 10;
}
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
return n == 5;
constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };
integer p = 7;
for (;;) {
for (integer w : wheel) {
if (p * p > n)
return true;
if (n % p == 0)
return false;
p += w;
}
}
}
int main() {
std::cout.imbue(std::locale(""));
const integer limit = 1000000000;
integer n = 0, max = 0;
std::cout << "First 25 SPDS primes:\n";
for (int i = 0; n < limit; ) {
n = next_prime_digit_number(n);
if (!is_prime(n))
continue;
if (i < 25) {
if (i > 0)
std::cout << ' ';
std::cout << n;
}
else if (i == 25)
std::cout << '\n';
++i;
if (i == 100)
std::cout << "Hundredth SPDS prime: " << n << '\n';
else if (i == 1000)
std::cout << "Thousandth SPDS prime: " << n << '\n';
else if (i == 10000)
std::cout << "Ten thousandth SPDS prime: " << n << '\n';
max = n;
}
std::cout << "Largest SPDS prime less than " << limit << ": " << max << '\n';
return 0;
}
|
Write a version of this Python function in C++ with identical behavior. | import random
def partition(vector, left, right, pivotIndex):
pivotValue = vector[pivotIndex]
vector[pivotIndex], vector[right] = vector[right], vector[pivotIndex]
storeIndex = left
for i in range(left, right):
if vector[i] < pivotValue:
vector[storeIndex], vector[i] = vector[i], vector[storeIndex]
storeIndex += 1
vector[right], vector[storeIndex] = vector[storeIndex], vector[right]
return storeIndex
def _select(vector, left, right, k):
"Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive."
while True:
pivotIndex = random.randint(left, right)
pivotNewIndex = partition(vector, left, right, pivotIndex)
pivotDist = pivotNewIndex - left
if pivotDist == k:
return vector[pivotNewIndex]
elif k < pivotDist:
right = pivotNewIndex - 1
else:
k -= pivotDist + 1
left = pivotNewIndex + 1
def select(vector, k, left=None, right=None):
if left is None:
left = 0
lv1 = len(vector) - 1
if right is None:
right = lv1
assert vector and k >= 0, "Either null vector or k < 0 "
assert 0 <= left <= lv1, "left is out of range"
assert left <= right <= lv1, "right is out of range"
return _select(vector, left, right, k)
if __name__ == '__main__':
v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
print([select(v, i) for i in range(10)])
| #include <algorithm>
#include <iostream>
int main() {
for (int i = 0; i < 10; i++) {
int a[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
std::nth_element(a, a + i, a + sizeof(a)/sizeof(*a));
std::cout << a[i];
if (i < 9) std::cout << ", ";
}
std::cout << std::endl;
return 0;
}
|
Translate the given Python code snippet into C++ without altering its behavior. | i = int('1a',16)
| #include <string>
#include <cstdlib>
#include <algorithm>
#include <cassert>
std::string const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
std::string to_base(unsigned long num, int base)
{
if (num == 0)
return "0";
std::string result;
while (num > 0) {
std::ldiv_t temp = std::div(num, (long)base);
result += digits[temp.rem];
num = temp.quot;
}
std::reverse(result.begin(), result.end());
return result;
}
unsigned long from_base(std::string const& num_str, int base)
{
unsigned long result = 0;
for (std::string::size_type pos = 0; pos < num_str.length(); ++pos)
result = result * base + digits.find(num_str[pos]);
return result;
}
|
Change the following Python code into C++ without altering its purpose. | from pathlib import Path
for path in Path('.').rglob('*.*'):
print(path)
| #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
boost::regex pattern("a.*");
for (recursive_directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
std::string name = iter->path().filename().string();
if (regex_match(name, pattern))
std::cout << iter->path() << "\n";
}
}
|
Port the following code from Python to C++ with equivalent syntax and logic. | k8 = [ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 ]
k7 = [ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 ]
k6 = [ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 ]
k5 = [ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 ]
k4 = [ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 ]
k3 = [ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 ]
k2 = [ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 ]
k1 = [ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 ]
k87 = [0] * 256
k65 = [0] * 256
k43 = [0] * 256
k21 = [0] * 256
def kboxinit():
for i in range(256):
k87[i] = k8[i >> 4] << 4 | k7[i & 15]
k65[i] = k6[i >> 4] << 4 | k5[i & 15]
k43[i] = k4[i >> 4] << 4 | k3[i & 15]
k21[i] = k2[i >> 4] << 4 | k1[i & 15]
def f(x):
x = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |
k43[x>> 8 & 255] << 8 | k21[x & 255] )
return x<<11 | x>>(32-11)
| UINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)
{
UINT_64 N;
N = N1;
N = (N<<32)|N2;
return UINT_64(N);
}
UINT_32 TGost::ReplaceBlock(UINT_32 x)
{
register i;
UINT_32 res = 0UL;
for(i=7;i>=0;i--)
{
ui4_0 = x>>(i*4);
ui4_0 = BS[ui4_0][i];
res = (res<<4)|ui4_0;
}
return res;
}
UINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)
{
UINT_32 N1,N2,S=0UL;
N1=UINT_32(N);
N2=N>>32;
S = N1 + X % 0x4000000000000;
S = ReplaceBlock(S);
S = (S<<11)|(S>>21);
S ^= N2;
N2 = N1;
N1 = S;
return SWAP32(N2,N1);
}
|
Maintain the same structure and functionality when rewriting this code in C++. | from collections import defaultdict
states = ["Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware", "Florida",
"Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas",
"Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts",
"Michigan", "Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico",
"New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma",
"Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming",
]
states = sorted(set(states))
smap = defaultdict(list)
for i, s1 in enumerate(states[:-1]):
for s2 in states[i + 1:]:
smap["".join(sorted(s1 + s2))].append(s1 + " + " + s2)
for pairs in sorted(smap.itervalues()):
if len(pairs) > 1:
print " = ".join(pairs)
| #include <algorithm>
#include <iostream>
#include <string>
#include <array>
#include <vector>
template<typename T>
T unique(T&& src)
{
T retval(std::move(src));
std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>());
retval.erase(std::unique(retval.begin(), retval.end()), retval.end());
return retval;
}
#define USE_FAKES 1
auto states = unique(std::vector<std::string>({
#if USE_FAKES
"Slender Dragon", "Abalamara",
#endif
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
}));
struct counted_pair
{
std::string name;
std::array<int, 26> count{};
void count_characters(const std::string& s)
{
for (auto&& c : s) {
if (c >= 'a' && c <= 'z') count[c - 'a']++;
if (c >= 'A' && c <= 'Z') count[c - 'A']++;
}
}
counted_pair(const std::string& s1, const std::string& s2)
: name(s1 + " + " + s2)
{
count_characters(s1);
count_characters(s2);
}
};
bool operator<(const counted_pair& lhs, const counted_pair& rhs)
{
auto lhs_size = lhs.name.size();
auto rhs_size = rhs.name.size();
return lhs_size == rhs_size
? std::lexicographical_compare(lhs.count.begin(),
lhs.count.end(),
rhs.count.begin(),
rhs.count.end())
: lhs_size < rhs_size;
}
bool operator==(const counted_pair& lhs, const counted_pair& rhs)
{
return lhs.name.size() == rhs.name.size() && lhs.count == rhs.count;
}
int main()
{
const int n_states = states.size();
std::vector<counted_pair> pairs;
for (int i = 0; i < n_states; i++) {
for (int j = 0; j < i; j++) {
pairs.emplace_back(counted_pair(states[i], states[j]));
}
}
std::sort(pairs.begin(), pairs.end());
auto start = pairs.begin();
while (true) {
auto match = std::adjacent_find(start, pairs.end());
if (match == pairs.end()) {
break;
}
auto next = match + 1;
std::cout << match->name << " => " << next->name << "\n";
start = next;
}
}
|
Generate an equivalent C++ version of this Python code. | >>> s = 'The quick brown fox jumps over the lazy dog'
>>> import zlib
>>> hex(zlib.crc32(s))
'0x414fa339'
>>> import binascii
>>> hex(binascii.crc32(s))
'0x414fa339'
| #include <algorithm>
#include <array>
#include <cstdint>
#include <numeric>
#include <iomanip>
#include <iostream>
#include <string>
std::array<std::uint_fast32_t, 256> generate_crc_lookup_table() noexcept
{
auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL};
struct byte_checksum
{
std::uint_fast32_t operator()() noexcept
{
auto checksum = static_cast<std::uint_fast32_t>(n++);
for (auto i = 0; i < 8; ++i)
checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0);
return checksum;
}
unsigned n = 0;
};
auto table = std::array<std::uint_fast32_t, 256>{};
std::generate(table.begin(), table.end(), byte_checksum{});
return table;
}
template <typename InputIterator>
std::uint_fast32_t crc(InputIterator first, InputIterator last)
{
static auto const table = generate_crc_lookup_table();
return std::uint_fast32_t{0xFFFFFFFFuL} &
~std::accumulate(first, last,
~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL},
[](std::uint_fast32_t checksum, std::uint_fast8_t value)
{ return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); });
}
int main()
{
auto const s = std::string{"The quick brown fox jumps over the lazy dog"};
std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\n';
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | csvtxt =
from cgi import escape
def _row2tr(row, attr=None):
cols = escape(row).split(',')
return ('<TR>'
+ ''.join('<TD>%s</TD>' % data for data in cols)
+ '</TR>')
def csv2html(txt):
htmltxt = '<TABLE summary="csv2html program output">\n'
for rownum, row in enumerate(txt.split('\n')):
htmlrow = _row2tr(row)
htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow
htmltxt += htmlrow
htmltxt += '</TABLE>\n'
return htmltxt
htmltxt = csv2html(csvtxt)
print(htmltxt)
| #include <string>
#include <boost/regex.hpp>
#include <iostream>
std::string csvToHTML( const std::string & ) ;
int main( ) {
std::string text = "Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you?\n"
"Brians mother,I'm his mother; that's who!\n"
"The multitude,Behold his mother! Behold his mother!\n" ;
std::cout << csvToHTML( text ) ;
return 0 ;
}
std::string csvToHTML( const std::string & csvtext ) {
std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
const char* replacements [ 5 ] = { "<" , ">" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ;
boost::regex e1( regexes[ 0 ] ) ;
std::string tabletext = boost::regex_replace( csvtext , e1 ,
replacements[ 0 ] , boost::match_default | boost::format_all ) ;
for ( int i = 1 ; i < 5 ; i++ ) {
e1.assign( regexes[ i ] ) ;
tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
}
tabletext = std::string( "<TABLE>\n" ) + tabletext ;
tabletext.append( "</TABLE>\n" ) ;
return tabletext ;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | csvtxt =
from cgi import escape
def _row2tr(row, attr=None):
cols = escape(row).split(',')
return ('<TR>'
+ ''.join('<TD>%s</TD>' % data for data in cols)
+ '</TR>')
def csv2html(txt):
htmltxt = '<TABLE summary="csv2html program output">\n'
for rownum, row in enumerate(txt.split('\n')):
htmlrow = _row2tr(row)
htmlrow = ' <TBODY>%s</TBODY>\n' % htmlrow
htmltxt += htmlrow
htmltxt += '</TABLE>\n'
return htmltxt
htmltxt = csv2html(csvtxt)
print(htmltxt)
| #include <string>
#include <boost/regex.hpp>
#include <iostream>
std::string csvToHTML( const std::string & ) ;
int main( ) {
std::string text = "Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you?\n"
"Brians mother,I'm his mother; that's who!\n"
"The multitude,Behold his mother! Behold his mother!\n" ;
std::cout << csvToHTML( text ) ;
return 0 ;
}
std::string csvToHTML( const std::string & csvtext ) {
std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
const char* replacements [ 5 ] = { "<" , ">" , " <TR><TD>$1" , "</TD><TD>", "</TD></TR>\n" } ;
boost::regex e1( regexes[ 0 ] ) ;
std::string tabletext = boost::regex_replace( csvtext , e1 ,
replacements[ 0 ] , boost::match_default | boost::format_all ) ;
for ( int i = 1 ; i < 5 ; i++ ) {
e1.assign( regexes[ i ] ) ;
tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
}
tabletext = std::string( "<TABLE>\n" ) + tabletext ;
tabletext.append( "</TABLE>\n" ) ;
return tabletext ;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | class MyClass:
name2 = 2
def __init__(self):
self.name1 = 0
def someMethod(self):
self.name1 = 1
MyClass.name2 = 3
myclass = MyClass()
class MyOtherClass:
count = 0
def __init__(self, name, gender="Male", age=None):
MyOtherClass.count += 1
self.name = name
self.gender = gender
if age is not None:
self.age = age
def __del__(self):
MyOtherClass.count -= 1
person1 = MyOtherClass("John")
print person1.name, person1.gender
print person1.age
person2 = MyOtherClass("Jane", "Female", 23)
print person2.name, person2.gender, person2.age
| PRAGMA COMPILER g++
PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive
OPTION PARSE FALSE
'---The class does the declaring for you
CLASS Books
public:
const char* title;
const char* author;
const char* subject;
int book_id;
END CLASS
'---pointer to an object declaration (we use a class called Books)
DECLARE Book1 TYPE Books
'--- the correct syntax for class
Book1 = Books()
'--- initialize the strings const char* in c++
Book1.title = "C++ Programming to bacon "
Book1.author = "anyone"
Book1.subject ="RECORD Tutorial"
Book1.book_id = 1234567
PRINT "Book title : " ,Book1.title FORMAT "%s%s\n"
PRINT "Book author : ", Book1.author FORMAT "%s%s\n"
PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n"
PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"
|
Preserve the algorithm and functionality while converting the code from Python to C++. | >>> def k(n):
n2 = str(n**2)
for i in range(len(n2)):
a, b = int(n2[:i] or 0), int(n2[i:])
if b and a + b == n:
return n
>>> [x for x in range(1,10000) if k(x)]
[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
>>> len([x for x in range(1,1000000) if k(x)])
54
>>>
| #include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <utility>
long string2long( const std::string & s ) {
long result ;
std::istringstream( s ) >> result ;
return result ;
}
bool isKaprekar( long number ) {
long long squarenumber = ((long long)number) * number ;
std::ostringstream numberbuf ;
numberbuf << squarenumber ;
std::string numberstring = numberbuf.str( ) ;
for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {
std::string firstpart = numberstring.substr( 0 , i ) ,
secondpart = numberstring.substr( i ) ;
if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) {
return false ;
}
if ( string2long( firstpart ) + string2long( secondpart ) == number ) {
return true ;
}
}
return false ;
}
int main( ) {
std::vector<long> kaprekarnumbers ;
kaprekarnumbers.push_back( 1 ) ;
for ( int i = 2 ; i < 1000001 ; i++ ) {
if ( isKaprekar( i ) )
kaprekarnumbers.push_back( i ) ;
}
std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;
std::cout << "Kaprekar numbers up to 10000: \n" ;
while ( *svi < 10000 ) {
std::cout << *svi << " " ;
svi++ ;
}
std::cout << '\n' ;
std::cout << "All the Kaprekar numbers up to 1000000 :\n" ;
std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,
std::ostream_iterator<long>( std::cout , "\n" ) ) ;
std::cout << "There are " << kaprekarnumbers.size( )
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}
|
Produce a functionally identical C++ code for the snippet given in Python. | >>> def k(n):
n2 = str(n**2)
for i in range(len(n2)):
a, b = int(n2[:i] or 0), int(n2[i:])
if b and a + b == n:
return n
>>> [x for x in range(1,10000) if k(x)]
[1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4879, 4950, 5050, 5292, 7272, 7777, 9999]
>>> len([x for x in range(1,1000000) if k(x)])
54
>>>
| #include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <utility>
long string2long( const std::string & s ) {
long result ;
std::istringstream( s ) >> result ;
return result ;
}
bool isKaprekar( long number ) {
long long squarenumber = ((long long)number) * number ;
std::ostringstream numberbuf ;
numberbuf << squarenumber ;
std::string numberstring = numberbuf.str( ) ;
for ( int i = 0 ; i < numberstring.length( ) ; i++ ) {
std::string firstpart = numberstring.substr( 0 , i ) ,
secondpart = numberstring.substr( i ) ;
if ( secondpart.find_first_not_of( "0" ) == std::string::npos ) {
return false ;
}
if ( string2long( firstpart ) + string2long( secondpart ) == number ) {
return true ;
}
}
return false ;
}
int main( ) {
std::vector<long> kaprekarnumbers ;
kaprekarnumbers.push_back( 1 ) ;
for ( int i = 2 ; i < 1000001 ; i++ ) {
if ( isKaprekar( i ) )
kaprekarnumbers.push_back( i ) ;
}
std::vector<long>::const_iterator svi = kaprekarnumbers.begin( ) ;
std::cout << "Kaprekar numbers up to 10000: \n" ;
while ( *svi < 10000 ) {
std::cout << *svi << " " ;
svi++ ;
}
std::cout << '\n' ;
std::cout << "All the Kaprekar numbers up to 1000000 :\n" ;
std::copy( kaprekarnumbers.begin( ) , kaprekarnumbers.end( ) ,
std::ostream_iterator<long>( std::cout , "\n" ) ) ;
std::cout << "There are " << kaprekarnumbers.size( )
<< " Kaprekar numbers less than one million!\n" ;
return 0 ;
}
|
Produce a functionally identical C++ code for the snippet given in Python. | def compress(uncompressed):
dict_size = 256
dictionary = dict((chr(i), i) for i in range(dict_size))
w = ""
result = []
for c in uncompressed:
wc = w + c
if wc in dictionary:
w = wc
else:
result.append(dictionary[w])
dictionary[wc] = dict_size
dict_size += 1
w = c
if w:
result.append(dictionary[w])
return result
def decompress(compressed):
from io import StringIO
dict_size = 256
dictionary = dict((i, chr(i)) for i in range(dict_size))
result = StringIO()
w = chr(compressed.pop(0))
result.write(w)
for k in compressed:
if k in dictionary:
entry = dictionary[k]
elif k == dict_size:
entry = w + w[0]
else:
raise ValueError('Bad compressed k: %s' % k)
result.write(entry)
dictionary[dict_size] = w + entry[0]
dict_size += 1
w = entry
return result.getvalue()
compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
print (compressed)
decompressed = decompress(compressed)
print (decompressed)
| #include <string>
#include <map>
template <typename Iterator>
Iterator compress(const std::string &uncompressed, Iterator result) {
int dictSize = 256;
std::map<std::string,int> dictionary;
for (int i = 0; i < 256; i++)
dictionary[std::string(1, i)] = i;
std::string w;
for (std::string::const_iterator it = uncompressed.begin();
it != uncompressed.end(); ++it) {
char c = *it;
std::string wc = w + c;
if (dictionary.count(wc))
w = wc;
else {
*result++ = dictionary[w];
dictionary[wc] = dictSize++;
w = std::string(1, c);
}
}
if (!w.empty())
*result++ = dictionary[w];
return result;
}
template <typename Iterator>
std::string decompress(Iterator begin, Iterator end) {
int dictSize = 256;
std::map<int,std::string> dictionary;
for (int i = 0; i < 256; i++)
dictionary[i] = std::string(1, i);
std::string w(1, *begin++);
std::string result = w;
std::string entry;
for ( ; begin != end; begin++) {
int k = *begin;
if (dictionary.count(k))
entry = dictionary[k];
else if (k == dictSize)
entry = w + w[0];
else
throw "Bad compressed k";
result += entry;
dictionary[dictSize++] = w + entry[0];
w = entry;
}
return result;
}
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<int> compressed;
compress("TOBEORNOTTOBEORTOBEORNOT", std::back_inserter(compressed));
copy(compressed.begin(), compressed.end(), std::ostream_iterator<int>(std::cout, ", "));
std::cout << std::endl;
std::string decompressed = decompress(compressed.begin(), compressed.end());
std::cout << decompressed << std::endl;
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Python. | def ffr(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return ffr.r[n]
except IndexError:
r, s = ffr.r, ffs.s
ffr_n_1 = ffr(n-1)
lastr = r[-1]
s += list(range(s[-1] + 1, lastr))
if s[-1] < lastr: s += [lastr + 1]
len_s = len(s)
ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]
ans = ffr_n_1 + ffs_n_1
r.append(ans)
return ans
ffr.r = [None, 1]
def ffs(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return ffs.s[n]
except IndexError:
r, s = ffr.r, ffs.s
for i in range(len(r), n+2):
ffr(i)
if len(s) > n:
return s[n]
raise Exception("Whoops!")
ffs.s = [None, 2]
if __name__ == '__main__':
first10 = [ffr(i) for i in range(1,11)]
assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)"
print("ffr(n) for n = [1..10] is", first10)
bin = [None] + [0]*1000
for i in range(40, 0, -1):
bin[ffr(i)] += 1
for i in range(960, 0, -1):
bin[ffs(i)] += 1
if all(b == 1 for b in bin[1:1000]):
print("All Integers 1..1000 found OK")
else:
print("All Integers 1..1000 NOT found only once: ERROR")
| #include <iomanip>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
auto n = rlistSize > slistSize ? rlistSize : slistSize;
auto rlist = new vector<unsigned> { 1, 3, 7 };
auto slist = new vector<unsigned> { 2, 4, 5, 6 };
auto list = rlistSize > 0 ? rlist : slist;
auto target_size = rlistSize > 0 ? rlistSize : slistSize;
while (list->size() > target_size) list->pop_back();
while (list->size() < target_size)
{
auto lastIndex = rlist->size() - 1;
auto lastr = (*rlist)[lastIndex];
auto r = lastr + (*slist)[lastIndex];
rlist->push_back(r);
for (auto s = lastr + 1; s < r && list->size() < target_size;)
slist->push_back(s++);
}
auto v = (*list)[n - 1];
delete rlist;
delete slist;
return v;
}
ostream& operator<<(ostream& os, const set<unsigned>& s)
{
cout << '(' << s.size() << "):";
auto i = 0;
for (auto c = s.begin(); c != s.end();)
{
if (i++ % 20 == 0) os << endl;
os << setw(5) << *c++;
}
return os;
}
int main(int argc, const char* argv[])
{
const auto v1 = atoi(argv[1]);
const auto v2 = atoi(argv[2]);
set<unsigned> r, s;
for (auto n = 1; n <= v2; n++)
{
if (n <= v1)
r.insert(hofstadter(n, 0));
s.insert(hofstadter(0, n));
}
cout << "R" << r << endl;
cout << "S" << s << endl;
int m = max(*r.rbegin(), *s.rbegin());
for (auto n = 1; n <= m; n++)
if (r.count(n) == s.count(n))
clog << "integer " << n << " either in both or neither set" << endl;
return 0;
}
|
Generate a C++ translation of this Python snippet without changing its computational steps. | def ffr(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return ffr.r[n]
except IndexError:
r, s = ffr.r, ffs.s
ffr_n_1 = ffr(n-1)
lastr = r[-1]
s += list(range(s[-1] + 1, lastr))
if s[-1] < lastr: s += [lastr + 1]
len_s = len(s)
ffs_n_1 = s[n-1] if len_s > n else (n - len_s) + s[-1]
ans = ffr_n_1 + ffs_n_1
r.append(ans)
return ans
ffr.r = [None, 1]
def ffs(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return ffs.s[n]
except IndexError:
r, s = ffr.r, ffs.s
for i in range(len(r), n+2):
ffr(i)
if len(s) > n:
return s[n]
raise Exception("Whoops!")
ffs.s = [None, 2]
if __name__ == '__main__':
first10 = [ffr(i) for i in range(1,11)]
assert first10 == [1, 3, 7, 12, 18, 26, 35, 45, 56, 69], "ffr() value error(s)"
print("ffr(n) for n = [1..10] is", first10)
bin = [None] + [0]*1000
for i in range(40, 0, -1):
bin[ffr(i)] += 1
for i in range(960, 0, -1):
bin[ffs(i)] += 1
if all(b == 1 for b in bin[1:1000]):
print("All Integers 1..1000 found OK")
else:
print("All Integers 1..1000 NOT found only once: ERROR")
| #include <iomanip>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
unsigned hofstadter(unsigned rlistSize, unsigned slistSize)
{
auto n = rlistSize > slistSize ? rlistSize : slistSize;
auto rlist = new vector<unsigned> { 1, 3, 7 };
auto slist = new vector<unsigned> { 2, 4, 5, 6 };
auto list = rlistSize > 0 ? rlist : slist;
auto target_size = rlistSize > 0 ? rlistSize : slistSize;
while (list->size() > target_size) list->pop_back();
while (list->size() < target_size)
{
auto lastIndex = rlist->size() - 1;
auto lastr = (*rlist)[lastIndex];
auto r = lastr + (*slist)[lastIndex];
rlist->push_back(r);
for (auto s = lastr + 1; s < r && list->size() < target_size;)
slist->push_back(s++);
}
auto v = (*list)[n - 1];
delete rlist;
delete slist;
return v;
}
ostream& operator<<(ostream& os, const set<unsigned>& s)
{
cout << '(' << s.size() << "):";
auto i = 0;
for (auto c = s.begin(); c != s.end();)
{
if (i++ % 20 == 0) os << endl;
os << setw(5) << *c++;
}
return os;
}
int main(int argc, const char* argv[])
{
const auto v1 = atoi(argv[1]);
const auto v2 = atoi(argv[2]);
set<unsigned> r, s;
for (auto n = 1; n <= v2; n++)
{
if (n <= v1)
r.insert(hofstadter(n, 0));
s.insert(hofstadter(0, n));
}
cout << "R" << r << endl;
cout << "S" << s << endl;
int m = max(*r.rbegin(), *s.rbegin());
for (auto n = 1; n <= m; n++)
if (r.count(n) == s.count(n))
clog << "integer " << n << " either in both or neither set" << endl;
return 0;
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | >>> def magic(n):
for row in range(1, n + 1):
print(' '.join('%*i' % (len(str(n**2)), cell) for cell in
(n * ((row + col - 1 + n // 2) % n) +
((row + 2 * col - 2) % n) + 1
for col in range(1, n + 1))))
print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2))
>>> for n in (5, 3, 7):
print('\nOrder %i\n=======' % n)
magic(n)
Order 5
=======
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
All sum to magic number 65
Order 3
=======
8 1 6
3 5 7
4 9 2
All sum to magic number 15
Order 7
=======
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
All sum to magic number 175
>>>
| #include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <vector>
using namespace std;
class MagicSquare
{
public:
MagicSquare(int d) : sqr(d*d,0), sz(d)
{
assert(d&1);
fillSqr();
}
void display()
{
cout << "Odd Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr;
cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ )
{
int yy = y * sz;
for( int x = 0; x < sz; x++ )
cout << setw( l + 2 ) << sqr[yy + x];
cout << "\n";
}
cout << "\n\n";
}
private:
void fillSqr()
{
int sx = sz / 2, sy = 0, c = 0;
while( c < sz * sz )
{
if( !sqr[sx + sy * sz] )
{
sqr[sx + sy * sz]= c + 1;
inc( sx ); dec( sy );
c++;
}
else
{
dec( sx ); inc( sy ); inc( sy );
}
}
}
int magicNumber()
{ return sz * ( ( sz * sz ) + 1 ) / 2; }
void inc( int& a )
{ if( ++a == sz ) a = 0; }
void dec( int& a )
{ if( --a < 0 ) a = sz - 1; }
bool checkPos( int x, int y )
{ return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
bool isInside( int s )
{ return ( s < sz && s > -1 ); }
vector<int> sqr;
int sz;
};
int main()
{
MagicSquare s(7);
s.display();
return 0;
}
|
Keep all operations the same but rewrite the snippet in C++. | >>> def magic(n):
for row in range(1, n + 1):
print(' '.join('%*i' % (len(str(n**2)), cell) for cell in
(n * ((row + col - 1 + n // 2) % n) +
((row + 2 * col - 2) % n) + 1
for col in range(1, n + 1))))
print('\nAll sum to magic number %i' % ((n * n + 1) * n // 2))
>>> for n in (5, 3, 7):
print('\nOrder %i\n=======' % n)
magic(n)
Order 5
=======
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
All sum to magic number 65
Order 3
=======
8 1 6
3 5 7
4 9 2
All sum to magic number 15
Order 7
=======
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
All sum to magic number 175
>>>
| #include <iostream>
#include <sstream>
#include <iomanip>
#include <cassert>
#include <vector>
using namespace std;
class MagicSquare
{
public:
MagicSquare(int d) : sqr(d*d,0), sz(d)
{
assert(d&1);
fillSqr();
}
void display()
{
cout << "Odd Magic Square: " << sz << " x " << sz << "\n";
cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
ostringstream cvr;
cvr << sz * sz;
int l = cvr.str().size();
for( int y = 0; y < sz; y++ )
{
int yy = y * sz;
for( int x = 0; x < sz; x++ )
cout << setw( l + 2 ) << sqr[yy + x];
cout << "\n";
}
cout << "\n\n";
}
private:
void fillSqr()
{
int sx = sz / 2, sy = 0, c = 0;
while( c < sz * sz )
{
if( !sqr[sx + sy * sz] )
{
sqr[sx + sy * sz]= c + 1;
inc( sx ); dec( sy );
c++;
}
else
{
dec( sx ); inc( sy ); inc( sy );
}
}
}
int magicNumber()
{ return sz * ( ( sz * sz ) + 1 ) / 2; }
void inc( int& a )
{ if( ++a == sz ) a = 0; }
void dec( int& a )
{ if( --a < 0 ) a = sz - 1; }
bool checkPos( int x, int y )
{ return( isInside( x ) && isInside( y ) && !sqr[sz * y + x] ); }
bool isInside( int s )
{ return ( s < sz && s > -1 ); }
vector<int> sqr;
int sz;
};
int main()
{
MagicSquare s(7);
s.display();
return 0;
}
|
Write the same algorithm in C++ as shown in this Python implementation. |
from itertools import chain, count, islice
from operator import itemgetter
from math import gcd
from matplotlib import pyplot
def yellowstone():
def relativelyPrime(a):
return lambda b: 1 == gcd(a, b)
def nextWindow(triple):
p2, p1, rest = triple
[rp2, rp1] = map(relativelyPrime, [p2, p1])
def match(xxs):
x, xs = uncons(xxs)['Just']
return (x, xs) if rp1(x) and not rp2(x) else (
second(cons(x))(
match(xs)
)
)
n, residue = match(rest)
return (p1, n, residue)
return chain(
range(1, 3),
map(
itemgetter(1),
iterate(nextWindow)(
(2, 3, count(4))
)
)
)
def main():
print(showList(
take(30)(yellowstone())
))
pyplot.plot(
take(100)(yellowstone())
)
pyplot.xlabel(main.__doc__)
pyplot.show()
def Just(x):
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
def Nothing():
return {'type': 'Maybe', 'Nothing': True}
def cons(x):
return lambda xs: [x] + xs if (
isinstance(xs, list)
) else x + xs if (
isinstance(xs, str)
) else chain([x], xs)
def iterate(f):
def go(x):
v = x
while True:
yield v
v = f(v)
return go
def second(f):
return lambda xy: (xy[0], f(xy[1]))
def showList(xs):
return '[' + ','.join(repr(x) for x in xs) + ']'
def take(n):
return lambda xs: (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
def uncons(xs):
if isinstance(xs, list):
return Just((xs[0], xs[1:])) if xs else Nothing()
else:
nxt = take(1)(xs)
return Just((nxt[0], xs)) if nxt else Nothing()
if __name__ == '__main__':
main()
| #include <iostream>
#include <numeric>
#include <set>
template <typename integer>
class yellowstone_generator {
public:
integer next() {
n2_ = n1_;
n1_ = n_;
if (n_ < 3) {
++n_;
} else {
for (n_ = min_; !(sequence_.count(n_) == 0
&& std::gcd(n1_, n_) == 1
&& std::gcd(n2_, n_) > 1); ++n_) {}
}
sequence_.insert(n_);
for (;;) {
auto it = sequence_.find(min_);
if (it == sequence_.end())
break;
sequence_.erase(it);
++min_;
}
return n_;
}
private:
std::set<integer> sequence_;
integer min_ = 1;
integer n_ = 0;
integer n1_ = 0;
integer n2_ = 0;
};
int main() {
std::cout << "First 30 Yellowstone numbers:\n";
yellowstone_generator<unsigned int> ygen;
std::cout << ygen.next();
for (int i = 1; i < 30; ++i)
std::cout << ' ' << ygen.next();
std::cout << '\n';
return 0;
}
|
Convert the following code from Python to C++, ensuring the logic remains intact. |
from itertools import chain, count, islice
from operator import itemgetter
from math import gcd
from matplotlib import pyplot
def yellowstone():
def relativelyPrime(a):
return lambda b: 1 == gcd(a, b)
def nextWindow(triple):
p2, p1, rest = triple
[rp2, rp1] = map(relativelyPrime, [p2, p1])
def match(xxs):
x, xs = uncons(xxs)['Just']
return (x, xs) if rp1(x) and not rp2(x) else (
second(cons(x))(
match(xs)
)
)
n, residue = match(rest)
return (p1, n, residue)
return chain(
range(1, 3),
map(
itemgetter(1),
iterate(nextWindow)(
(2, 3, count(4))
)
)
)
def main():
print(showList(
take(30)(yellowstone())
))
pyplot.plot(
take(100)(yellowstone())
)
pyplot.xlabel(main.__doc__)
pyplot.show()
def Just(x):
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
def Nothing():
return {'type': 'Maybe', 'Nothing': True}
def cons(x):
return lambda xs: [x] + xs if (
isinstance(xs, list)
) else x + xs if (
isinstance(xs, str)
) else chain([x], xs)
def iterate(f):
def go(x):
v = x
while True:
yield v
v = f(v)
return go
def second(f):
return lambda xy: (xy[0], f(xy[1]))
def showList(xs):
return '[' + ','.join(repr(x) for x in xs) + ']'
def take(n):
return lambda xs: (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
def uncons(xs):
if isinstance(xs, list):
return Just((xs[0], xs[1:])) if xs else Nothing()
else:
nxt = take(1)(xs)
return Just((nxt[0], xs)) if nxt else Nothing()
if __name__ == '__main__':
main()
| #include <iostream>
#include <numeric>
#include <set>
template <typename integer>
class yellowstone_generator {
public:
integer next() {
n2_ = n1_;
n1_ = n_;
if (n_ < 3) {
++n_;
} else {
for (n_ = min_; !(sequence_.count(n_) == 0
&& std::gcd(n1_, n_) == 1
&& std::gcd(n2_, n_) > 1); ++n_) {}
}
sequence_.insert(n_);
for (;;) {
auto it = sequence_.find(min_);
if (it == sequence_.end())
break;
sequence_.erase(it);
++min_;
}
return n_;
}
private:
std::set<integer> sequence_;
integer min_ = 1;
integer n_ = 0;
integer n1_ = 0;
integer n2_ = 0;
};
int main() {
std::cout << "First 30 Yellowstone numbers:\n";
yellowstone_generator<unsigned int> ygen;
std::cout << ygen.next();
for (int i = 1; i < 30; ++i)
std::cout << ' ' << ygen.next();
std::cout << '\n';
return 0;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. | def cut_it(h, w):
dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))
if h % 2: h, w = w, h
if h % 2: return 0
if w == 1: return 1
count = 0
next = [w + 1, -w - 1, -1, 1]
blen = (h + 1) * (w + 1) - 1
grid = [False] * (blen + 1)
def walk(y, x, count):
if not y or y == h or not x or x == w:
return count + 1
t = y * (w + 1) + x
grid[t] = grid[blen - t] = True
if not grid[t + next[0]]:
count = walk(y + dirs[0][0], x + dirs[0][1], count)
if not grid[t + next[1]]:
count = walk(y + dirs[1][0], x + dirs[1][1], count)
if not grid[t + next[2]]:
count = walk(y + dirs[2][0], x + dirs[2][1], count)
if not grid[t + next[3]]:
count = walk(y + dirs[3][0], x + dirs[3][1], count)
grid[t] = grid[blen - t] = False
return count
t = h // 2 * (w + 1) + w // 2
if w % 2:
grid[t] = grid[t + 1] = True
count = walk(h // 2, w // 2 - 1, count)
res = count
count = 0
count = walk(h // 2 - 1, w // 2, count)
return res + count * 2
else:
grid[t] = True
count = walk(h // 2, w // 2 - 1, count)
if h == w:
return count * 2
count = walk(h // 2 - 1, w // 2, count)
return count
def main():
for w in xrange(1, 10):
for h in xrange(1, w + 1):
if not((w * h) % 2):
print "%d x %d: %d" % (w, h, cut_it(w, h))
main()
| #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
}
void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return;
}
std::vector<std::vector<int>> grid(h, std::vector<int>(w));
std::stack<int> stack;
int half = (w * h) / 2;
long bits = (long)pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.top();
stack.pop();
int r = pos / w;
int c = pos % w;
for (auto dir : DIRS) {
int nextR = r + dir.first;
int nextC = c + dir.second;
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
std::cout << '\n';
}
}
}
int main() {
cutRectangle(2, 2);
cutRectangle(4, 3);
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Python version. | def cut_it(h, w):
dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))
if h % 2: h, w = w, h
if h % 2: return 0
if w == 1: return 1
count = 0
next = [w + 1, -w - 1, -1, 1]
blen = (h + 1) * (w + 1) - 1
grid = [False] * (blen + 1)
def walk(y, x, count):
if not y or y == h or not x or x == w:
return count + 1
t = y * (w + 1) + x
grid[t] = grid[blen - t] = True
if not grid[t + next[0]]:
count = walk(y + dirs[0][0], x + dirs[0][1], count)
if not grid[t + next[1]]:
count = walk(y + dirs[1][0], x + dirs[1][1], count)
if not grid[t + next[2]]:
count = walk(y + dirs[2][0], x + dirs[2][1], count)
if not grid[t + next[3]]:
count = walk(y + dirs[3][0], x + dirs[3][1], count)
grid[t] = grid[blen - t] = False
return count
t = h // 2 * (w + 1) + w // 2
if w % 2:
grid[t] = grid[t + 1] = True
count = walk(h // 2, w // 2 - 1, count)
res = count
count = 0
count = walk(h // 2 - 1, w // 2, count)
return res + count * 2
else:
grid[t] = True
count = walk(h // 2, w // 2 - 1, count)
if h == w:
return count * 2
count = walk(h // 2 - 1, w // 2, count)
return count
def main():
for w in xrange(1, 10):
for h in xrange(1, w + 1):
if not((w * h) % 2):
print "%d x %d: %d" % (w, h, cut_it(w, h))
main()
| #include <array>
#include <iostream>
#include <stack>
#include <vector>
const std::array<std::pair<int, int>, 4> DIRS = {
std::make_pair(0, -1),
std::make_pair(-1, 0),
std::make_pair(0, 1),
std::make_pair(1, 0),
};
void printResult(const std::vector<std::vector<int>> &v) {
for (auto &row : v) {
auto it = row.cbegin();
auto end = row.cend();
std::cout << '[';
if (it != end) {
std::cout << *it;
it = std::next(it);
}
while (it != end) {
std::cout << ", " << *it;
it = std::next(it);
}
std::cout << "]\n";
}
}
void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1) {
return;
}
std::vector<std::vector<int>> grid(h, std::vector<int>(w));
std::stack<int> stack;
int half = (w * h) / 2;
long bits = (long)pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.top();
stack.pop();
int r = pos / w;
int c = pos % w;
for (auto dir : DIRS) {
int nextR = r + dir.first;
int nextC = c + dir.second;
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
std::cout << '\n';
}
}
}
int main() {
cutRectangle(2, 2);
cutRectangle(4, 3);
return 0;
}
|
Translate the given Python code snippet into C++ without altering its behavior. | def mertens(count):
m = [None, 1]
for n in range(2, count+1):
m.append(1)
for k in range(2, n+1):
m[n] -= m[n//k]
return m
ms = mertens(1000)
print("The first 99 Mertens numbers are:")
print(" ", end=' ')
col = 1
for n in ms[1:100]:
print("{:2d}".format(n), end=' ')
col += 1
if col == 10:
print()
col = 0
zeroes = sum(x==0 for x in ms)
crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))
print("M(N) equals zero {} times.".format(zeroes))
print("M(N) crosses zero {} times.".format(crosses))
| #include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> mertens_numbers(int max) {
std::vector<int> m(max + 1, 1);
for (int n = 2; n <= max; ++n) {
for (int k = 2; k <= n; ++k)
m[n] -= m[n / k];
}
return m;
}
int main() {
const int max = 1000;
auto m(mertens_numbers(max));
std::cout << "First 199 Mertens numbers:\n";
for (int i = 0, column = 0; i < 200; ++i) {
if (column > 0)
std::cout << ' ';
if (i == 0)
std::cout << " ";
else
std::cout << std::setw(2) << m[i];
++column;
if (column == 20) {
std::cout << '\n';
column = 0;
}
}
int zero = 0, cross = 0, previous = 0;
for (int i = 1; i <= max; ++i) {
if (m[i] == 0) {
++zero;
if (previous != 0)
++cross;
}
previous = m[i];
}
std::cout << "M(n) is zero " << zero << " times for 1 <= n <= 1000.\n";
std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n";
return 0;
}
|
Please provide an equivalent version of this Python code in C++. | def mertens(count):
m = [None, 1]
for n in range(2, count+1):
m.append(1)
for k in range(2, n+1):
m[n] -= m[n//k]
return m
ms = mertens(1000)
print("The first 99 Mertens numbers are:")
print(" ", end=' ')
col = 1
for n in ms[1:100]:
print("{:2d}".format(n), end=' ')
col += 1
if col == 10:
print()
col = 0
zeroes = sum(x==0 for x in ms)
crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))
print("M(N) equals zero {} times.".format(zeroes))
print("M(N) crosses zero {} times.".format(crosses))
| #include <iomanip>
#include <iostream>
#include <vector>
std::vector<int> mertens_numbers(int max) {
std::vector<int> m(max + 1, 1);
for (int n = 2; n <= max; ++n) {
for (int k = 2; k <= n; ++k)
m[n] -= m[n / k];
}
return m;
}
int main() {
const int max = 1000;
auto m(mertens_numbers(max));
std::cout << "First 199 Mertens numbers:\n";
for (int i = 0, column = 0; i < 200; ++i) {
if (column > 0)
std::cout << ' ';
if (i == 0)
std::cout << " ";
else
std::cout << std::setw(2) << m[i];
++column;
if (column == 20) {
std::cout << '\n';
column = 0;
}
}
int zero = 0, cross = 0, previous = 0;
for (int i = 1; i <= max; ++i) {
if (m[i] == 0) {
++zero;
if (previous != 0)
++cross;
}
previous = m[i];
}
std::cout << "M(n) is zero " << zero << " times for 1 <= n <= 1000.\n";
std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n";
return 0;
}
|
Write the same code in C++ as shown below in Python. | def _insort_right(a, x, q):
lo, hi = 0, len(a)
while lo < hi:
mid = (lo+hi)//2
q += 1
less = input(f"{q:2}: IS {x:>6} LESS-THAN {a[mid]:>6} ? y/n: ").strip().lower() == 'y'
if less: hi = mid
else: lo = mid+1
a.insert(lo, x)
return q
def order(items):
ordered, q = [], 0
for item in items:
q = _insort_right(ordered, item, q)
return ordered, q
if __name__ == '__main__':
items = 'violet red green indigo blue yellow orange'.split()
ans, questions = order(items)
print('\n' + ' '.join(ans))
| #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool InteractiveCompare(const string& s1, const string& s2)
{
if(s1 == s2) return false;
static int count = 0;
string response;
cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? ";
getline(cin, response);
return !response.empty() && response.front() == 'y';
}
void PrintOrder(const vector<string>& items)
{
cout << "{ ";
for(auto& item : items) cout << item << " ";
cout << "}\n";
}
int main()
{
const vector<string> items
{
"violet", "red", "green", "indigo", "blue", "yellow", "orange"
};
vector<string> sortedItems;
for(auto& item : items)
{
cout << "Inserting '" << item << "' into ";
PrintOrder(sortedItems);
auto spotToInsert = lower_bound(sortedItems.begin(),
sortedItems.end(), item, InteractiveCompare);
sortedItems.insert(spotToInsert, item);
}
PrintOrder(sortedItems);
return 0;
}
|
Please provide an equivalent version of this Python code in C++. | from __future__ import division
from itertools import islice, count
from collections import Counter
from math import log10
from random import randint
expected = [log10(1+1/d) for d in range(1,10)]
def fib():
a,b = 1,1
while True:
yield a
a,b = b,a+b
def power_of_threes():
return (3**k for k in count(0))
def heads(s):
for a in s: yield int(str(a)[0])
def show_dist(title, s):
c = Counter(s)
size = sum(c.values())
res = [c[d]/size for d in range(1,10)]
print("\n%s Benfords deviation" % title)
for r, e in zip(res, expected):
print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.))
def rand1000():
while True: yield randint(1,9999)
if __name__ == '__main__':
show_dist("fibbed", islice(heads(fib()), 1000))
show_dist("threes", islice(heads(power_of_threes()), 1000))
show_dist("random", islice(heads(rand1000()), 10000))
|
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;
class NextNum {
public :
NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }
cl_I operator( )( ) {
cl_I result = first + second ;
first = second ;
second = result ;
return result ;
}
private :
cl_I first ;
cl_I second ;
} ;
void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) {
for ( cl_I bignumber : fibos ) {
std::ostringstream os ;
fprintdecimal ( os , bignumber ) ;
int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;
auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;
if ( ! result.second )
numberfrequencies[ firstdigit ]++ ;
}
}
int main( ) {
std::vector<cl_I> fibonaccis( 1000 ) ;
fibonaccis[ 0 ] = 0 ;
fibonaccis[ 1 ] = 1 ;
cl_I a = 0 ;
cl_I b = 1 ;
std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;
std::cout << std::endl ;
std::map<int , int> frequencies ;
findFrequencies( fibonaccis , frequencies ) ;
std::cout << " found expected\n" ;
for ( int i = 1 ; i < 10 ; i++ ) {
double found = static_cast<double>( frequencies[ i ] ) / 1000 ;
double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;
std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ;
std::cout.precision( 3 ) ;
std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ;
}
return 0 ;
}
|
Rewrite the snippet below in C++ so it works the same as the original Python code. | from __future__ import division
from itertools import islice, count
from collections import Counter
from math import log10
from random import randint
expected = [log10(1+1/d) for d in range(1,10)]
def fib():
a,b = 1,1
while True:
yield a
a,b = b,a+b
def power_of_threes():
return (3**k for k in count(0))
def heads(s):
for a in s: yield int(str(a)[0])
def show_dist(title, s):
c = Counter(s)
size = sum(c.values())
res = [c[d]/size for d in range(1,10)]
print("\n%s Benfords deviation" % title)
for r, e in zip(res, expected):
print("%5.1f%% %5.1f%% %5.1f%%" % (r*100., e*100., abs(r - e)*100.))
def rand1000():
while True: yield randint(1,9999)
if __name__ == '__main__':
show_dist("fibbed", islice(heads(fib()), 1000))
show_dist("threes", islice(heads(power_of_threes()), 1000))
show_dist("random", islice(heads(rand1000()), 10000))
|
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;
class NextNum {
public :
NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }
cl_I operator( )( ) {
cl_I result = first + second ;
first = second ;
second = result ;
return result ;
}
private :
cl_I first ;
cl_I second ;
} ;
void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies ) {
for ( cl_I bignumber : fibos ) {
std::ostringstream os ;
fprintdecimal ( os , bignumber ) ;
int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;
auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;
if ( ! result.second )
numberfrequencies[ firstdigit ]++ ;
}
}
int main( ) {
std::vector<cl_I> fibonaccis( 1000 ) ;
fibonaccis[ 0 ] = 0 ;
fibonaccis[ 1 ] = 1 ;
cl_I a = 0 ;
cl_I b = 1 ;
std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;
std::cout << std::endl ;
std::map<int , int> frequencies ;
findFrequencies( fibonaccis , frequencies ) ;
std::cout << " found expected\n" ;
for ( int i = 1 ; i < 10 ; i++ ) {
double found = static_cast<double>( frequencies[ i ] ) / 1000 ;
double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;
std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ;
std::cout.precision( 3 ) ;
std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ;
}
return 0 ;
}
|
Change the following Python code into C++ without altering its purpose. | import time, calendar, sched, winsound
duration = 750
freq = 1280
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); off(0.5)
def bongs(m):
for i in range(m):
print(bellchar, end=' ')
bong()
if i % 2:
print(' ', end='')
off(0.5)
print('')
scheds = sched.scheduler(time.time, time.sleep)
def ships_bell(now=None):
def adjust_to_half_hour(atime):
atime[4] = (atime[4] // 30) * 30
atime[5] = 0
return atime
debug = now is not None
rightnow = time.gmtime()
if not debug:
now = adjust_to_half_hour( list(rightnow) )
then = now[::]
then[4] += 30
hr, mn = now[3:5]
watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)
b += 1
bells = '%i bell%s' % (b, 's' if b > 1 else ' ')
if debug:
print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')
else:
print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')
bongs(b)
if not debug:
scheds.enterabs(calendar.timegm(then), 0, ships_bell)
scheds.run()
def dbg_tester():
for h in range(24):
for m in (0, 30):
if (h,m) == (24,30): break
ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )
if __name__ == '__main__':
ships_bell()
| #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"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight";
_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );
}
private:
static DWORD WINAPI bell( LPVOID p )
{
DWORD wait = _inst->waitTime();
while( true )
{
Sleep( wait );
_inst->playBell();
wait = _inst->waitTime();
}
return 0;
}
DWORD waitTime()
{
GetLocalTime( &st );
int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;
return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );
}
void playBell()
{
GetLocalTime( &st );
int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;
int w = ( 60 * st.wHour + st.wMinute );
if( w < 1 ) w = 5; else w = ( w - 1 ) / 240;
char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute );
cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell";
if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl;
for( int x = 0, c = 1; x < b; x++, c++ )
{
cout << "\7"; Sleep( 500 );
if( !( c % 2 ) ) Sleep( 300 );
}
}
SYSTEMTIME st;
string watch[7], count[8];
static bells* _inst;
};
bells* bells::_inst = 0;
int main( int argc, char* argv[] )
{
bells b; b.start();
while( 1 );
return 0;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. | import time, calendar, sched, winsound
duration = 750
freq = 1280
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); off(0.5)
def bongs(m):
for i in range(m):
print(bellchar, end=' ')
bong()
if i % 2:
print(' ', end='')
off(0.5)
print('')
scheds = sched.scheduler(time.time, time.sleep)
def ships_bell(now=None):
def adjust_to_half_hour(atime):
atime[4] = (atime[4] // 30) * 30
atime[5] = 0
return atime
debug = now is not None
rightnow = time.gmtime()
if not debug:
now = adjust_to_half_hour( list(rightnow) )
then = now[::]
then[4] += 30
hr, mn = now[3:5]
watch, b = divmod(int(2 * hr + mn // 30 - 1), 8)
b += 1
bells = '%i bell%s' % (b, 's' if b > 1 else ' ')
if debug:
print("%02i:%02i, %-20s %s" % (now[3], now[4], watches[watch] + ' watch', bells), end=' ')
else:
print("%02i:%02i, %-20s %s" % (rightnow[3], rightnow[4], watches[watch] + ' watch', bells), end=' ')
bongs(b)
if not debug:
scheds.enterabs(calendar.timegm(then), 0, ships_bell)
scheds.run()
def dbg_tester():
for h in range(24):
for m in (0, 30):
if (h,m) == (24,30): break
ships_bell( [2013, 3, 2, h, m, 15, 5, 61, 0] )
if __name__ == '__main__':
ships_bell()
| #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"; count[3] = "Four"; count[4] = "Five"; count[5] = "Six"; count[6] = "Seven"; count[7] = "Eight";
_inst = this; CreateThread( NULL, 0, bell, NULL, 0, NULL );
}
private:
static DWORD WINAPI bell( LPVOID p )
{
DWORD wait = _inst->waitTime();
while( true )
{
Sleep( wait );
_inst->playBell();
wait = _inst->waitTime();
}
return 0;
}
DWORD waitTime()
{
GetLocalTime( &st );
int m = st.wMinute >= 30 ? st.wMinute - 30 : st.wMinute;
return( 1800000 - ( ( m * 60 + st.wSecond ) * 1000 + st.wMilliseconds ) );
}
void playBell()
{
GetLocalTime( &st );
int b = ( 2 * st.wHour + st.wMinute / 30 ) % 8; b = b == 0 ? 8 : b;
int w = ( 60 * st.wHour + st.wMinute );
if( w < 1 ) w = 5; else w = ( w - 1 ) / 240;
char hr[32]; wsprintf( hr, "%.2d:%.2d", st.wHour, st.wMinute );
cout << hr << " - " << watch[w] << " watch - " << count[b - 1] << " Bell";
if( b > 1 ) cout << "s"; else cout << " "; cout << " Gone." << endl;
for( int x = 0, c = 1; x < b; x++, c++ )
{
cout << "\7"; Sleep( 500 );
if( !( c % 2 ) ) Sleep( 300 );
}
}
SYSTEMTIME st;
string watch[7], count[8];
static bells* _inst;
};
bells* bells::_inst = 0;
int main( int argc, char* argv[] )
{
bells b; b.start();
while( 1 );
return 0;
}
|
Change the following Python code into C++ without altering its purpose. | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fib = lambda f: lambda n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))
>>> [ Y(fib)(i) for i in range(-2, 10) ]
[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
| double fib(double n)
{
if(n < 0)
{
throw "Invalid argument passed to fib";
}
else
{
struct actual_fib
{
static double calc(double n)
{
if(n < 2)
{
return n;
}
else
{
return calc(n-1) + calc(n-2);
}
}
};
return actual_fib::calc(n);
}
}
|
Change the following Python code into C++ without altering its purpose. | from __future__ import annotations
import itertools
import random
from enum import Enum
from typing import Any
from typing import Tuple
import pygame as pg
from pygame import Color
from pygame import Rect
from pygame.surface import Surface
from pygame.sprite import AbstractGroup
from pygame.sprite import Group
from pygame.sprite import RenderUpdates
from pygame.sprite import Sprite
class Direction(Enum):
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
def opposite(self, other: Direction):
return (self[0] + other[0], self[1] + other[1]) == (0, 0)
def __getitem__(self, i: int):
return self.value[i]
class SnakeHead(Sprite):
def __init__(
self,
size: int,
position: Tuple[int, int],
facing: Direction,
bounds: Rect,
) -> None:
super().__init__()
self.image = Surface((size, size))
self.image.fill(Color("aquamarine4"))
self.rect = self.image.get_rect()
self.rect.center = position
self.facing = facing
self.size = size
self.speed = size
self.bounds = bounds
def update(self, *args: Any, **kwargs: Any) -> None:
self.rect.move_ip(
(
self.facing[0] * self.speed,
self.facing[1] * self.speed,
)
)
if self.rect.right > self.bounds.right:
self.rect.left = 0
elif self.rect.left < 0:
self.rect.right = self.bounds.right
if self.rect.bottom > self.bounds.bottom:
self.rect.top = 0
elif self.rect.top < 0:
self.rect.bottom = self.bounds.bottom
def change_direction(self, direction: Direction):
if not self.facing == direction and not direction.opposite(self.facing):
self.facing = direction
class SnakeBody(Sprite):
def __init__(
self,
size: int,
position: Tuple[int, int],
colour: str = "white",
) -> None:
super().__init__()
self.image = Surface((size, size))
self.image.fill(Color(colour))
self.rect = self.image.get_rect()
self.rect.center = position
class Snake(RenderUpdates):
def __init__(self, game: Game) -> None:
self.segment_size = game.segment_size
self.colours = itertools.cycle(["aquamarine1", "aquamarine3"])
self.head = SnakeHead(
size=self.segment_size,
position=game.rect.center,
facing=Direction.RIGHT,
bounds=game.rect,
)
neck = [
SnakeBody(
size=self.segment_size,
position=game.rect.center,
colour=next(self.colours),
)
for _ in range(2)
]
super().__init__(*[self.head, *neck])
self.body = Group()
self.tail = neck[-1]
def update(self, *args: Any, **kwargs: Any) -> None:
self.head.update()
segments = self.sprites()
for i in range(len(segments) - 1, 0, -1):
segments[i].rect.center = segments[i - 1].rect.center
def change_direction(self, direction: Direction):
self.head.change_direction(direction)
def grow(self):
tail = SnakeBody(
size=self.segment_size,
position=self.tail.rect.center,
colour=next(self.colours),
)
self.tail = tail
self.add(self.tail)
self.body.add(self.tail)
class SnakeFood(Sprite):
def __init__(self, game: Game, size: int, *groups: AbstractGroup) -> None:
super().__init__(*groups)
self.image = Surface((size, size))
self.image.fill(Color("red"))
self.rect = self.image.get_rect()
self.rect.topleft = (
random.randint(0, game.rect.width),
random.randint(0, game.rect.height),
)
self.rect.clamp_ip(game.rect)
while pg.sprite.spritecollideany(self, game.snake):
self.rect.topleft = (
random.randint(0, game.rect.width),
random.randint(0, game.rect.height),
)
self.rect.clamp_ip(game.rect)
class Game:
def __init__(self) -> None:
self.rect = Rect(0, 0, 640, 480)
self.background = Surface(self.rect.size)
self.background.fill(Color("black"))
self.score = 0
self.framerate = 16
self.segment_size = 10
self.snake = Snake(self)
self.food_group = RenderUpdates(SnakeFood(game=self, size=self.segment_size))
pg.init()
def _init_display(self) -> Surface:
bestdepth = pg.display.mode_ok(self.rect.size, 0, 32)
screen = pg.display.set_mode(self.rect.size, 0, bestdepth)
pg.display.set_caption("Snake")
pg.mouse.set_visible(False)
screen.blit(self.background, (0, 0))
pg.display.flip()
return screen
def draw(self, screen: Surface):
dirty = self.snake.draw(screen)
pg.display.update(dirty)
dirty = self.food_group.draw(screen)
pg.display.update(dirty)
def update(self, screen):
self.food_group.clear(screen, self.background)
self.food_group.update()
self.snake.clear(screen, self.background)
self.snake.update()
def main(self) -> int:
screen = self._init_display()
clock = pg.time.Clock()
while self.snake.head.alive():
for event in pg.event.get():
if event.type == pg.QUIT or (
event.type == pg.KEYDOWN and event.key in (pg.K_ESCAPE, pg.K_q)
):
return self.score
keystate = pg.key.get_pressed()
if keystate[pg.K_RIGHT]:
self.snake.change_direction(Direction.RIGHT)
elif keystate[pg.K_LEFT]:
self.snake.change_direction(Direction.LEFT)
elif keystate[pg.K_UP]:
self.snake.change_direction(Direction.UP)
elif keystate[pg.K_DOWN]:
self.snake.change_direction(Direction.DOWN)
self.update(screen)
for food in pg.sprite.spritecollide(
self.snake.head, self.food_group, dokill=False
):
food.kill()
self.snake.grow()
self.score += 1
if self.score % 5 == 0:
self.framerate += 1
self.food_group.add(SnakeFood(self, self.segment_size))
if pg.sprite.spritecollideany(self.snake.head, self.snake.body):
self.snake.head.kill()
self.draw(screen)
clock.tick(self.framerate)
return self.score
if __name__ == "__main__":
game = Game()
score = game.main()
print(score)
| #include <windows.h>
#include <ctime>
#include <iostream>
#include <string>
const int WID = 60, HEI = 30, MAX_LEN = 600;
enum DIR { NORTH, EAST, SOUTH, WEST };
class snake {
public:
snake() {
console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( "Snake" );
COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord );
SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc );
CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci );
}
void play() {
std::string a;
while( 1 ) {
createField(); alive = true;
while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); }
COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c );
SetConsoleTextAttribute( console, 0x000b );
std::cout << "Play again [Y/N]? "; std::cin >> a;
if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return;
}
}
private:
void createField() {
COORD coord = { 0, 0 }; DWORD c;
FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c );
FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c );
SetConsoleCursorPosition( console, coord );
int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0;
for( x = 0; x < WID; x++ ) {
brd[x] = brd[x + WID * ( HEI - 1 )] = '+';
}
for( ; y < HEI; y++ ) {
brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+';
}
do {
x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );
} while( brd[x + WID * y] );
brd[x + WID * y] = '@';
tailIdx = 0; headIdx = 4; x = 3; y = 2;
for( int c = tailIdx; c < headIdx; c++ ) {
brd[x + WID * y] = '#';
snk[c].X = 3 + c; snk[c].Y = 2;
}
head = snk[3]; dir = EAST; points = 0;
}
void readKey() {
if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST;
if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST;
if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH;
if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH;
}
void drawField() {
COORD coord; char t;
for( int y = 0; y < HEI; y++ ) {
coord.Y = y;
for( int x = 0; x < WID; x++ ) {
t = brd[x + WID * y]; if( !t ) continue;
coord.X = x; SetConsoleCursorPosition( console, coord );
if( coord.X == head.X && coord.Y == head.Y ) {
SetConsoleTextAttribute( console, 0x002e );
std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 );
continue;
}
switch( t ) {
case '#': SetConsoleTextAttribute( console, 0x002a ); break;
case '+': SetConsoleTextAttribute( console, 0x0019 ); break;
case '@': SetConsoleTextAttribute( console, 0x004c ); break;
}
std::cout << t; SetConsoleTextAttribute( console, 0x0000 );
}
}
std::cout << t; SetConsoleTextAttribute( console, 0x0007 );
COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c );
std::cout << "Points: " << points;
}
void moveSnake() {
switch( dir ) {
case NORTH: head.Y--; break;
case EAST: head.X++; break;
case SOUTH: head.Y++; break;
case WEST: head.X--; break;
}
char t = brd[head.X + WID * head.Y];
if( t && t != '@' ) { alive = false; return; }
brd[head.X + WID * head.Y] = '#';
snk[headIdx].X = head.X; snk[headIdx].Y = head.Y;
if( ++headIdx >= MAX_LEN ) headIdx = 0;
if( t == '@' ) {
points++; int x, y;
do {
x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 );
} while( brd[x + WID * y] );
brd[x + WID * y] = '@'; return;
}
SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' ';
brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0;
if( ++tailIdx >= MAX_LEN ) tailIdx = 0;
}
bool alive; char brd[WID * HEI];
HANDLE console; DIR dir; COORD snk[MAX_LEN];
COORD head; int tailIdx, headIdx, points;
};
int main( int argc, char* argv[] ) {
srand( static_cast<unsigned>( time( NULL ) ) );
snake s; s.play(); return 0;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. | print "knight"[1:]
print "socks"[:-1]
print "brooms"[1:-1]
| #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
}
|
Port the provided Python code into C++ while preserving the original functionality. | print "knight"[1:]
print "socks"[:-1]
print "brooms"[1:-1]
| #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. | print "knight"[1:]
print "socks"[:-1]
print "brooms"[1:-1]
| #include <string>
#include <iostream>
int main( ) {
std::string word( "Premier League" ) ;
std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
return 0 ;
}
|
Port the following code from Python to C++ with equivalent syntax and logic. | from primesieve import primes
from math import isqrt
from functools import cache
p = primes(isqrt(1_000_000_000))
@cache
def phi(x, a):
res = 0
while True:
if not a or not x:
return x + res
a -= 1
res -= phi(x//p[a], a)
def legpi(n):
if n < 2: return 0
a = legpi(isqrt(n))
return phi(n, a) + a - 1
for e in range(10):
print(f'10^{e}', legpi(10**e))
| #include <cmath>
#include <iostream>
#include <vector>
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[q >> 1] = false;
}
s += (p + 1) << 2;
}
std::vector<int> primes;
if (limit > 2)
primes.push_back(2);
for (int i = 1; i < sieve.size(); ++i) {
if (sieve[i])
primes.push_back((i << 1) + 1);
}
return primes;
}
class legendre_prime_counter {
public:
explicit legendre_prime_counter(int limit);
int prime_count(int n);
private:
int phi(int x, int a);
std::vector<int> primes;
};
legendre_prime_counter::legendre_prime_counter(int limit) :
primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}
int legendre_prime_counter::prime_count(int n) {
if (n < 2)
return 0;
int a = prime_count(static_cast<int>(std::sqrt(n)));
return phi(n, a) + a - 1;
}
int legendre_prime_counter::phi(int x, int a) {
if (a == 0)
return x;
if (a == 1)
return x - (x >> 1);
int pa = primes[a - 1];
if (x <= pa)
return 1;
return phi(x, a - 1) - phi(x / pa, a - 1);
}
int main() {
legendre_prime_counter counter(1000000000);
for (int i = 0, n = 1; i < 10; ++i, n *= 10)
std::cout << "10^" << i << "\t" << counter.prime_count(n) << '\n';
}
|
Convert this Python snippet to C++ and keep its semantics consistent. | from primesieve import primes
from math import isqrt
from functools import cache
p = primes(isqrt(1_000_000_000))
@cache
def phi(x, a):
res = 0
while True:
if not a or not x:
return x + res
a -= 1
res -= phi(x//p[a], a)
def legpi(n):
if n < 2: return 0
a = legpi(isqrt(n))
return phi(n, a) + a - 1
for e in range(10):
print(f'10^{e}', legpi(10**e))
| #include <cmath>
#include <iostream>
#include <vector>
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[q >> 1] = false;
}
s += (p + 1) << 2;
}
std::vector<int> primes;
if (limit > 2)
primes.push_back(2);
for (int i = 1; i < sieve.size(); ++i) {
if (sieve[i])
primes.push_back((i << 1) + 1);
}
return primes;
}
class legendre_prime_counter {
public:
explicit legendre_prime_counter(int limit);
int prime_count(int n);
private:
int phi(int x, int a);
std::vector<int> primes;
};
legendre_prime_counter::legendre_prime_counter(int limit) :
primes(generate_primes(static_cast<int>(std::sqrt(limit)))) {}
int legendre_prime_counter::prime_count(int n) {
if (n < 2)
return 0;
int a = prime_count(static_cast<int>(std::sqrt(n)));
return phi(n, a) + a - 1;
}
int legendre_prime_counter::phi(int x, int a) {
if (a == 0)
return x;
if (a == 1)
return x - (x >> 1);
int pa = primes[a - 1];
if (x <= pa)
return 1;
return phi(x, a - 1) - phi(x / pa, a - 1);
}
int main() {
legendre_prime_counter counter(1000000000);
for (int i = 0, n = 1; i < 10; ++i, n *= 10)
std::cout << "10^" << i << "\t" << counter.prime_count(n) << '\n';
}
|
Generate an equivalent C++ version of this Python code. |
def query(buffer_length):
message = b'Here am I'
L = len(message)
return message[0:L*(L <= buffer_length)]
| #include <string>
using std::string;
extern "C" int
Query (char *Data, size_t *Length)
{
const string Message = "Here am I";
if (*Length < Message.length())
return false;
*Length = Message.length();
Message.copy(Data, *Length);
return true;
}
|
Convert the following code from Python to C++, ensuring the logic remains intact. | import fileinput
def longer(a, b):
try:
b[len(a)-1]
return False
except:
return True
longest, lines = '', ''
for x in fileinput.input():
if longer(x, longest):
lines, longest = x, x
elif not longer(longest, x):
lines += x
print(lines, end='')
| #include <iostream>
#include <string.h>
int main()
{
std::string longLine, longestLines, newLine;
while (std::cin >> newLine)
{
auto isNewLineShorter = longLine.c_str();
auto isLongLineShorter = newLine.c_str();
while (*isNewLineShorter && *isLongLineShorter)
{
isNewLineShorter = &isNewLineShorter[1];
isLongLineShorter = &isLongLineShorter[1];
}
if(*isNewLineShorter) continue;
if(*isLongLineShorter)
{
longLine = newLine;
longestLines = newLine;
}
else
{
longestLines+=newLine;
}
longestLines+="\n";
}
std::cout << "\nLongest string:\n" << longestLines;
}
|
Convert the following code from Python to C++, ensuring the logic remains intact. | from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( "bad init position")
rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)
while True:
print(st, '\t', end=" ")
for i, v in enumerate(tape):
if i == pos: print("[%s]" % (v,), end=" ")
else: print(v, end=" ")
print()
if st == halt: break
if (st, tape[pos]) not in rules: break
(v1, dr, s1) = rules[(st, tape[pos])]
tape[pos] = v1
if dr == 'left':
if pos > 0: pos -= 1
else: tape.insert(0, blank)
if dr == 'right':
pos += 1
if pos >= len(tape): tape.append(blank)
st = s1
print("incr machine\n")
run_utm(
halt = 'qf',
state = 'q0',
tape = list("111"),
blank = 'B',
rules = map(tuple,
["q0 1 1 right q0".split(),
"q0 B 1 stay qf".split()]
)
)
print("\nbusy beaver\n")
run_utm(
halt = 'halt',
state = 'a',
blank = '0',
rules = map(tuple,
["a 0 1 right b".split(),
"a 1 1 left c".split(),
"b 0 1 left a".split(),
"b 1 1 right b".split(),
"c 0 1 left b".split(),
"c 1 1 stay halt".split()]
)
)
print("\nsorting test\n")
run_utm(halt = 'STOP',
state = 'A',
blank = '0',
tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(),
rules = map(tuple,
["A 1 1 right A".split(),
"A 2 3 right B".split(),
"A 0 0 left E".split(),
"B 1 1 right B".split(),
"B 2 2 right B".split(),
"B 0 0 left C".split(),
"C 1 2 left D".split(),
"C 2 2 left C".split(),
"C 3 2 left E".split(),
"D 1 1 left D".split(),
"D 2 2 left D".split(),
"D 3 1 right A".split(),
"E 1 1 left E".split(),
"E 0 0 right STOP".split()]
)
)
| #include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iomanip>
typedef unsigned int uint;
using namespace std;
const uint TAPE_MAX_LEN = 49152;
struct action { char write, direction; };
class tape
{
public:
tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }
void reset() { clear( '0' ); headPos = _sp; }
char read(){ return _t[headPos]; }
void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }
void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }
void action( const action* a ) { write( a->write ); move( a->direction ); }
void print( int c = 10 )
{
int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;
for( int x = st; x < ed; x++ )
{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; }
cout << endl << setw( c + 1 ) << "^" << endl;
}
private:
void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }
void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }
string _t; uint headPos, _sp; char blk; const uint MAX_LEN;
};
class state
{
public:
bool operator ==( const string o ) { return o == name; }
string name, next; char symbol, write, direction;
};
class actionTable
{
public:
bool loadTable( string file )
{
reset();
ifstream mf; mf.open( file.c_str() ); if( mf.is_open() )
{
string str; state stt;
while( mf.good() )
{
getline( mf, str ); if( str[0] == '\'' ) break;
parseState( str, stt ); states.push_back( stt );
}
while( mf.good() )
{
getline( mf, str ); if( str == "" ) continue;
if( str[0] == '!' ) blank = str.erase( 0, 1 )[0];
if( str[0] == '^' ) curState = str.erase( 0, 1 );
if( str[0] == '>' ) input = str.erase( 0, 1 );
}
mf.close(); return true;
}
cout << "Could not open " << file << endl; return false;
}
bool action( char symbol, action& a )
{
vector<state>::iterator f = states.begin();
while( true )
{
f = find( f, states.end(), curState );
if( f == states.end() ) return false;
if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )
{ a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }
f++;
}
return true;
}
void reset() { states.clear(); blank = '0'; curState = input = ""; }
string getInput() { return input; }
char getBlank() { return blank; }
private:
void parseState( string str, state& stt )
{
string a[5]; int idx = 0;
for( string::iterator si = str.begin(); si != str.end(); si++ )
{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }
stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];
}
vector<state> states; char blank; string curState, input;
};
class utm
{
public:
utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; }
void start()
{
while( true )
{
reset(); int t = showMenu(); if( t == 0 ) return;
if( !at.loadTable( files[t - 1] ) ) return; startMachine();
}
}
private:
void simulate()
{
char r; action a;
while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }
cout << endl << endl; system( "pause" );
}
int showMenu()
{
int t = -1;
while( t < 0 || t > 3 )
{
system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit";
cout << endl << endl << "Choose an action "; cin >> t;
}
return t;
}
void reset() { tp.reset(); at.reset(); }
void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }
tape tp; actionTable at; string files[7];
};
int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
|
Write a version of this Python function in C++ with identical behavior. | from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( "bad init position")
rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)
while True:
print(st, '\t', end=" ")
for i, v in enumerate(tape):
if i == pos: print("[%s]" % (v,), end=" ")
else: print(v, end=" ")
print()
if st == halt: break
if (st, tape[pos]) not in rules: break
(v1, dr, s1) = rules[(st, tape[pos])]
tape[pos] = v1
if dr == 'left':
if pos > 0: pos -= 1
else: tape.insert(0, blank)
if dr == 'right':
pos += 1
if pos >= len(tape): tape.append(blank)
st = s1
print("incr machine\n")
run_utm(
halt = 'qf',
state = 'q0',
tape = list("111"),
blank = 'B',
rules = map(tuple,
["q0 1 1 right q0".split(),
"q0 B 1 stay qf".split()]
)
)
print("\nbusy beaver\n")
run_utm(
halt = 'halt',
state = 'a',
blank = '0',
rules = map(tuple,
["a 0 1 right b".split(),
"a 1 1 left c".split(),
"b 0 1 left a".split(),
"b 1 1 right b".split(),
"c 0 1 left b".split(),
"c 1 1 stay halt".split()]
)
)
print("\nsorting test\n")
run_utm(halt = 'STOP',
state = 'A',
blank = '0',
tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(),
rules = map(tuple,
["A 1 1 right A".split(),
"A 2 3 right B".split(),
"A 0 0 left E".split(),
"B 1 1 right B".split(),
"B 2 2 right B".split(),
"B 0 0 left C".split(),
"C 1 2 left D".split(),
"C 2 2 left C".split(),
"C 3 2 left E".split(),
"D 1 1 left D".split(),
"D 2 2 left D".split(),
"D 3 1 right A".split(),
"E 1 1 left E".split(),
"E 0 0 right STOP".split()]
)
)
| #include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iomanip>
typedef unsigned int uint;
using namespace std;
const uint TAPE_MAX_LEN = 49152;
struct action { char write, direction; };
class tape
{
public:
tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }
void reset() { clear( '0' ); headPos = _sp; }
char read(){ return _t[headPos]; }
void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }
void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }
void action( const action* a ) { write( a->write ); move( a->direction ); }
void print( int c = 10 )
{
int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;
for( int x = st; x < ed; x++ )
{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; }
cout << endl << setw( c + 1 ) << "^" << endl;
}
private:
void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }
void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }
string _t; uint headPos, _sp; char blk; const uint MAX_LEN;
};
class state
{
public:
bool operator ==( const string o ) { return o == name; }
string name, next; char symbol, write, direction;
};
class actionTable
{
public:
bool loadTable( string file )
{
reset();
ifstream mf; mf.open( file.c_str() ); if( mf.is_open() )
{
string str; state stt;
while( mf.good() )
{
getline( mf, str ); if( str[0] == '\'' ) break;
parseState( str, stt ); states.push_back( stt );
}
while( mf.good() )
{
getline( mf, str ); if( str == "" ) continue;
if( str[0] == '!' ) blank = str.erase( 0, 1 )[0];
if( str[0] == '^' ) curState = str.erase( 0, 1 );
if( str[0] == '>' ) input = str.erase( 0, 1 );
}
mf.close(); return true;
}
cout << "Could not open " << file << endl; return false;
}
bool action( char symbol, action& a )
{
vector<state>::iterator f = states.begin();
while( true )
{
f = find( f, states.end(), curState );
if( f == states.end() ) return false;
if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )
{ a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }
f++;
}
return true;
}
void reset() { states.clear(); blank = '0'; curState = input = ""; }
string getInput() { return input; }
char getBlank() { return blank; }
private:
void parseState( string str, state& stt )
{
string a[5]; int idx = 0;
for( string::iterator si = str.begin(); si != str.end(); si++ )
{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }
stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];
}
vector<state> states; char blank; string curState, input;
};
class utm
{
public:
utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; }
void start()
{
while( true )
{
reset(); int t = showMenu(); if( t == 0 ) return;
if( !at.loadTable( files[t - 1] ) ) return; startMachine();
}
}
private:
void simulate()
{
char r; action a;
while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }
cout << endl << endl; system( "pause" );
}
int showMenu()
{
int t = -1;
while( t < 0 || t > 3 )
{
system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit";
cout << endl << endl << "Choose an action "; cin >> t;
}
return t;
}
void reset() { tp.reset(); at.reset(); }
void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }
tape tp; actionTable at; string files[7];
};
int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
|
Change the following Python code into C++ without altering its purpose. | from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( "bad init position")
rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)
while True:
print(st, '\t', end=" ")
for i, v in enumerate(tape):
if i == pos: print("[%s]" % (v,), end=" ")
else: print(v, end=" ")
print()
if st == halt: break
if (st, tape[pos]) not in rules: break
(v1, dr, s1) = rules[(st, tape[pos])]
tape[pos] = v1
if dr == 'left':
if pos > 0: pos -= 1
else: tape.insert(0, blank)
if dr == 'right':
pos += 1
if pos >= len(tape): tape.append(blank)
st = s1
print("incr machine\n")
run_utm(
halt = 'qf',
state = 'q0',
tape = list("111"),
blank = 'B',
rules = map(tuple,
["q0 1 1 right q0".split(),
"q0 B 1 stay qf".split()]
)
)
print("\nbusy beaver\n")
run_utm(
halt = 'halt',
state = 'a',
blank = '0',
rules = map(tuple,
["a 0 1 right b".split(),
"a 1 1 left c".split(),
"b 0 1 left a".split(),
"b 1 1 right b".split(),
"c 0 1 left b".split(),
"c 1 1 stay halt".split()]
)
)
print("\nsorting test\n")
run_utm(halt = 'STOP',
state = 'A',
blank = '0',
tape = "2 2 2 1 2 2 1 2 1 2 1 2 1 2".split(),
rules = map(tuple,
["A 1 1 right A".split(),
"A 2 3 right B".split(),
"A 0 0 left E".split(),
"B 1 1 right B".split(),
"B 2 2 right B".split(),
"B 0 0 left C".split(),
"C 1 2 left D".split(),
"C 2 2 left C".split(),
"C 3 2 left E".split(),
"D 1 1 left D".split(),
"D 2 2 left D".split(),
"D 3 1 right A".split(),
"E 1 1 left E".split(),
"E 0 0 right STOP".split()]
)
)
| #include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <iomanip>
typedef unsigned int uint;
using namespace std;
const uint TAPE_MAX_LEN = 49152;
struct action { char write, direction; };
class tape
{
public:
tape( uint startPos = TAPE_MAX_LEN >> 1 ) : MAX_LEN( TAPE_MAX_LEN ) { _sp = startPos; reset(); }
void reset() { clear( '0' ); headPos = _sp; }
char read(){ return _t[headPos]; }
void input( string a ){ if( a == "" ) return; for( uint s = 0; s < a.length(); s++ ) _t[headPos + s] = a[s]; }
void clear( char c ) { _t.clear(); blk = c; _t.resize( MAX_LEN, blk ); }
void action( const action* a ) { write( a->write ); move( a->direction ); }
void print( int c = 10 )
{
int ml = static_cast<int>( MAX_LEN ), st = static_cast<int>( headPos ) - c, ed = static_cast<int>( headPos ) + c + 1, tx;
for( int x = st; x < ed; x++ )
{ tx = x; if( tx < 0 ) tx += ml; if( tx >= ml ) tx -= ml; cout << _t[tx]; }
cout << endl << setw( c + 1 ) << "^" << endl;
}
private:
void move( char d ) { if( d == 'N' ) return; headPos += d == 'R' ? 1 : -1; if( headPos >= MAX_LEN ) headPos = d == 'R' ? 0 : MAX_LEN - 1; }
void write( char a ) { if( a != 'N' ) { if( a == 'B' ) _t[headPos] = blk; else _t[headPos] = a; } }
string _t; uint headPos, _sp; char blk; const uint MAX_LEN;
};
class state
{
public:
bool operator ==( const string o ) { return o == name; }
string name, next; char symbol, write, direction;
};
class actionTable
{
public:
bool loadTable( string file )
{
reset();
ifstream mf; mf.open( file.c_str() ); if( mf.is_open() )
{
string str; state stt;
while( mf.good() )
{
getline( mf, str ); if( str[0] == '\'' ) break;
parseState( str, stt ); states.push_back( stt );
}
while( mf.good() )
{
getline( mf, str ); if( str == "" ) continue;
if( str[0] == '!' ) blank = str.erase( 0, 1 )[0];
if( str[0] == '^' ) curState = str.erase( 0, 1 );
if( str[0] == '>' ) input = str.erase( 0, 1 );
}
mf.close(); return true;
}
cout << "Could not open " << file << endl; return false;
}
bool action( char symbol, action& a )
{
vector<state>::iterator f = states.begin();
while( true )
{
f = find( f, states.end(), curState );
if( f == states.end() ) return false;
if( ( *f ).symbol == '*' || ( *f ).symbol == symbol || ( ( *f ).symbol == 'B' && blank == symbol ) )
{ a.direction = ( *f ).direction; a.write = ( *f ).write; curState = ( *f ).next; break; }
f++;
}
return true;
}
void reset() { states.clear(); blank = '0'; curState = input = ""; }
string getInput() { return input; }
char getBlank() { return blank; }
private:
void parseState( string str, state& stt )
{
string a[5]; int idx = 0;
for( string::iterator si = str.begin(); si != str.end(); si++ )
{ if( ( *si ) == ';' ) idx++; else a[idx].append( &( *si ), 1 ); }
stt.name = a[0]; stt.symbol = a[1][0]; stt.write = a[2][0]; stt.direction = a[3][0]; stt.next = a[4];
}
vector<state> states; char blank; string curState, input;
};
class utm
{
public:
utm() { files[0] = "incrementer.utm"; files[1] = "busy_beaver.utm"; files[2] = "sort.utm"; }
void start()
{
while( true )
{
reset(); int t = showMenu(); if( t == 0 ) return;
if( !at.loadTable( files[t - 1] ) ) return; startMachine();
}
}
private:
void simulate()
{
char r; action a;
while( true ) { tp.print(); r = tp.read(); if( !( at.action( r, a ) ) ) break; tp.action( &a ); }
cout << endl << endl; system( "pause" );
}
int showMenu()
{
int t = -1;
while( t < 0 || t > 3 )
{
system( "cls" ); cout << "1. Incrementer\n2. Busy beaver\n3. Sort\n\n0. Quit";
cout << endl << endl << "Choose an action "; cin >> t;
}
return t;
}
void reset() { tp.reset(); at.reset(); }
void startMachine() { system( "cls" ); tp.clear( at.getBlank() ); tp.input( at.getInput() ); simulate(); }
tape tp; actionTable at; string files[7];
};
int main( int a, char* args[] ){ utm mm; mm.start(); return 0; }
|
Ensure the translated C++ code behaves exactly like the original Python snippet. | import os
for directory in ['/', './']:
open(directory + 'output.txt', 'w').close()
os.mkdir(directory + 'docs')
| #include <direct.h>
#include <fstream>
int main() {
std::fstream f("output.txt", std::ios::out);
f.close();
f.open("/output.txt", std::ios::out);
f.close();
_mkdir("docs");
_mkdir("/docs");
return 0;
}
|
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically? | from itertools import count, islice
def primes(_cache=[2, 3]):
yield from _cache
for n in count(_cache[-1]+2, 2):
if isprime(n):
_cache.append(n)
yield n
def isprime(n, _seen={0: False, 1: False}):
def _isprime(n):
for p in primes():
if p*p > n:
return True
if n%p == 0:
return False
if n not in _seen:
_seen[n] = _isprime(n)
return _seen[n]
def unprime():
for a in count(1):
d = 1
while d <= a:
base = (a//(d*10))*(d*10) + (a%d)
if any(isprime(y) for y in range(base, base + d*10, d)):
break
d *= 10
else:
yield a
print('First 35:')
print(' '.join(str(i) for i in islice(unprime(), 35)))
print('\nThe 600-th:')
print(list(islice(unprime(), 599, 600))[0])
print()
first, need = [False]*10, 10
for p in unprime():
i = p%10
if first[i]: continue
first[i] = p
need -= 1
if not need:
break
for i,v in enumerate(first):
print(f'{i} ending: {v}')
| #include <iostream>
#include <cstdint>
#include "prime_sieve.hpp"
typedef uint32_t integer;
int count_digits(integer n) {
int digits = 0;
for (; n > 0; ++digits)
n /= 10;
return digits;
}
integer change_digit(integer n, int index, int new_digit) {
integer p = 1;
integer changed = 0;
for (; index > 0; p *= 10, n /= 10, --index)
changed += p * (n % 10);
changed += (10 * (n/10) + new_digit) * p;
return changed;
}
bool unprimeable(const prime_sieve& sieve, integer n) {
if (sieve.is_prime(n))
return false;
int d = count_digits(n);
for (int i = 0; i < d; ++i) {
for (int j = 0; j <= 9; ++j) {
integer m = change_digit(n, i, j);
if (m != n && sieve.is_prime(m))
return false;
}
}
return true;
}
int main() {
const integer limit = 10000000;
prime_sieve sieve(limit);
std::cout.imbue(std::locale(""));
std::cout << "First 35 unprimeable numbers:\n";
integer n = 100;
integer lowest[10] = { 0 };
for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {
if (unprimeable(sieve, n)) {
if (count < 35) {
if (count != 0)
std::cout << ", ";
std::cout << n;
}
++count;
if (count == 600)
std::cout << "\n600th unprimeable number: " << n << '\n';
int last_digit = n % 10;
if (lowest[last_digit] == 0) {
lowest[last_digit] = n;
++found;
}
}
}
for (int i = 0; i < 10; ++i)
std::cout << "Least unprimeable number ending in " << i << ": " << lowest[i] << '\n';
return 0;
}
|
Produce a language-to-language conversion: from Python to C++, same semantics. |
def combine( snl, snr ):
cl = {}
if isinstance(snl, int):
cl['1'] = snl
elif isinstance(snl, string):
cl[snl] = 1
else:
cl.update( snl)
if isinstance(snr, int):
n = cl.get('1', 0)
cl['1'] = n + snr
elif isinstance(snr, string):
n = cl.get(snr, 0)
cl[snr] = n + 1
else:
for k,v in snr.items():
n = cl.get(k, 0)
cl[k] = n+v
return cl
def constrain(nsum, vn ):
nn = {}
nn.update(vn)
n = nn.get('1', 0)
nn['1'] = n - nsum
return nn
def makeMatrix( constraints ):
vmap = set()
for c in constraints:
vmap.update( c.keys())
vmap.remove('1')
nvars = len(vmap)
vmap = sorted(vmap)
mtx = []
for c in constraints:
row = []
for vv in vmap:
row.append(float(c.get(vv, 0)))
row.append(-float(c.get('1',0)))
mtx.append(row)
if len(constraints) == nvars:
print 'System appears solvable'
elif len(constraints) < nvars:
print 'System is not solvable - needs more constraints.'
return mtx, vmap
def SolvePyramid( vl, cnstr ):
vl.reverse()
constraints = [cnstr]
lvls = len(vl)
for lvln in range(1,lvls):
lvd = vl[lvln]
for k in range(lvls - lvln):
sn = lvd[k]
ll = vl[lvln-1]
vn = combine(ll[k], ll[k+1])
if sn is None:
lvd[k] = vn
else:
constraints.append(constrain( sn, vn ))
print 'Constraint Equations:'
for cstr in constraints:
fset = ('%d*%s'%(v,k) for k,v in cstr.items() )
print ' + '.join(fset), ' = 0'
mtx,vmap = makeMatrix(constraints)
MtxSolve(mtx)
d = len(vmap)
for j in range(d):
print vmap[j],'=', mtx[j][d]
def MtxSolve(mtx):
mDim = len(mtx)
for j in range(mDim):
rw0= mtx[j]
f = 1.0/rw0[j]
for k in range(j, mDim+1):
rw0[k] *= f
for l in range(1+j,mDim):
rwl = mtx[l]
f = -rwl[j]
for k in range(j, mDim+1):
rwl[k] += f * rw0[k]
for j1 in range(1,mDim):
j = mDim - j1
rw0= mtx[j]
for l in range(0, j):
rwl = mtx[l]
f = -rwl[j]
rwl[j] += f * rw0[j]
rwl[mDim] += f * rw0[mDim]
return mtx
p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]
addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }
SolvePyramid( p, addlConstraint)
| #include <iostream>
#include <iomanip>
inline int sign(int i) {
return i < 0 ? -1 : i > 0;
}
inline int& E(int *x, int row, int col) {
return x[row * (row + 1) / 2 + col];
}
int iter(int *v, int *diff) {
E(v, 0, 0) = 151;
E(v, 2, 0) = 40;
E(v, 4, 1) = 11;
E(v, 4, 3) = 4;
for (auto i = 1u; i < 5u; i++)
for (auto j = 0u; j <= i; j++) {
E(diff, i, j) = 0;
if (j < i)
E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);
if (j)
E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);
}
for (auto i = 0u; i < 4u; i++)
for (auto j = 0u; j < i; j++)
E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);
E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);
uint sum;
int e = 0;
for (auto i = sum = 0u; i < 15u; i++) {
sum += !!sign(e = diff[i]);
if (e >= 4 || e <= -4)
v[i] += e / 5;
else if (rand() < RAND_MAX / 4)
v[i] += sign(e);
}
return sum;
}
void show(int *x) {
for (auto i = 0u; i < 5u; i++)
for (auto j = 0u; j <= i; j++)
std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n');
}
int main() {
int v[15] = { 0 }, diff[15] = { 0 };
for (auto i = 1u, s = 1u; s; i++) {
s = iter(v, diff);
std::cout << "pass " << i << ": " << s << std::endl;
}
show(v);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. |
def combine( snl, snr ):
cl = {}
if isinstance(snl, int):
cl['1'] = snl
elif isinstance(snl, string):
cl[snl] = 1
else:
cl.update( snl)
if isinstance(snr, int):
n = cl.get('1', 0)
cl['1'] = n + snr
elif isinstance(snr, string):
n = cl.get(snr, 0)
cl[snr] = n + 1
else:
for k,v in snr.items():
n = cl.get(k, 0)
cl[k] = n+v
return cl
def constrain(nsum, vn ):
nn = {}
nn.update(vn)
n = nn.get('1', 0)
nn['1'] = n - nsum
return nn
def makeMatrix( constraints ):
vmap = set()
for c in constraints:
vmap.update( c.keys())
vmap.remove('1')
nvars = len(vmap)
vmap = sorted(vmap)
mtx = []
for c in constraints:
row = []
for vv in vmap:
row.append(float(c.get(vv, 0)))
row.append(-float(c.get('1',0)))
mtx.append(row)
if len(constraints) == nvars:
print 'System appears solvable'
elif len(constraints) < nvars:
print 'System is not solvable - needs more constraints.'
return mtx, vmap
def SolvePyramid( vl, cnstr ):
vl.reverse()
constraints = [cnstr]
lvls = len(vl)
for lvln in range(1,lvls):
lvd = vl[lvln]
for k in range(lvls - lvln):
sn = lvd[k]
ll = vl[lvln-1]
vn = combine(ll[k], ll[k+1])
if sn is None:
lvd[k] = vn
else:
constraints.append(constrain( sn, vn ))
print 'Constraint Equations:'
for cstr in constraints:
fset = ('%d*%s'%(v,k) for k,v in cstr.items() )
print ' + '.join(fset), ' = 0'
mtx,vmap = makeMatrix(constraints)
MtxSolve(mtx)
d = len(vmap)
for j in range(d):
print vmap[j],'=', mtx[j][d]
def MtxSolve(mtx):
mDim = len(mtx)
for j in range(mDim):
rw0= mtx[j]
f = 1.0/rw0[j]
for k in range(j, mDim+1):
rw0[k] *= f
for l in range(1+j,mDim):
rwl = mtx[l]
f = -rwl[j]
for k in range(j, mDim+1):
rwl[k] += f * rw0[k]
for j1 in range(1,mDim):
j = mDim - j1
rw0= mtx[j]
for l in range(0, j):
rwl = mtx[l]
f = -rwl[j]
rwl[j] += f * rw0[j]
rwl[mDim] += f * rw0[mDim]
return mtx
p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ]
addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 }
SolvePyramid( p, addlConstraint)
| #include <iostream>
#include <iomanip>
inline int sign(int i) {
return i < 0 ? -1 : i > 0;
}
inline int& E(int *x, int row, int col) {
return x[row * (row + 1) / 2 + col];
}
int iter(int *v, int *diff) {
E(v, 0, 0) = 151;
E(v, 2, 0) = 40;
E(v, 4, 1) = 11;
E(v, 4, 3) = 4;
for (auto i = 1u; i < 5u; i++)
for (auto j = 0u; j <= i; j++) {
E(diff, i, j) = 0;
if (j < i)
E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);
if (j)
E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);
}
for (auto i = 0u; i < 4u; i++)
for (auto j = 0u; j < i; j++)
E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);
E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);
uint sum;
int e = 0;
for (auto i = sum = 0u; i < 15u; i++) {
sum += !!sign(e = diff[i]);
if (e >= 4 || e <= -4)
v[i] += e / 5;
else if (rand() < RAND_MAX / 4)
v[i] += sign(e);
}
return sum;
}
void show(int *x) {
for (auto i = 0u; i < 5u; i++)
for (auto j = 0u; j <= i; j++)
std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n');
}
int main() {
int v[15] = { 0 }, diff[15] = { 0 };
for (auto i = 1u, s = 1u; s; i++) {
s = iter(v, diff);
std::cout << "pass " << i << ": " << s << std::endl;
}
show(v);
return 0;
}
|
Convert this Python block to C++, preserving its control flow and logic. |
from sympy import isprime
def primality_pretest(k):
if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23):
return (k <= 23)
return True
def is_chernick(n, m):
t = 9 * m
if not primality_pretest(6 * m + 1):
return False
if not primality_pretest(12 * m + 1):
return False
for i in range(1,n-1):
if not primality_pretest((t << i) + 1):
return False
if not isprime(6 * m + 1):
return False
if not isprime(12 * m + 1):
return False
for i in range(1,n - 1):
if not isprime((t << i) + 1):
return False
return True
for n in range(3,10):
if n > 4:
multiplier = 1 << (n - 4)
else:
multiplier = 1
if n > 5:
multiplier *= 5
k = 1
while True:
m = k * multiplier
if is_chernick(n, m):
print("a("+str(n)+") has m = "+str(m))
break
k += 1
| #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 probprime(u64 k, mpz_t n) {
mpz_set_ui(n, k);
return mpz_probab_prime_p(n, 0);
}
bool is_chernick(int n, u64 m, mpz_t z) {
if (!primality_pretest(6 * m + 1)) {
return false;
}
if (!primality_pretest(12 * m + 1)) {
return false;
}
u64 t = 9 * m;
for (int i = 1; i <= n - 2; i++) {
if (!primality_pretest((t << i) + 1)) {
return false;
}
}
if (!probprime(6 * m + 1, z)) {
return false;
}
if (!probprime(12 * m + 1, z)) {
return false;
}
for (int i = 1; i <= n - 2; i++) {
if (!probprime((t << i) + 1, z)) {
return false;
}
}
return true;
}
int main() {
mpz_t z;
mpz_inits(z, NULL);
for (int n = 3; n <= 10; n++) {
u64 multiplier = (n > 4) ? (1 << (n - 4)) : 1;
if (n > 5) {
multiplier *= 5;
}
for (u64 k = 1; ; k++) {
u64 m = k * multiplier;
if (is_chernick(n, m, z)) {
cout << "a(" << n << ") has m = " << m << endl;
break;
}
}
}
return 0;
}
|
Translate the given Python code snippet into C++ without altering its behavior. |
from sympy.geometry import Point, Triangle
def sign(pt1, pt2, pt3):
return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)
def iswithin(point, pt1, pt2, pt3):
zval1 = sign(point, pt1, pt2)
zval2 = sign(point, pt2, pt3)
zval3 = sign(point, pt3, pt1)
notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0
notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0
return notanyneg or notanypos
if __name__ == "__main__":
POINTS = [Point(0, 0)]
TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))
for pnt in POINTS:
a, b, c = TRI.vertices
isornot = "is" if iswithin(pnt, a, b, c) else "is not"
print("Point", pnt, isornot, "within the triangle", TRI)
| #include <iostream>
const double EPS = 0.001;
const double EPS_SQUARE = EPS * EPS;
double side(double x1, double y1, double x2, double y2, double x, double y) {
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);
}
bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;
double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;
double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double xMin = std::min(x1, std::min(x2, x3)) - EPS;
double xMax = std::max(x1, std::max(x2, x3)) + EPS;
double yMin = std::min(y1, std::min(y2, y3)) - EPS;
double yMax = std::max(y1, std::max(y2, y3)) + EPS;
return !(x < xMin || xMax < x || y < yMin || yMax < y);
}
double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {
double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;
if (dotProduct < 0) {
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
} else if (dotProduct <= 1) {
double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
} else {
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
}
bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {
return false;
}
if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
return true;
}
if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {
return true;
}
return false;
}
void printPoint(double x, double y) {
std::cout << '(' << x << ", " << y << ')';
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
std::cout << "Triangle is [";
printPoint(x1, y1);
std::cout << ", ";
printPoint(x2, y2);
std::cout << ", ";
printPoint(x3, y3);
std::cout << "]\n";
}
void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
printTriangle(x1, y1, x2, y2, x3, y3);
std::cout << "Point ";
printPoint(x, y);
std::cout << " is within triangle? ";
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
std::cout << "true\n";
} else {
std::cout << "false\n";
}
}
int main() {
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
return 0;
}
|
Write a version of this Python function in C++ with identical behavior. |
from sympy.geometry import Point, Triangle
def sign(pt1, pt2, pt3):
return (pt1.x - pt3.x) * (pt2.y - pt3.y) - (pt2.x - pt3.x) * (pt1.y - pt3.y)
def iswithin(point, pt1, pt2, pt3):
zval1 = sign(point, pt1, pt2)
zval2 = sign(point, pt2, pt3)
zval3 = sign(point, pt3, pt1)
notanyneg = zval1 >= 0 and zval2 >= 0 and zval3 >= 0
notanypos = zval1 <= 0 and zval2 <= 0 and zval3 <= 0
return notanyneg or notanypos
if __name__ == "__main__":
POINTS = [Point(0, 0)]
TRI = Triangle(Point(1.5, 2.4), Point(5.1, -3.1), Point(-3.8, 0.5))
for pnt in POINTS:
a, b, c = TRI.vertices
isornot = "is" if iswithin(pnt, a, b, c) else "is not"
print("Point", pnt, isornot, "within the triangle", TRI)
| #include <iostream>
const double EPS = 0.001;
const double EPS_SQUARE = EPS * EPS;
double side(double x1, double y1, double x2, double y2, double x, double y) {
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);
}
bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;
double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;
double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double xMin = std::min(x1, std::min(x2, x3)) - EPS;
double xMax = std::max(x1, std::max(x2, x3)) + EPS;
double yMin = std::min(y1, std::min(y2, y3)) - EPS;
double yMax = std::max(y1, std::max(y2, y3)) + EPS;
return !(x < xMin || xMax < x || y < yMin || yMax < y);
}
double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {
double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;
if (dotProduct < 0) {
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
} else if (dotProduct <= 1) {
double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
} else {
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
}
bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {
return false;
}
if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
return true;
}
if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {
return true;
}
return false;
}
void printPoint(double x, double y) {
std::cout << '(' << x << ", " << y << ')';
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
std::cout << "Triangle is [";
printPoint(x1, y1);
std::cout << ", ";
printPoint(x2, y2);
std::cout << ", ";
printPoint(x3, y3);
std::cout << "]\n";
}
void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
printTriangle(x1, y1, x2, y2, x3, y3);
std::cout << "Point ";
printPoint(x, y);
std::cout << " is within triangle? ";
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
std::cout << "true\n";
} else {
std::cout << "false\n";
}
}
int main() {
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
return 0;
}
|
Write the same code in C++ as shown below in Python. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def tau(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= 1 + k
return ans
if __name__ == "__main__":
print(*map(tau, range(1, 101)))
| #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(3) << divisor_count(n);
if (n % 20 == 0)
std::cout << '\n';
}
}
|
Change the following Python code into C++ without altering its purpose. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def tau(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= 1 + k
return ans
if __name__ == "__main__":
print(*map(tau, range(1, 101)))
| #include <iomanip>
#include <iostream>
unsigned int divisor_count(unsigned int n) {
unsigned int total = 1;
for (; (n & 1) == 0; n >>= 1)
++total;
for (unsigned int p = 3; p * p <= n; p += 2) {
unsigned int count = 1;
for (; n % p == 0; n /= p)
++count;
total *= count;
}
if (n > 1)
total *= 2;
return total;
}
int main() {
const unsigned int limit = 100;
std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
for (unsigned int n = 1; n <= limit; ++n) {
std::cout << std::setw(3) << divisor_count(n);
if (n % 20 == 0)
std::cout << '\n';
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.