Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert the following code from Java to C++, ensuring the logic remains intact.
import java.util.Arrays; import java.util.List; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public interface PythagComp{ static void main(String... args){ System.out.println(run(20)); } static List<List<Integer>> run(int n){ return range(1, n).mapToObj( x -> range(x, n).mapToObj( y -> range(y, n).mapToObj( z -> new Integer[]{x, y, z} ) ) ) .flatMap(identity()) .flatMap(identity()) .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2]) .map(Arrays::asList) .collect(toList()) ; } }
#include <vector> #include <cmath> #include <iostream> #include <algorithm> #include <iterator> void list_comprehension( std::vector<int> & , int ) ; int main( ) { std::vector<int> triangles ; list_comprehension( triangles , 20 ) ; std::copy( triangles.begin( ) , triangles.end( ) , std::ostream_iterator<int>( std::cout , " " ) ) ; std::cout << std::endl ; return 0 ; } void list_comprehension( std::vector<int> & numbers , int upper_border ) { for ( int a = 1 ; a < upper_border ; a++ ) { for ( int b = a + 1 ; b < upper_border ; b++ ) { double c = pow( a * a + b * b , 0.5 ) ; if ( ( c * c ) < pow( upper_border , 2 ) + 1 ) { if ( c == floor( c ) ) { numbers.push_back( a ) ; numbers.push_back( b ) ; numbers.push_back( static_cast<int>( c ) ) ; } } } } }
Keep all operations the same but rewrite the snippet in C++.
public static void sort(int[] nums){ for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){ int smallest = Integer.MAX_VALUE; int smallestAt = currentPlace+1; for(int check = currentPlace; check<nums.length;check++){ if(nums[check]<smallest){ smallestAt = check; smallest = nums[check]; } } int temp = nums[currentPlace]; nums[currentPlace] = nums[smallestAt]; nums[smallestAt] = temp; } }
#include <algorithm> #include <iterator> #include <iostream> template<typename ForwardIterator> void selection_sort(ForwardIterator begin, ForwardIterator end) { for(auto i = begin; i != end; ++i) { std::iter_swap(i, std::min_element(i, end)); } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; selection_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
Maintain the same structure and functionality when rewriting this code in C++.
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t; } std::swap(n, k); if (n % 4 == 3 && k % 4 == 3) t = -t; n %= k; } return k == 1 ? t : 0; } void print_table(std::ostream& out, int kmax, int nmax) { out << "n\\k|"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << k; out << "\n----"; for (int k = 0; k <= kmax; ++k) out << "---"; out << '\n'; for (int n = 1; n <= nmax; n += 2) { out << std::setw(2) << n << " |"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << jacobi(k, n); out << '\n'; } } int main() { print_table(std::cout, 20, 21); return 0; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
public class JacobiSymbol { public static void main(String[] args) { int max = 30; System.out.printf("n\\k "); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", k); } System.out.printf("%n"); for ( int n = 1 ; n <= max ; n += 2 ) { System.out.printf("%2d ", n); for ( int k = 1 ; k <= max ; k++ ) { System.out.printf("%2d ", jacobiSymbol(k, n)); } System.out.printf("%n"); } } private static int jacobiSymbol(int k, int n) { if ( k < 0 || n % 2 == 0 ) { throw new IllegalArgumentException("Invalid value. k = " + k + ", n = " + n); } k %= n; int jacobi = 1; while ( k > 0 ) { while ( k % 2 == 0 ) { k /= 2; int r = n % 8; if ( r == 3 || r == 5 ) { jacobi = -jacobi; } } int temp = n; n = k; k = temp; if ( k % 4 == 3 && n % 4 == 3 ) { jacobi = -jacobi; } k %= n; } if ( n == 1 ) { return jacobi; } return 0; } }
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t; } std::swap(n, k); if (n % 4 == 3 && k % 4 == 3) t = -t; n %= k; } return k == 1 ? t : 0; } void print_table(std::ostream& out, int kmax, int nmax) { out << "n\\k|"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << k; out << "\n----"; for (int k = 0; k <= kmax; ++k) out << "---"; out << '\n'; for (int n = 1; n <= nmax; n += 2) { out << std::setw(2) << n << " |"; for (int k = 0; k <= kmax; ++k) out << ' ' << std::setw(2) << jacobi(k, n); out << '\n'; } } int main() { print_table(std::cout, 20, 21); return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.*; public class KdTree { private int dimensions_; private Node root_ = null; private Node best_ = null; private double bestDistance_ = 0; private int visited_ = 0; public KdTree(int dimensions, List<Node> nodes) { dimensions_ = dimensions; root_ = makeTree(nodes, 0, nodes.size(), 0); } public Node findNearest(Node target) { if (root_ == null) throw new IllegalStateException("Tree is empty!"); best_ = null; visited_ = 0; bestDistance_ = 0; nearest(root_, target, 0); return best_; } public int visited() { return visited_; } public double distance() { return Math.sqrt(bestDistance_); } private void nearest(Node root, Node target, int index) { if (root == null) return; ++visited_; double d = root.distance(target); if (best_ == null || d < bestDistance_) { bestDistance_ = d; best_ = root; } if (bestDistance_ == 0) return; double dx = root.get(index) - target.get(index); index = (index + 1) % dimensions_; nearest(dx > 0 ? root.left_ : root.right_, target, index); if (dx * dx >= bestDistance_) return; nearest(dx > 0 ? root.right_ : root.left_, target, index); } private Node makeTree(List<Node> nodes, int begin, int end, int index) { if (end <= begin) return null; int n = begin + (end - begin)/2; Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index)); index = (index + 1) % dimensions_; node.left_ = makeTree(nodes, begin, n, index); node.right_ = makeTree(nodes, n + 1, end, index); return node; } private static class NodeComparator implements Comparator<Node> { private int index_; private NodeComparator(int index) { index_ = index; } public int compare(Node n1, Node n2) { return Double.compare(n1.get(index_), n2.get(index_)); } } public static class Node { private double[] coords_; private Node left_ = null; private Node right_ = null; public Node(double[] coords) { coords_ = coords; } public Node(double x, double y) { this(new double[]{x, y}); } public Node(double x, double y, double z) { this(new double[]{x, y, z}); } double get(int index) { return coords_[index]; } double distance(Node node) { double dist = 0; for (int i = 0; i < coords_.length; ++i) { double d = coords_[i] - node.coords_[i]; dist += d * d; } return dist; } public String toString() { StringBuilder s = new StringBuilder("("); for (int i = 0; i < coords_.length; ++i) { if (i > 0) s.append(", "); s.append(coords_[i]); } s.append(')'); return s.toString(); } } }
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { size_t n = std::min(dimensions, list.size()); std::copy_n(list.begin(), n, coords_.begin()); } coordinate_type get(size_t index) const { return coords_[index]; } double distance(const point& pt) const { double dist = 0; for (size_t i = 0; i < dimensions; ++i) { double d = get(i) - pt.get(i); dist += d * d; } return dist; } private: std::array<coordinate_type, dimensions> coords_; }; template<typename coordinate_type, size_t dimensions> std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) { out << '('; for (size_t i = 0; i < dimensions; ++i) { if (i > 0) out << ", "; out << pt.get(i); } out << ')'; return out; } template<typename coordinate_type, size_t dimensions> class kdtree { public: typedef point<coordinate_type, dimensions> point_type; private: struct node { node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {} coordinate_type get(size_t index) const { return point_.get(index); } double distance(const point_type& pt) const { return point_.distance(pt); } point_type point_; node* left_; node* right_; }; node* root_ = nullptr; node* best_ = nullptr; double best_dist_ = 0; size_t visited_ = 0; std::vector<node> nodes_; struct node_cmp { node_cmp(size_t index) : index_(index) {} bool operator()(const node& n1, const node& n2) const { return n1.point_.get(index_) < n2.point_.get(index_); } size_t index_; }; node* make_tree(size_t begin, size_t end, size_t index) { if (end <= begin) return nullptr; size_t n = begin + (end - begin)/2; auto i = nodes_.begin(); std::nth_element(i + begin, i + n, i + end, node_cmp(index)); index = (index + 1) % dimensions; nodes_[n].left_ = make_tree(begin, n, index); nodes_[n].right_ = make_tree(n + 1, end, index); return &nodes_[n]; } void nearest(node* root, const point_type& point, size_t index) { if (root == nullptr) return; ++visited_; double d = root->distance(point); if (best_ == nullptr || d < best_dist_) { best_dist_ = d; best_ = root; } if (best_dist_ == 0) return; double dx = root->get(index) - point.get(index); index = (index + 1) % dimensions; nearest(dx > 0 ? root->left_ : root->right_, point, index); if (dx * dx >= best_dist_) return; nearest(dx > 0 ? root->right_ : root->left_, point, index); } public: kdtree(const kdtree&) = delete; kdtree& operator=(const kdtree&) = delete; template<typename iterator> kdtree(iterator begin, iterator end) : nodes_(begin, end) { root_ = make_tree(0, nodes_.size(), 0); } template<typename func> kdtree(func&& f, size_t n) { nodes_.reserve(n); for (size_t i = 0; i < n; ++i) nodes_.push_back(f()); root_ = make_tree(0, nodes_.size(), 0); } bool empty() const { return nodes_.empty(); } size_t visited() const { return visited_; } double distance() const { return std::sqrt(best_dist_); } const point_type& nearest(const point_type& pt) { if (root_ == nullptr) throw std::logic_error("tree is empty"); best_ = nullptr; visited_ = 0; best_dist_ = 0; nearest(root_, pt, 0); return best_->point_; } }; void test_wikipedia() { typedef point<int, 2> point2d; typedef kdtree<int, 2> tree2d; point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } }; tree2d tree(std::begin(points), std::end(points)); point2d n = tree.nearest({ 9, 2 }); std::cout << "Wikipedia example data:\n"; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } typedef point<double, 3> point3d; typedef kdtree<double, 3> tree3d; struct random_point_generator { random_point_generator(double min, double max) : engine_(std::random_device()()), distribution_(min, max) {} point3d operator()() { double x = distribution_(engine_); double y = distribution_(engine_); double z = distribution_(engine_); return point3d({x, y, z}); } std::mt19937 engine_; std::uniform_real_distribution<double> distribution_; }; void test_random(size_t count) { random_point_generator rpg(0, 1); tree3d tree(rpg, count); point3d pt(rpg()); point3d n = tree.nearest(pt); std::cout << "Random data (" << count << " points):\n"; std::cout << "point: " << pt << '\n'; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } int main() { try { test_wikipedia(); std::cout << '\n'; test_random(1000); std::cout << '\n'; test_random(1000000); } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; }
Translate the given Java code snippet into C++ without altering its behavior.
import java.util.*; public class KdTree { private int dimensions_; private Node root_ = null; private Node best_ = null; private double bestDistance_ = 0; private int visited_ = 0; public KdTree(int dimensions, List<Node> nodes) { dimensions_ = dimensions; root_ = makeTree(nodes, 0, nodes.size(), 0); } public Node findNearest(Node target) { if (root_ == null) throw new IllegalStateException("Tree is empty!"); best_ = null; visited_ = 0; bestDistance_ = 0; nearest(root_, target, 0); return best_; } public int visited() { return visited_; } public double distance() { return Math.sqrt(bestDistance_); } private void nearest(Node root, Node target, int index) { if (root == null) return; ++visited_; double d = root.distance(target); if (best_ == null || d < bestDistance_) { bestDistance_ = d; best_ = root; } if (bestDistance_ == 0) return; double dx = root.get(index) - target.get(index); index = (index + 1) % dimensions_; nearest(dx > 0 ? root.left_ : root.right_, target, index); if (dx * dx >= bestDistance_) return; nearest(dx > 0 ? root.right_ : root.left_, target, index); } private Node makeTree(List<Node> nodes, int begin, int end, int index) { if (end <= begin) return null; int n = begin + (end - begin)/2; Node node = QuickSelect.select(nodes, begin, end - 1, n, new NodeComparator(index)); index = (index + 1) % dimensions_; node.left_ = makeTree(nodes, begin, n, index); node.right_ = makeTree(nodes, n + 1, end, index); return node; } private static class NodeComparator implements Comparator<Node> { private int index_; private NodeComparator(int index) { index_ = index; } public int compare(Node n1, Node n2) { return Double.compare(n1.get(index_), n2.get(index_)); } } public static class Node { private double[] coords_; private Node left_ = null; private Node right_ = null; public Node(double[] coords) { coords_ = coords; } public Node(double x, double y) { this(new double[]{x, y}); } public Node(double x, double y, double z) { this(new double[]{x, y, z}); } double get(int index) { return coords_[index]; } double distance(Node node) { double dist = 0; for (int i = 0; i < coords_.length; ++i) { double d = coords_[i] - node.coords_[i]; dist += d * d; } return dist; } public String toString() { StringBuilder s = new StringBuilder("("); for (int i = 0; i < coords_.length; ++i) { if (i > 0) s.append(", "); s.append(coords_[i]); } s.append(')'); return s.toString(); } } }
#include <algorithm> #include <array> #include <cmath> #include <iostream> #include <random> #include <vector> template<typename coordinate_type, size_t dimensions> class point { public: point(std::array<coordinate_type, dimensions> c) : coords_(c) {} point(std::initializer_list<coordinate_type> list) { size_t n = std::min(dimensions, list.size()); std::copy_n(list.begin(), n, coords_.begin()); } coordinate_type get(size_t index) const { return coords_[index]; } double distance(const point& pt) const { double dist = 0; for (size_t i = 0; i < dimensions; ++i) { double d = get(i) - pt.get(i); dist += d * d; } return dist; } private: std::array<coordinate_type, dimensions> coords_; }; template<typename coordinate_type, size_t dimensions> std::ostream& operator<<(std::ostream& out, const point<coordinate_type, dimensions>& pt) { out << '('; for (size_t i = 0; i < dimensions; ++i) { if (i > 0) out << ", "; out << pt.get(i); } out << ')'; return out; } template<typename coordinate_type, size_t dimensions> class kdtree { public: typedef point<coordinate_type, dimensions> point_type; private: struct node { node(const point_type& pt) : point_(pt), left_(nullptr), right_(nullptr) {} coordinate_type get(size_t index) const { return point_.get(index); } double distance(const point_type& pt) const { return point_.distance(pt); } point_type point_; node* left_; node* right_; }; node* root_ = nullptr; node* best_ = nullptr; double best_dist_ = 0; size_t visited_ = 0; std::vector<node> nodes_; struct node_cmp { node_cmp(size_t index) : index_(index) {} bool operator()(const node& n1, const node& n2) const { return n1.point_.get(index_) < n2.point_.get(index_); } size_t index_; }; node* make_tree(size_t begin, size_t end, size_t index) { if (end <= begin) return nullptr; size_t n = begin + (end - begin)/2; auto i = nodes_.begin(); std::nth_element(i + begin, i + n, i + end, node_cmp(index)); index = (index + 1) % dimensions; nodes_[n].left_ = make_tree(begin, n, index); nodes_[n].right_ = make_tree(n + 1, end, index); return &nodes_[n]; } void nearest(node* root, const point_type& point, size_t index) { if (root == nullptr) return; ++visited_; double d = root->distance(point); if (best_ == nullptr || d < best_dist_) { best_dist_ = d; best_ = root; } if (best_dist_ == 0) return; double dx = root->get(index) - point.get(index); index = (index + 1) % dimensions; nearest(dx > 0 ? root->left_ : root->right_, point, index); if (dx * dx >= best_dist_) return; nearest(dx > 0 ? root->right_ : root->left_, point, index); } public: kdtree(const kdtree&) = delete; kdtree& operator=(const kdtree&) = delete; template<typename iterator> kdtree(iterator begin, iterator end) : nodes_(begin, end) { root_ = make_tree(0, nodes_.size(), 0); } template<typename func> kdtree(func&& f, size_t n) { nodes_.reserve(n); for (size_t i = 0; i < n; ++i) nodes_.push_back(f()); root_ = make_tree(0, nodes_.size(), 0); } bool empty() const { return nodes_.empty(); } size_t visited() const { return visited_; } double distance() const { return std::sqrt(best_dist_); } const point_type& nearest(const point_type& pt) { if (root_ == nullptr) throw std::logic_error("tree is empty"); best_ = nullptr; visited_ = 0; best_dist_ = 0; nearest(root_, pt, 0); return best_->point_; } }; void test_wikipedia() { typedef point<int, 2> point2d; typedef kdtree<int, 2> tree2d; point2d points[] = { { 2, 3 }, { 5, 4 }, { 9, 6 }, { 4, 7 }, { 8, 1 }, { 7, 2 } }; tree2d tree(std::begin(points), std::end(points)); point2d n = tree.nearest({ 9, 2 }); std::cout << "Wikipedia example data:\n"; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } typedef point<double, 3> point3d; typedef kdtree<double, 3> tree3d; struct random_point_generator { random_point_generator(double min, double max) : engine_(std::random_device()()), distribution_(min, max) {} point3d operator()() { double x = distribution_(engine_); double y = distribution_(engine_); double z = distribution_(engine_); return point3d({x, y, z}); } std::mt19937 engine_; std::uniform_real_distribution<double> distribution_; }; void test_random(size_t count) { random_point_generator rpg(0, 1); tree3d tree(rpg, count); point3d pt(rpg()); point3d n = tree.nearest(pt); std::cout << "Random data (" << count << " points):\n"; std::cout << "point: " << pt << '\n'; std::cout << "nearest point: " << n << '\n'; std::cout << "distance: " << tree.distance() << '\n'; std::cout << "nodes visited: " << tree.visited() << '\n'; } int main() { try { test_wikipedia(); std::cout << '\n'; test_random(1000); std::cout << '\n'; test_random(1000000); } catch (const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; }
Preserve the algorithm and functionality while converting the code from Java to C++.
public class ArrayCallback7 { interface IntConsumer { void run(int x); } interface IntToInt { int run(int x); } static void forEach(int[] arr, IntConsumer consumer) { for (int i : arr) { consumer.run(i); } } static void update(int[] arr, IntToInt mapper) { for (int i = 0; i < arr.length; i++) { arr[i] = mapper.run(arr[i]); } } public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); update(numbers, new IntToInt() { @Override public int run(int x) { return x * x; } }); forEach(numbers, new IntConsumer() { public void run(int x) { System.out.println(x); } }); } }
#include <iostream> #include <algorithm> void print_square(int i) { std::cout << i*i << " "; } int main() { int ary[]={1,2,3,4,5}; std::for_each(ary,ary+5,print_square); return 0; }
Produce a language-to-language conversion: from Java to C++, same semantics.
class Singleton { private static Singleton myInstance; public static Singleton getInstance() { if (myInstance == null) { synchronized(Singleton.class) { if (myInstance == null) { myInstance = new Singleton(); } } } return myInstance; } protected Singleton() { } }
#include <stdexcept> template <typename Self> class singleton { protected: static Self* sentry; public: static Self& instance() { return *sentry; } singleton() { if(sentry) throw std::logic_error("Error: attempt to instantiate a singleton over a pre-existing one!"); sentry = (Self*)this; } virtual ~singleton() { if(sentry == this) sentry = 0; } }; template <typename Self> Self* singleton<Self>::sentry = 0; #include <iostream> #include <string> using namespace std; class controller : public singleton<controller> { public: controller(string const& name) : name(name) { trace("begin"); } ~controller() { trace("end"); } void work() { trace("doing stuff"); } void trace(string const& message) { cout << name << ": " << message << endl; } string name; }; int main() { controller* first = new controller("first"); controller::instance().work(); delete first; controller second("second"); controller::instance().work(); try { controller goner("goner"); controller::instance().work(); } catch(exception const& error) { cout << error.what() << endl; } controller::instance().work(); controller goner("goner"); controller::instance().work(); }
Produce a functionally identical C++ code for the snippet given in Java.
public class SafeAddition { private static double stepDown(double d) { return Math.nextAfter(d, Double.NEGATIVE_INFINITY); } private static double stepUp(double d) { return Math.nextUp(d); } private static double[] safeAdd(double a, double b) { return new double[]{stepDown(a + b), stepUp(a + b)}; } public static void main(String[] args) { double a = 1.2; double b = 0.03; double[] result = safeAdd(a, b); System.out.printf("(%.2f + %.2f) is in the range %.16f..%.16f", a, b, result[0], result[1]); } }
#include <iostream> #include <tuple> union conv { int i; float f; }; float nextUp(float d) { if (isnan(d) || d == -INFINITY || d == INFINITY) return d; if (d == 0.0) return FLT_EPSILON; conv c; c.f = d; c.i++; return c.f; } float nextDown(float d) { if (isnan(d) || d == -INFINITY || d == INFINITY) return d; if (d == 0.0) return -FLT_EPSILON; conv c; c.f = d; c.i--; return c.f; } auto safeAdd(float a, float b) { return std::make_tuple(nextDown(a + b), nextUp(a + b)); } int main() { float a = 1.20f; float b = 0.03f; auto result = safeAdd(a, b); printf("(%f + %f) is in the range (%0.16f, %0.16f)\n", a, b, std::get<0>(result), std::get<1>(result)); return 0; }
Generate an equivalent C++ version of this Java code.
String dog = "Benjamin"; String Dog = "Samba"; String DOG = "Bernie"; @Inject Console console; console.print($"There are three dogs named {dog}, {Dog}, and {DOG}");
#include <iostream> #include <string> using namespace std; int main() { string dog = "Benjamin", Dog = "Samba", DOG = "Bernie"; cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl; }
Ensure the translated C++ code behaves exactly like the original Java snippet.
for (int i = 10; i >= 0; i--) { System.out.println(i); }
for(int i = 10; i >= 0; --i) std::cout << i << "\n";
Translate this program into C++ but keep the logic exactly as in Java.
import java.io.*; public class Test { public static void main(String[] args) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) { bw.write("abc"); } } }
#include <fstream> using namespace std; int main() { ofstream file("new.txt"); file << "this is a string"; file.close(); return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Java version.
for (Integer i = 0; i < 5; i++) { String line = ''; for (Integer j = 0; j < i; j++) { line += '*'; } System.debug(line); } List<String> lines = new List<String> { '*', '**', '***', '****', '*****' }; for (String line : lines) { System.debug(line); }
for(int i = 0; i < 5; ++i) { for(int j = 0; j < i; ++j) std::cout.put('*'); std::cout.put('\n'); }
Port the provided Java code into C++ while preserving the original functionality.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(15, 100)); System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(10, 1000)); } private static void displayMap(Map<Integer,List<Long>> map) { for ( int key = 1 ; key <= 9 ; key++ ) { System.out.println(key + " : " + map.get(key)); } } public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) { Map<Integer,List<Long>> map = new HashMap<>(); Map<Integer,Integer> mapCount = new HashMap<>(); for ( int i = 1 ; i <= 9 ; i++ ) { map.put(i, new ArrayList<>()); mapCount.put(i, 0); } boolean notPopulated = true; for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) { if ( isGapful(n) ) { int index = (int) (n % 10); if ( mapCount.get(index) < firstHowMany ) { map.get(index).add(n); mapCount.put(index, mapCount.get(index) + 1); if ( map.get(index).size() > countReturned ) { map.get(index).remove(0); } } boolean finished = true; for ( int i = 1 ; i <= 9 ; i++ ) { if ( mapCount.get(i) < firstHowMany ) { finished = false; break; } } if ( finished ) { notPopulated = false; } } } return map; } public static boolean isGapful(long n) { String s = Long.toString(n); return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0; } public static int length(long n) { int length = 0; while ( n > 0 ) { length += 1; n /= 10; } return length; } public static long nextPalindrome(long n) { int length = length(n); if ( length % 2 == 0 ) { length /= 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/10)); } return Long.parseLong(n + reverse(n)); } length = (length - 1) / 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/100)); } return Long.parseLong(n + reverse(n/10)); } private static boolean powerTen(long n) { while ( n > 9 && n % 10 == 0 ) { n /= 10; } return n == 1; } private static String reverse(long n) { return (new StringBuilder(n + "")).reverse().toString(); } }
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1), digit_(digit), even_(false) {} integer next_palindrome() { ++next_; if (next_ == power_ * (digit_ + 1)) { if (even_) power_ *= 10; next_ = digit_ * power_; even_ = !even_; } return next_ * (even_ ? 10 * power_ : power_) + reverse(even_ ? next_ : next_/10); } private: integer power_; integer next_; int digit_; bool even_; }; bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } template<size_t len> void print(integer (&array)[9][len]) { for (int digit = 1; digit < 10; ++digit) { std::cout << digit << ":"; for (int i = 0; i < len; ++i) std::cout << ' ' << array[digit - 1][i]; std::cout << '\n'; } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palindrome_generator pgen(digit); for (int i = 0; i < m2; ) { integer n = pgen.next_palindrome(); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n"; print(pg1); std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n"; print(pg2); std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n"; print(pg3); return 0; }
Write a version of this Java function in C++ with identical behavior.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(15, 100)); System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(10, 1000)); } private static void displayMap(Map<Integer,List<Long>> map) { for ( int key = 1 ; key <= 9 ; key++ ) { System.out.println(key + " : " + map.get(key)); } } public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) { Map<Integer,List<Long>> map = new HashMap<>(); Map<Integer,Integer> mapCount = new HashMap<>(); for ( int i = 1 ; i <= 9 ; i++ ) { map.put(i, new ArrayList<>()); mapCount.put(i, 0); } boolean notPopulated = true; for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) { if ( isGapful(n) ) { int index = (int) (n % 10); if ( mapCount.get(index) < firstHowMany ) { map.get(index).add(n); mapCount.put(index, mapCount.get(index) + 1); if ( map.get(index).size() > countReturned ) { map.get(index).remove(0); } } boolean finished = true; for ( int i = 1 ; i <= 9 ; i++ ) { if ( mapCount.get(i) < firstHowMany ) { finished = false; break; } } if ( finished ) { notPopulated = false; } } } return map; } public static boolean isGapful(long n) { String s = Long.toString(n); return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0; } public static int length(long n) { int length = 0; while ( n > 0 ) { length += 1; n /= 10; } return length; } public static long nextPalindrome(long n) { int length = length(n); if ( length % 2 == 0 ) { length /= 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/10)); } return Long.parseLong(n + reverse(n)); } length = (length - 1) / 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/100)); } return Long.parseLong(n + reverse(n/10)); } private static boolean powerTen(long n) { while ( n > 9 && n % 10 == 0 ) { n /= 10; } return n == 1; } private static String reverse(long n) { return (new StringBuilder(n + "")).reverse().toString(); } }
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1), digit_(digit), even_(false) {} integer next_palindrome() { ++next_; if (next_ == power_ * (digit_ + 1)) { if (even_) power_ *= 10; next_ = digit_ * power_; even_ = !even_; } return next_ * (even_ ? 10 * power_ : power_) + reverse(even_ ? next_ : next_/10); } private: integer power_; integer next_; int digit_; bool even_; }; bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } template<size_t len> void print(integer (&array)[9][len]) { for (int digit = 1; digit < 10; ++digit) { std::cout << digit << ":"; for (int i = 0; i < len; ++i) std::cout << ' ' << array[digit - 1][i]; std::cout << '\n'; } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palindrome_generator pgen(digit); for (int i = 0; i < m2; ) { integer n = pgen.next_palindrome(); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n"; print(pg1); std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n"; print(pg2); std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n"; print(pg3); return 0; }
Translate the given Java code snippet into C++ without altering its behavior.
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); } } final int level = i; JFrame frame = new JFrame("Sierpinsky Triangle - Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); } }; panel.setPreferredSize(new Dimension(400, 400)); frame.add(panel); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { if(level <= 0) return; g.drawLine(x, y, x+size, y); g.drawLine(x, y, x, y+size); g.drawLine(x+size, y, x, y+size); drawSierpinskyTriangle(level-1, x, y, size/2, g); drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); } }
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( 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( std::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 sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
Port the following code from Java to C++ with equivalent syntax and logic.
import javax.swing.*; import java.awt.*; class SierpinskyTriangle { public static void main(String[] args) { int i = 3; if(args.length >= 1) { try { i = Integer.parseInt(args[0]); } catch(NumberFormatException e) { System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); } } final int level = i; JFrame frame = new JFrame("Sierpinsky Triangle - Java"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel() { @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); } }; panel.setPreferredSize(new Dimension(400, 400)); frame.add(panel); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { if(level <= 0) return; g.drawLine(x, y, x+size, y); g.drawLine(x, y, x, y+size); g.drawLine(x+size, y, x, y+size); drawSierpinskyTriangle(level-1, x, y, size/2, g); drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); } }
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( 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( std::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 sierpinski { public: void draw( int o ) { colors[0] = 0xff0000; colors[1] = 0x00ff33; colors[2] = 0x0033ff; colors[3] = 0xffff00; colors[4] = 0x00ffff; colors[5] = 0xffffff; bmp.create( BMP_SIZE, BMP_SIZE ); HDC dc = bmp.getDC(); drawTri( dc, 0, 0, ( float )BMP_SIZE, ( float )BMP_SIZE, o / 2 ); bmp.setPenColor( colors[0] ); MoveToEx( dc, BMP_SIZE >> 1, 0, NULL ); LineTo( dc, 0, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE - 1, BMP_SIZE - 1 ); LineTo( dc, BMP_SIZE >> 1, 0 ); bmp.saveBitmap( "./st.bmp" ); } private: void drawTri( HDC dc, float l, float t, float r, float b, int i ) { float w = r - l, h = b - t, hh = h / 2.f, ww = w / 4.f; if( i ) { drawTri( dc, l + ww, t, l + ww * 3.f, t + hh, i - 1 ); drawTri( dc, l, t + hh, l + w / 2.f, t + h, i - 1 ); drawTri( dc, l + w / 2.f, t + hh, l + w, t + h, i - 1 ); } bmp.setPenColor( colors[i % 6] ); MoveToEx( dc, ( int )( l + ww ), ( int )( t + hh ), NULL ); LineTo ( dc, ( int )( l + ww * 3.f ), ( int )( t + hh ) ); LineTo ( dc, ( int )( l + ( w / 2.f ) ), ( int )( t + h ) ); LineTo ( dc, ( int )( l + ww ), ( int )( t + hh ) ); } myBitmap bmp; DWORD colors[6]; }; int main(int argc, char* argv[]) { sierpinski s; s.draw( 12 ); return 0; }
Please provide an equivalent version of this Java code in C++.
public class NonContinuousSubsequences { public static void main(String args[]) { seqR("1234", "", 0, 0); } private static void seqR(String s, String c, int i, int added) { if (i == s.length()) { if (c.trim().length() > added) System.out.println(c); } else { seqR(s, c + s.charAt(i), i + 1, added + 1); seqR(s, c + ' ', i + 1, added); } } }
class N{ uint n,i,g,e,l; public: N(uint n): n(n-1),i{},g{},e(1),l(n-1){} bool hasNext(){ g=(1<<n)+e;for(i=l;i<n;++i) g+=1<<i; if (l==2) {l=--n; e=1; return true;} if (e<((1<<(l-1))-1)) {++e; return true;} e=1; --l; return (l>0); } uint next() {return g;} };
Generate an equivalent C++ version of this Java code.
import java.awt.*; import javax.swing.*; public class FibonacciWordFractal extends JPanel { String wordFractal; FibonacciWordFractal(int n) { setPreferredSize(new Dimension(450, 620)); setBackground(Color.white); wordFractal = wordFractal(n); } public String wordFractal(int n) { if (n < 2) return n == 1 ? "1" : ""; StringBuilder f1 = new StringBuilder("1"); StringBuilder f2 = new StringBuilder("0"); for (n = n - 2; n > 0; n--) { String tmp = f2.toString(); f2.append(f1); f1.setLength(0); f1.append(tmp); } return f2.toString(); } void drawWordFractal(Graphics2D g, int x, int y, int dx, int dy) { for (int n = 0; n < wordFractal.length(); n++) { g.drawLine(x, y, x + dx, y + dy); x += dx; y += dy; if (wordFractal.charAt(n) == '0') { int tx = dx; dx = (n % 2 == 0) ? -dy : dy; dy = (n % 2 == 0) ? tx : -tx; } } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); drawWordFractal(g, 20, 20, 1, 0); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Fibonacci Word Fractal"); f.setResizable(false); f.add(new FibonacciWordFractal(23), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include <windows.h> #include <string> using namespace std; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, 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; clear(); return true; } void clear() { ZeroMemory( pBits, width * height * sizeof( DWORD ) ); } void setPenColor( DWORD clr ) { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, 1, clr ); SelectObject( hdc, pen ); } void saveBitmap( string path ) { BITMAPFILEHEADER fileheader; BITMAPINFO infoheader; BITMAP bitmap; DWORD* dwpBits; DWORD wb; HANDLE file; GetObject( bmp, sizeof( bitmap ), &bitmap ); 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 ); 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() { return hdc; } int getWidth() { return width; } int getHeight() { return height; } private: HBITMAP bmp; HDC hdc; HPEN pen; void *pBits; int width, height; }; class fiboFractal { public: fiboFractal( int l ) { bmp.create( 600, 440 ); bmp.setPenColor( 0x00ff00 ); createWord( l ); createFractal(); bmp.saveBitmap( "path_to_save_bitmap" ); } private: void createWord( int l ) { string a = "1", b = "0", c; l -= 2; while( l-- ) { c = b + a; a = b; b = c; } fWord = c; } void createFractal() { int n = 1, px = 10, dir, py = 420, len = 1, x = 0, y = -len, goingTo = 0; HDC dc = bmp.getDC(); MoveToEx( dc, px, py, NULL ); for( string::iterator si = fWord.begin(); si != fWord.end(); si++ ) { px += x; py += y; LineTo( dc, px, py ); if( !( *si - 48 ) ) { if( n & 1 ) dir = 1; else dir = 0; switch( goingTo ) { case 0: y = 0; if( dir ){ x = len; goingTo = 1; } else { x = -len; goingTo = 3; } break; case 1: x = 0; if( dir ) { y = len; goingTo = 2; } else { y = -len; goingTo = 0; } break; case 2: y = 0; if( dir ) { x = -len; goingTo = 3; } else { x = len; goingTo = 1; } break; case 3: x = 0; if( dir ) { y = -len; goingTo = 0; } else { y = len; goingTo = 2; } } } n++; } } string fWord; myBitmap bmp; }; int main( int argc, char* argv[] ) { fiboFractal ff( 23 ); return system( "pause" ); }
Translate this program into C++ but keep the logic exactly as in Java.
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){ BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE); if(x.add(BigInteger.TWO).compareTo(max) <= 0) { counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0; } } System.out.println(counter + " twin prime pairs."); } public static boolean findPrime(BigInteger x, BigInteger sqrtNum){ for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){ if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){ return false; } } return true; } }
#include <cstdint> #include <iostream> #include <string> #include <primesieve.hpp> void print_twin_prime_count(long long limit) { std::cout << "Number of twin prime pairs less than " << limit << " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n'; } int main(int argc, char** argv) { std::cout.imbue(std::locale("")); if (argc > 1) { for (int i = 1; i < argc; ++i) { try { print_twin_prime_count(std::stoll(argv[i])); } catch (const std::exception& ex) { std::cerr << "Cannot parse limit from '" << argv[i] << "'\n"; } } } else { uint64_t limit = 10; for (int power = 1; power < 12; ++power, limit *= 10) print_twin_prime_count(limit); } return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.Locale; public class Test { public static void main(String[] a) { for (int n = 2; n < 6; n++) unity(n); } public static void unity(int n) { System.out.printf("%n%d: ", n); for (double angle = 0; angle < 2 * Math.PI; angle += (2 * Math.PI) / n) { double real = Math.cos(angle); if (Math.abs(real) < 1.0E-3) real = 0.0; double imag = Math.sin(angle); if (Math.abs(imag) < 1.0E-3) imag = 0.0; System.out.printf(Locale.US, "(%9f,%9f) ", real, imag); } } }
#include <complex> #include <cmath> #include <iostream> double const pi = 4 * std::atan(1); int main() { for (int n = 2; n <= 10; ++n) { std::cout << n << ": "; for (int k = 0; k < n; ++k) std::cout << std::polar(1, 2*pi*k/n) << " "; std::cout << std::endl; } }
Write the same code in C++ as shown below in Java.
public class LongMult { private static byte[] stringToDigits(String num) { byte[] result = new byte[num.length()]; for (int i = 0; i < num.length(); i++) { char c = num.charAt(i); if (c < '0' || c > '9') { throw new IllegalArgumentException("Invalid digit " + c + " found at position " + i); } result[num.length() - 1 - i] = (byte) (c - '0'); } return result; } public static String longMult(String num1, String num2) { byte[] left = stringToDigits(num1); byte[] right = stringToDigits(num2); byte[] result = new byte[left.length + right.length]; for (int rightPos = 0; rightPos < right.length; rightPos++) { byte rightDigit = right[rightPos]; byte temp = 0; for (int leftPos = 0; leftPos < left.length; leftPos++) { temp += result[leftPos + rightPos]; temp += rightDigit * left[leftPos]; result[leftPos + rightPos] = (byte) (temp % 10); temp /= 10; } int destPos = rightPos + left.length; while (temp != 0) { temp += result[destPos] & 0xFFFFFFFFL; result[destPos] = (byte) (temp % 10); temp /= 10; destPos++; } } StringBuilder stringResultBuilder = new StringBuilder(result.length); for (int i = result.length - 1; i >= 0; i--) { byte digit = result[i]; if (digit != 0 || stringResultBuilder.length() > 0) { stringResultBuilder.append((char) (digit + '0')); } } return stringResultBuilder.toString(); } public static void main(String[] args) { System.out.println(longMult("18446744073709551616", "18446744073709551616")); } }
#include <iostream> #include <sstream> typedef long long bigInt; using namespace std; class number { public: number() { s = "0"; neg = false; } number( bigInt a ) { set( a ); } number( string a ) { set( a ); } void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); } void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); } number operator * ( const number& b ) { return this->mul( b ); } number& operator *= ( const number& b ) { *this = *this * b; return *this; } number& operator = ( const number& b ) { s = b.s; return *this; } friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; } friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; } private: number mul( const number& b ) { number a; bool neg = false; string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' ); int xx, ss, rr, t, c, stp = 0; string::reverse_iterator xi = bs.rbegin(), si, ri; for( ; xi != bs.rend(); xi++ ) { c = 0; ri = r.rbegin() + stp; for( si = s.rbegin(); si != s.rend(); si++ ) { xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48; ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10; ( *ri++ ) = t + 48; } if( c > 0 ) ( *ri ) = c + 48; stp++; } trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0; if( t & 1 ) a.s = "-" + r; else a.s = r; return a; } void trimLeft( string& r ) { if( r.length() < 2 ) return; for( string::iterator x = r.begin(); x != ( r.end() - 1 ); ) { if( ( *x ) != '0' ) return; x = r.erase( x ); } } void clearStr() { for( string::iterator x = s.begin(); x != s.end(); ) { if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x ); else x++; } } string s; bool neg; }; int main( int argc, char* argv[] ) { number a, b; a.set( "18446744073709551616" ); b.set( "18446744073709551616" ); cout << a * b << endl << endl; cout << "Factor 1 = "; cin >> a; cout << "Factor 2 = "; cin >> b; cout << "Product: = " << a * b << endl << endl; return system( "pause" ); }
Change the programming language of this snippet from Java to C++ without modifying what it does.
public class LongMult { private static byte[] stringToDigits(String num) { byte[] result = new byte[num.length()]; for (int i = 0; i < num.length(); i++) { char c = num.charAt(i); if (c < '0' || c > '9') { throw new IllegalArgumentException("Invalid digit " + c + " found at position " + i); } result[num.length() - 1 - i] = (byte) (c - '0'); } return result; } public static String longMult(String num1, String num2) { byte[] left = stringToDigits(num1); byte[] right = stringToDigits(num2); byte[] result = new byte[left.length + right.length]; for (int rightPos = 0; rightPos < right.length; rightPos++) { byte rightDigit = right[rightPos]; byte temp = 0; for (int leftPos = 0; leftPos < left.length; leftPos++) { temp += result[leftPos + rightPos]; temp += rightDigit * left[leftPos]; result[leftPos + rightPos] = (byte) (temp % 10); temp /= 10; } int destPos = rightPos + left.length; while (temp != 0) { temp += result[destPos] & 0xFFFFFFFFL; result[destPos] = (byte) (temp % 10); temp /= 10; destPos++; } } StringBuilder stringResultBuilder = new StringBuilder(result.length); for (int i = result.length - 1; i >= 0; i--) { byte digit = result[i]; if (digit != 0 || stringResultBuilder.length() > 0) { stringResultBuilder.append((char) (digit + '0')); } } return stringResultBuilder.toString(); } public static void main(String[] args) { System.out.println(longMult("18446744073709551616", "18446744073709551616")); } }
#include <iostream> #include <sstream> typedef long long bigInt; using namespace std; class number { public: number() { s = "0"; neg = false; } number( bigInt a ) { set( a ); } number( string a ) { set( a ); } void set( bigInt a ) { neg = false; if( a < 0 ) { a = -a; neg = true; } ostringstream o; o << a; s = o.str(); clearStr(); } void set( string a ) { neg = false; s = a; if( s.length() > 1 && s[0] == '-' ) { neg = true; } clearStr(); } number operator * ( const number& b ) { return this->mul( b ); } number& operator *= ( const number& b ) { *this = *this * b; return *this; } number& operator = ( const number& b ) { s = b.s; return *this; } friend ostream& operator << ( ostream& out, const number& a ) { if( a.neg ) out << "-"; out << a.s; return out; } friend istream& operator >> ( istream& in, number& a ){ string b; in >> b; a.set( b ); return in; } private: number mul( const number& b ) { number a; bool neg = false; string r, bs = b.s; r.resize( 2 * max( b.s.length(), s.length() ), '0' ); int xx, ss, rr, t, c, stp = 0; string::reverse_iterator xi = bs.rbegin(), si, ri; for( ; xi != bs.rend(); xi++ ) { c = 0; ri = r.rbegin() + stp; for( si = s.rbegin(); si != s.rend(); si++ ) { xx = ( *xi ) - 48; ss = ( *si ) - 48; rr = ( *ri ) - 48; ss = ss * xx + rr + c; t = ss % 10; c = ( ss - t ) / 10; ( *ri++ ) = t + 48; } if( c > 0 ) ( *ri ) = c + 48; stp++; } trimLeft( r ); t = b.neg ? 1 : 0; t += neg ? 1 : 0; if( t & 1 ) a.s = "-" + r; else a.s = r; return a; } void trimLeft( string& r ) { if( r.length() < 2 ) return; for( string::iterator x = r.begin(); x != ( r.end() - 1 ); ) { if( ( *x ) != '0' ) return; x = r.erase( x ); } } void clearStr() { for( string::iterator x = s.begin(); x != s.end(); ) { if( ( *x ) < '0' || ( *x ) > '9' ) x = s.erase( x ); else x++; } } string s; bool neg; }; int main( int argc, char* argv[] ) { number a, b; a.set( "18446744073709551616" ); b.set( "18446744073709551616" ); cout << a * b << endl << endl; cout << "Factor 1 = "; cin >> a; cout << "Factor 2 = "; cin >> b; cout << "Product: = " << a * b << endl << endl; return system( "pause" ); }
Translate this program into C++ but keep the logic exactly as in Java.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class PellsEquation { public static void main(String[] args) { NumberFormat format = NumberFormat.getInstance(); for ( int n : new int[] {61, 109, 181, 277, 8941} ) { BigInteger[] pell = pellsEquation(n); System.out.printf("x^2 - %3d * y^2 = 1 for:%n x = %s%n y = %s%n%n", n, format.format(pell[0]), format.format(pell[1])); } } private static final BigInteger[] pellsEquation(int n) { int a0 = (int) Math.sqrt(n); if ( a0*a0 == n ) { throw new IllegalArgumentException("ERROR 102: Invalid n = " + n); } List<Integer> continuedFrac = continuedFraction(n); int count = 0; BigInteger ajm2 = BigInteger.ONE; BigInteger ajm1 = new BigInteger(a0 + ""); BigInteger bjm2 = BigInteger.ZERO; BigInteger bjm1 = BigInteger.ONE; boolean stop = (continuedFrac.size() % 2 == 1); if ( continuedFrac.size() == 2 ) { stop = true; } while ( true ) { count++; BigInteger bn = new BigInteger(continuedFrac.get(count) + ""); BigInteger aj = bn.multiply(ajm1).add(ajm2); BigInteger bj = bn.multiply(bjm1).add(bjm2); if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) { return new BigInteger[] {aj, bj}; } else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) { stop = true; } if ( count == continuedFrac.size()-1 ) { count = 0; } ajm2 = ajm1; ajm1 = aj; bjm2 = bjm1; bjm1 = bj; } } private static final List<Integer> continuedFraction(int n) { List<Integer> answer = new ArrayList<Integer>(); int a0 = (int) Math.sqrt(n); answer.add(a0); int a = -a0; int aStart = a; int b = 1; int bStart = b; while ( true ) { int[] values = iterateFrac(n, a, b); answer.add(values[0]); a = values[1]; b = values[2]; if (a == aStart && b == bStart) break; } return answer; } private static final int[] iterateFrac(int n, int a, int b) { int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a)); int[] answer = new int[3]; answer[0] = x; answer[1] = -(b * a + x *(n - a * a)) / b; answer[2] = (n - a * a) / b; return answer; } }
#include <iomanip> #include <iostream> #include <tuple> std::tuple<uint64_t, uint64_t> solvePell(int n) { int x = (int)sqrt(n); if (x * x == n) { return std::make_pair(1, 0); } int y = x; int z = 1; int r = 2 * x; std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0); std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e)); f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f)); a = std::get<1>(e) + x * std::get<1>(f); b = std::get<1>(f); if (a * a - n * b * b == 1) { break; } } return std::make_pair(a, b); } void test(int n) { auto r = solvePell(n); std::cout << "x^2 - " << std::setw(3) << n << " * y^2 = 1 for x = " << std::setw(21) << std::get<0>(r) << " and y = " << std::setw(21) << std::get<1>(r) << '\n'; } int main() { test(61); test(109); test(181); test(277); return 0; }
Port the provided Java code into C++ while preserving the original functionality.
import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class PellsEquation { public static void main(String[] args) { NumberFormat format = NumberFormat.getInstance(); for ( int n : new int[] {61, 109, 181, 277, 8941} ) { BigInteger[] pell = pellsEquation(n); System.out.printf("x^2 - %3d * y^2 = 1 for:%n x = %s%n y = %s%n%n", n, format.format(pell[0]), format.format(pell[1])); } } private static final BigInteger[] pellsEquation(int n) { int a0 = (int) Math.sqrt(n); if ( a0*a0 == n ) { throw new IllegalArgumentException("ERROR 102: Invalid n = " + n); } List<Integer> continuedFrac = continuedFraction(n); int count = 0; BigInteger ajm2 = BigInteger.ONE; BigInteger ajm1 = new BigInteger(a0 + ""); BigInteger bjm2 = BigInteger.ZERO; BigInteger bjm1 = BigInteger.ONE; boolean stop = (continuedFrac.size() % 2 == 1); if ( continuedFrac.size() == 2 ) { stop = true; } while ( true ) { count++; BigInteger bn = new BigInteger(continuedFrac.get(count) + ""); BigInteger aj = bn.multiply(ajm1).add(ajm2); BigInteger bj = bn.multiply(bjm1).add(bjm2); if ( stop && (count == continuedFrac.size()-2 || continuedFrac.size() == 2) ) { return new BigInteger[] {aj, bj}; } else if (continuedFrac.size() % 2 == 0 && count == continuedFrac.size()-2 ) { stop = true; } if ( count == continuedFrac.size()-1 ) { count = 0; } ajm2 = ajm1; ajm1 = aj; bjm2 = bjm1; bjm1 = bj; } } private static final List<Integer> continuedFraction(int n) { List<Integer> answer = new ArrayList<Integer>(); int a0 = (int) Math.sqrt(n); answer.add(a0); int a = -a0; int aStart = a; int b = 1; int bStart = b; while ( true ) { int[] values = iterateFrac(n, a, b); answer.add(values[0]); a = values[1]; b = values[2]; if (a == aStart && b == bStart) break; } return answer; } private static final int[] iterateFrac(int n, int a, int b) { int x = (int) Math.floor((b * Math.sqrt(n) - b * a)/(n - a * a)); int[] answer = new int[3]; answer[0] = x; answer[1] = -(b * a + x *(n - a * a)) / b; answer[2] = (n - a * a) / b; return answer; } }
#include <iomanip> #include <iostream> #include <tuple> std::tuple<uint64_t, uint64_t> solvePell(int n) { int x = (int)sqrt(n); if (x * x == n) { return std::make_pair(1, 0); } int y = x; int z = 1; int r = 2 * x; std::tuple<uint64_t, uint64_t> e = std::make_pair(1, 0); std::tuple<uint64_t, uint64_t> f = std::make_pair(0, 1); uint64_t a = 0; uint64_t b = 0; while (true) { y = r * z - y; z = (n - y * y) / z; r = (x + y) / z; e = std::make_pair(std::get<1>(e), r * std::get<1>(e) + std::get<0>(e)); f = std::make_pair(std::get<1>(f), r * std::get<1>(f) + std::get<0>(f)); a = std::get<1>(e) + x * std::get<1>(f); b = std::get<1>(f); if (a * a - n * b * b == 1) { break; } } return std::make_pair(a, b); } void test(int n) { auto r = solvePell(n); std::cout << "x^2 - " << std::setw(3) << n << " * y^2 = 1 for x = " << std::setw(21) << std::get<0>(r) << " and y = " << std::setw(21) << std::get<1>(r) << '\n'; } int main() { test(61); test(109); test(181); test(277); return 0; }
Produce a functionally identical C++ code for the snippet given in Java.
import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; public class BullsAndCows{ public static void main(String[] args){ Random gen= new Random(); int target; while(hasDupes(target= (gen.nextInt(9000) + 1000))); String targetStr = target +""; boolean guessed = false; Scanner input = new Scanner(System.in); int guesses = 0; do{ int bulls = 0; int cows = 0; System.out.print("Guess a 4-digit number with no duplicate digits: "); int guess; try{ guess = input.nextInt(); if(hasDupes(guess) || guess < 1000) continue; }catch(InputMismatchException e){ continue; } guesses++; String guessStr = guess + ""; for(int i= 0;i < 4;i++){ if(guessStr.charAt(i) == targetStr.charAt(i)){ bulls++; }else if(targetStr.contains(guessStr.charAt(i)+"")){ cows++; } } if(bulls == 4){ guessed = true; }else{ System.out.println(cows+" Cows and "+bulls+" Bulls."); } }while(!guessed); System.out.println("You won after "+guesses+" guesses!"); } public static boolean hasDupes(int num){ boolean[] digs = new boolean[10]; while(num > 0){ if(digs[num%10]) return true; digs[num%10] = true; num/= 10; } return false; } }
#include <iostream> #include <string> #include <algorithm> #include <cstdlib> bool contains_duplicates(std::string s) { std::sort(s.begin(), s.end()); return std::adjacent_find(s.begin(), s.end()) != s.end(); } void game() { typedef std::string::size_type index; std::string symbols = "0123456789"; unsigned int const selection_length = 4; std::random_shuffle(symbols.begin(), symbols.end()); std::string selection = symbols.substr(0, selection_length); std::string guess; while (std::cout << "Your guess? ", std::getline(std::cin, guess)) { if (guess.length() != selection_length || guess.find_first_not_of(symbols) != std::string::npos || contains_duplicates(guess)) { std::cout << guess << " is not a valid guess!"; continue; } unsigned int bulls = 0; unsigned int cows = 0; for (index i = 0; i != selection_length; ++i) { index pos = selection.find(guess[i]); if (pos == i) ++bulls; else if (pos != std::string::npos) ++cows; } std::cout << bulls << " bulls, " << cows << " cows.\n"; if (bulls == selection_length) { std::cout << "Congratulations! You have won!\n"; return; } } std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n"; std::exit(EXIT_FAILURE); } int main() { std::cout << "Welcome to bulls and cows!\nDo you want to play? "; std::string answer; while (true) { while (true) { if (!std::getline(std::cin, answer)) { std::cout << "I can't get an answer. Exiting.\n"; return EXIT_FAILURE; } if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y") break; if (answer == "no" || answer == "No" || answer == "n" || answer == "N") { std::cout << "Ok. Goodbye.\n"; return EXIT_SUCCESS; } std::cout << "Please answer yes or no: "; } game(); std::cout << "Another game? "; } }
Generate an equivalent C++ version of this Java code.
import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; public class BullsAndCows{ public static void main(String[] args){ Random gen= new Random(); int target; while(hasDupes(target= (gen.nextInt(9000) + 1000))); String targetStr = target +""; boolean guessed = false; Scanner input = new Scanner(System.in); int guesses = 0; do{ int bulls = 0; int cows = 0; System.out.print("Guess a 4-digit number with no duplicate digits: "); int guess; try{ guess = input.nextInt(); if(hasDupes(guess) || guess < 1000) continue; }catch(InputMismatchException e){ continue; } guesses++; String guessStr = guess + ""; for(int i= 0;i < 4;i++){ if(guessStr.charAt(i) == targetStr.charAt(i)){ bulls++; }else if(targetStr.contains(guessStr.charAt(i)+"")){ cows++; } } if(bulls == 4){ guessed = true; }else{ System.out.println(cows+" Cows and "+bulls+" Bulls."); } }while(!guessed); System.out.println("You won after "+guesses+" guesses!"); } public static boolean hasDupes(int num){ boolean[] digs = new boolean[10]; while(num > 0){ if(digs[num%10]) return true; digs[num%10] = true; num/= 10; } return false; } }
#include <iostream> #include <string> #include <algorithm> #include <cstdlib> bool contains_duplicates(std::string s) { std::sort(s.begin(), s.end()); return std::adjacent_find(s.begin(), s.end()) != s.end(); } void game() { typedef std::string::size_type index; std::string symbols = "0123456789"; unsigned int const selection_length = 4; std::random_shuffle(symbols.begin(), symbols.end()); std::string selection = symbols.substr(0, selection_length); std::string guess; while (std::cout << "Your guess? ", std::getline(std::cin, guess)) { if (guess.length() != selection_length || guess.find_first_not_of(symbols) != std::string::npos || contains_duplicates(guess)) { std::cout << guess << " is not a valid guess!"; continue; } unsigned int bulls = 0; unsigned int cows = 0; for (index i = 0; i != selection_length; ++i) { index pos = selection.find(guess[i]); if (pos == i) ++bulls; else if (pos != std::string::npos) ++cows; } std::cout << bulls << " bulls, " << cows << " cows.\n"; if (bulls == selection_length) { std::cout << "Congratulations! You have won!\n"; return; } } std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n"; std::exit(EXIT_FAILURE); } int main() { std::cout << "Welcome to bulls and cows!\nDo you want to play? "; std::string answer; while (true) { while (true) { if (!std::getline(std::cin, answer)) { std::cout << "I can't get an answer. Exiting.\n"; return EXIT_FAILURE; } if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y") break; if (answer == "no" || answer == "No" || answer == "n" || answer == "N") { std::cout << "Ok. Goodbye.\n"; return EXIT_SUCCESS; } std::cout << "Please answer yes or no: "; } game(); std::cout << "Another game? "; } }
Maintain the same structure and functionality when rewriting this code in C++.
public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { boolean changed = false; do { changed = false; for (int a = 0; a < comparable.length - 1; a++) { if (comparable[a].compareTo(comparable[a + 1]) > 0) { E tmp = comparable[a]; comparable[a] = comparable[a + 1]; comparable[a + 1] = tmp; changed = true; } } } while (changed); }
#include <algorithm> #include <iostream> #include <iterator> template <typename RandomAccessIterator> void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) { bool swapped = true; while (begin != end-- && swapped) { swapped = false; for (auto i = begin; i != end; ++i) { if (*(i + 1) < *i) { std::iter_swap(i, i + 1); swapped = true; } } } } int main() { int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; bubble_sort(std::begin(a), std::end(a)); copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; }
Change the following Java code into C++ without altering its purpose.
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } unsigned int divisor_product(unsigned int n) { return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0)); } int main() { const unsigned int limit = 50; std::cout << "Product of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(11) << divisor_product(n); if (n % 5 == 0) std::cout << '\n'; } }
Translate this program into C++ but keep the logic exactly as in Java.
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } unsigned int divisor_product(unsigned int n) { return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0)); } int main() { const unsigned int limit = 50; std::cout << "Product of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(11) << divisor_product(n); if (n % 5 == 0) std::cout << '\n'; } }
Convert this Java snippet to C++ and keep its semantics consistent.
public class ProductOfDivisors { private static long divisorCount(long n) { long total = 1; for (; (n & 1) == 0; n >>= 1) { ++total; } for (long p = 3; p * p <= n; p += 2) { long count = 1; for (; n % p == 0; n /= p) { ++count; } total *= count; } if (n > 1) { total *= 2; } return total; } private static long divisorProduct(long n) { return (long) Math.pow(n, divisorCount(n) / 2.0); } public static void main(String[] args) { final long limit = 50; System.out.printf("Product of divisors for the first %d positive integers:%n", limit); for (long n = 1; n <= limit; n++) { System.out.printf("%11d", divisorProduct(n)); if (n % 5 == 0) { System.out.println(); } } } }
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } unsigned int divisor_product(unsigned int n) { return static_cast<unsigned int>(std::pow(n, divisor_count(n)/2.0)); } int main() { const unsigned int limit = 50; std::cout << "Product of divisors for the first " << limit << " positive integers:\n"; for (unsigned int n = 1; n <= limit; ++n) { std::cout << std::setw(11) << divisor_product(n); if (n % 5 == 0) std::cout << '\n'; } }
Ensure the translated C++ code behaves exactly like the original Java snippet.
import java.io.*; public class FileIODemo { public static void main(String[] args) { try { FileInputStream in = new FileInputStream("input.txt"); FileOutputStream out = new FileOutputStream("ouput.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } } }
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream input ( "input.txt" ); ofstream output ("output.txt"); if (output.is_open()) { if (input.is_open()){ while (getline (input,line)) { output << line << endl; } input.close(); } else { cout << "input.txt cannot be opened!\n"; } output.close(); } else { cout << "output.txt cannot be written to!\n"; } return 0; }
Convert the following code from Java to C++, ensuring the logic remains intact.
import java.util.Scanner; public class IntegerArithmetic { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int sum = a + b; int difference = a - b; int product = a * b; int division = a / b; int remainder = a % b; System.out.println("a + b = " + sum); System.out.println("a - b = " + difference); System.out.println("a * b = " + product); System.out.println("quotient of a / b = " + division); System.out.println("remainder of a / b = " + remainder); } }
#include <iostream> int main() { int a, b; std::cin >> a >> b; std::cout << "a+b = " << a+b << "\n"; std::cout << "a-b = " << a-b << "\n"; std::cout << "a*b = " << a*b << "\n"; std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n"; return 0; }
Translate this program into C++ but keep the logic exactly as in Java.
import java.util.Arrays; public class Transpose{ public static void main(String[] args){ double[][] m = {{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}, {5, 25, 125, 625}}; double[][] ans = new double[m[0].length][m.length]; for(int rows = 0; rows < m.length; rows++){ for(int cols = 0; cols < m[0].length; cols++){ ans[cols][rows] = m[rows][cols]; } } for(double[] i:ans){ System.out.println(Arrays.toString(i)); } } }
#include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> int main() { using namespace boost::numeric::ublas; matrix<double> m(3,3); for(int i=0; i!=m.size1(); ++i) for(int j=0; j!=m.size2(); ++j) m(i,j)=3*i+j; std::cout << trans(m) << std::endl; }
Write the same algorithm in C++ as shown in this Java implementation.
import java.util.function.DoubleSupplier; public class ManOrBoy { static double A(int k, DoubleSupplier x1, DoubleSupplier x2, DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) { DoubleSupplier B = new DoubleSupplier() { int m = k; public double getAsDouble() { return A(--m, this, x1, x2, x3, x4); } }; return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble(); } public static void main(String[] args) { System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0)); } }
#include <iostream> #include <tr1/memory> using std::tr1::shared_ptr; using std::tr1::enable_shared_from_this; struct Arg { virtual int run() = 0; virtual ~Arg() { }; }; int A(int, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>, shared_ptr<Arg>); class B : public Arg, public enable_shared_from_this<B> { private: int k; const shared_ptr<Arg> x1, x2, x3, x4; public: B(int _k, shared_ptr<Arg> _x1, shared_ptr<Arg> _x2, shared_ptr<Arg> _x3, shared_ptr<Arg> _x4) : k(_k), x1(_x1), x2(_x2), x3(_x3), x4(_x4) { } int run() { return A(--k, shared_from_this(), x1, x2, x3, x4); } }; class Const : public Arg { private: const int x; public: Const(int _x) : x(_x) { } int run () { return x; } }; int A(int k, shared_ptr<Arg> x1, shared_ptr<Arg> x2, shared_ptr<Arg> x3, shared_ptr<Arg> x4, shared_ptr<Arg> x5) { if (k <= 0) return x4->run() + x5->run(); else { shared_ptr<Arg> b(new B(k, x1, x2, x3, x4)); return b->run(); } } int main() { std::cout << A(10, shared_ptr<Arg>(new Const(1)), shared_ptr<Arg>(new Const(-1)), shared_ptr<Arg>(new Const(-1)), shared_ptr<Arg>(new Const(1)), shared_ptr<Arg>(new Const(0))) << std::endl; return 0; }
Port the following code from Java to C++ with equivalent syntax and logic.
module test { @Inject Console console; static Boolean show(String name, Boolean value) { console.print($"{name}()={value}"); return value; } void run() { val a = show("a", _); val b = show("b", _); for (Boolean v1 : False..True) { for (Boolean v2 : False..True) { console.print($"a({v1}) && b({v2}) == {a(v1) && b(v2)}"); console.print(); console.print($"a({v1}) || b({v2}) == {a(v1) || b(v2)}"); console.print(); } } } }
#include <iostream> bool a(bool in) { std::cout << "a" << std::endl; return in; } bool b(bool in) { std::cout << "b" << std::endl; return in; } void test(bool i, bool j) { std::cout << std::boolalpha << i << " and " << j << " = " << (a(i) && b(j)) << std::endl; std::cout << std::boolalpha << i << " or " << j << " = " << (a(i) || b(j)) << std::endl; } int main() { test(false, false); test(false, true); test(true, false); test(true, true); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
public class RecursionTest { private static void recurse(int i) { try { recurse(i+1); } catch (StackOverflowError e) { System.out.print("Recursion depth on this system is " + i + "."); } } public static void main(String[] args) { recurse(0); } }
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
Please provide an equivalent version of this Java code in C++.
public class RecursionTest { private static void recurse(int i) { try { recurse(i+1); } catch (StackOverflowError e) { System.out.print("Recursion depth on this system is " + i + "."); } } public static void main(String[] args) { recurse(0); } }
#include <iostream> void recurse(unsigned int i) { std::cout<<i<<"\n"; recurse(i+1); } int main() { recurse(0); }
Change the programming language of this snippet from Java to C++ without modifying what it does.
public class Test { static int mod(int n, int m) { return ((n % m) + m) % m; } static boolean isPrime(int n) { if (n == 2 || n == 3) return true; else if (n < 2 || n % 2 == 0 || n % 3 == 0) return false; for (int div = 5, inc = 2; Math.pow(div, 2) <= n; div += inc, inc = 6 - inc) if (n % div == 0) return false; return true; } public static void main(String[] args) { for (int p = 2; p < 62; p++) { if (!isPrime(p)) continue; for (int h3 = 2; h3 < p; h3++) { int g = h3 + p; for (int d = 1; d < g; d++) { if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3) continue; int q = 1 + (p - 1) * g / d; if (!isPrime(q)) continue; int r = 1 + (p * q / h3); if (!isPrime(r) || (q * r) % (p - 1) != 1) continue; System.out.printf("%d x %d x %d%n", p, q, r); } } } } }
#include <iomanip> #include <iostream> int mod(int n, int d) { return (d + n % d) % d; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; } void print_carmichael_numbers(int prime1) { for (int h3 = 1; h3 < prime1; ++h3) { for (int d = 1; d < h3 + prime1; ++d) { if (mod((h3 + prime1) * (prime1 - 1), d) != 0 || mod(-prime1 * prime1, h3) != mod(d, h3)) continue; int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d; if (!is_prime(prime2)) continue; int prime3 = 1 + prime1 * prime2/h3; if (!is_prime(prime3)) continue; if (mod(prime2 * prime3, prime1 - 1) != 1) continue; unsigned int c = prime1 * prime2 * prime3; std::cout << std::setw(2) << prime1 << " x " << std::setw(4) << prime2 << " x " << std::setw(5) << prime3 << " = " << std::setw(10) << c << '\n'; } } } int main() { for (int p = 2; p <= 61; ++p) { if (is_prime(p)) print_carmichael_numbers(p); } return 0; }
Port the following code from Java to C++ with equivalent syntax and logic.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.util.Arrays; import java.util.Random; import javax.swing.*; public class ImageNoise { int framecount = 0; int fps = 0; BufferedImage image; Kernel kernel; ConvolveOp cop; JFrame frame = new JFrame("Java Image Noise"); JPanel panel = new JPanel() { private int show_fps = 0; private MouseAdapter ma = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { show_fps = (show_fps + 1) % 3; } }; {addMouseListener(ma);} @Override public Dimension getPreferredSize() { return new Dimension(320, 240); } @Override @SuppressWarnings("fallthrough") public void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; drawNoise(); g.drawImage(image, 0, 0, null); switch (show_fps) { case 0: int xblur = getWidth() - 130, yblur = getHeight() - 32; BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32); BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(), BufferedImage.TYPE_BYTE_GRAY); cop.filter(bc, bs); g.drawImage(bs, xblur, yblur , null); case 1: g.setColor(Color.RED); g.setFont(new Font("Monospaced", Font.BOLD, 20)); g.drawString("FPS: " + fps, getWidth() - 120, getHeight() - 10); } framecount++; } }; Timer repainter = new Timer(1, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panel.repaint(); } }); Timer framerateChecker = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fps = framecount; framecount = 0; } }); public ImageNoise() { float[] vals = new float[121]; Arrays.fill(vals, 1/121f); kernel = new Kernel(11, 11, vals); cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); frame.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); repainter.start(); framerateChecker.start(); } void drawNoise() { int w = panel.getWidth(), h = panel.getHeight(); if (null == image || image.getWidth() != w || image.getHeight() != h) { image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); } Random rand = new Random(); int[] data = new int[w * h]; for (int x = 0; x < w * h / 32; x++) { int r = rand.nextInt(); for (int i = 0; i < 32; i++) { data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE; r >>>= 1; } } image.getRaster().setPixels(0, 0, w, h, data); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ImageNoise i = new ImageNoise(); } }); } }
#include <windows.h> #include <sstream> #include <tchar.h> using namespace std; const unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0; 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; } void* getBits( void ) const { return pBits; } 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 bmpNoise { public: bmpNoise() { QueryPerformanceFrequency( &_frequency ); _bmp.create( BMP_WID, BMP_HEI ); _frameTime = _fps = 0; _start = getTime(); _frames = 0; } void mainLoop() { float now = getTime(); if( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; } HDC wdc, dc = _bmp.getDC(); unsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() ); for( int y = 0; y < BMP_HEI; y++ ) { for( int x = 0; x < BMP_WID; x++ ) { if( rand() % 10 < 5 ) memset( bits, 255, 3 ); else memset( bits, 0, 3 ); bits++; } } ostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() ); wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); _frames++; _frameTime = getTime() - now; if( _frameTime > 1.0f ) _frameTime = 1.0f; } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: float getTime() { LARGE_INTEGER liTime; QueryPerformanceCounter( &liTime ); return liTime.QuadPart / ( float )_frequency.QuadPart; } myBitmap _bmp; HWND _hwnd; float _start, _fps, _frameTime; unsigned int _frames; LARGE_INTEGER _frequency; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _noise.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { _noise.mainLoop(); } } return UnregisterClass( "_MY_NOISE_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_NOISE_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_WID, BMP_HEI }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_NOISE_", ".: Noise image -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; bmpNoise _noise; }; wnd* wnd::_inst = 0; int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
Ensure the translated C++ code behaves exactly like the original Java snippet.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.util.Arrays; import java.util.Random; import javax.swing.*; public class ImageNoise { int framecount = 0; int fps = 0; BufferedImage image; Kernel kernel; ConvolveOp cop; JFrame frame = new JFrame("Java Image Noise"); JPanel panel = new JPanel() { private int show_fps = 0; private MouseAdapter ma = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { show_fps = (show_fps + 1) % 3; } }; {addMouseListener(ma);} @Override public Dimension getPreferredSize() { return new Dimension(320, 240); } @Override @SuppressWarnings("fallthrough") public void paintComponent(Graphics g1) { Graphics2D g = (Graphics2D) g1; drawNoise(); g.drawImage(image, 0, 0, null); switch (show_fps) { case 0: int xblur = getWidth() - 130, yblur = getHeight() - 32; BufferedImage bc = image.getSubimage(xblur, yblur, 115, 32); BufferedImage bs = new BufferedImage(bc.getWidth(), bc.getHeight(), BufferedImage.TYPE_BYTE_GRAY); cop.filter(bc, bs); g.drawImage(bs, xblur, yblur , null); case 1: g.setColor(Color.RED); g.setFont(new Font("Monospaced", Font.BOLD, 20)); g.drawString("FPS: " + fps, getWidth() - 120, getHeight() - 10); } framecount++; } }; Timer repainter = new Timer(1, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panel.repaint(); } }); Timer framerateChecker = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fps = framecount; framecount = 0; } }); public ImageNoise() { float[] vals = new float[121]; Arrays.fill(vals, 1/121f); kernel = new Kernel(11, 11, vals); cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); frame.add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); repainter.start(); framerateChecker.start(); } void drawNoise() { int w = panel.getWidth(), h = panel.getHeight(); if (null == image || image.getWidth() != w || image.getHeight() != h) { image = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); } Random rand = new Random(); int[] data = new int[w * h]; for (int x = 0; x < w * h / 32; x++) { int r = rand.nextInt(); for (int i = 0; i < 32; i++) { data[x * 32 + i] = (r & 1) * Integer.MAX_VALUE; r >>>= 1; } } image.getRaster().setPixels(0, 0, w, h, data); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ImageNoise i = new ImageNoise(); } }); } }
#include <windows.h> #include <sstream> #include <tchar.h> using namespace std; const unsigned int BMP_WID = 320, BMP_HEI = 240, WHITE = 16777215, BLACK = 0; 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; } void* getBits( void ) const { return pBits; } 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 bmpNoise { public: bmpNoise() { QueryPerformanceFrequency( &_frequency ); _bmp.create( BMP_WID, BMP_HEI ); _frameTime = _fps = 0; _start = getTime(); _frames = 0; } void mainLoop() { float now = getTime(); if( now - _start > 1.0f ) { _fps = static_cast<float>( _frames ) / ( now - _start ); _start = now; _frames = 0; } HDC wdc, dc = _bmp.getDC(); unsigned int* bits = reinterpret_cast<unsigned int*>( _bmp.getBits() ); for( int y = 0; y < BMP_HEI; y++ ) { for( int x = 0; x < BMP_WID; x++ ) { if( rand() % 10 < 5 ) memset( bits, 255, 3 ); else memset( bits, 0, 3 ); bits++; } } ostringstream o; o << _fps; TextOut( dc, 0, 0, o.str().c_str(), o.str().size() ); wdc = GetDC( _hwnd ); BitBlt( wdc, 0, 0, BMP_WID, BMP_HEI, dc, 0, 0, SRCCOPY ); ReleaseDC( _hwnd, wdc ); _frames++; _frameTime = getTime() - now; if( _frameTime > 1.0f ) _frameTime = 1.0f; } void setHWND( HWND hwnd ) { _hwnd = hwnd; } private: float getTime() { LARGE_INTEGER liTime; QueryPerformanceCounter( &liTime ); return liTime.QuadPart / ( float )_frequency.QuadPart; } myBitmap _bmp; HWND _hwnd; float _start, _fps, _frameTime; unsigned int _frames; LARGE_INTEGER _frequency; }; class wnd { public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _noise.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { _noise.mainLoop(); } } return UnregisterClass( "_MY_NOISE_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return DefWindowProc( hWnd, msg, wParam, lParam ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_MY_NOISE_"; RegisterClassEx( &wcex ); RECT rc = { 0, 0, BMP_WID, BMP_HEI }; AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); int w = rc.right - rc.left, h = rc.bottom - rc.top; return CreateWindow( "_MY_NOISE_", ".: Noise image -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; bmpNoise _noise; }; wnd* wnd::_inst = 0; int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
Write the same code in C++ as shown below in Java.
public static boolean perf(int n){ int sum= 0; for(int i= 1;i < n;i++){ if(n % i == 0){ sum+= i; } } return sum == n; }
#include <iostream> using namespace std ; int divisor_sum( int number ) { int sum = 0 ; for ( int i = 1 ; i < number ; i++ ) if ( number % i == 0 ) sum += i ; return sum; } int main( ) { cout << "Perfect numbers from 1 to 33550337:\n" ; for ( int num = 1 ; num < 33550337 ; num++ ) { if (divisor_sum(num) == num) cout << num << '\n' ; } return 0 ; }
Port the provided Java code into C++ while preserving the original functionality.
public class BeadSort { public static void main(String[] args) { BeadSort now=new BeadSort(); int[] arr=new int[(int)(Math.random()*11)+5]; for(int i=0;i<arr.length;i++) arr[i]=(int)(Math.random()*10); System.out.print("Unsorted: "); now.display1D(arr); int[] sort=now.beadSort(arr); System.out.print("Sorted: "); now.display1D(sort); } int[] beadSort(int[] arr) { int max=a[0]; for(int i=1;i<arr.length;i++) if(arr[i]>max) max=arr[i]; char[][] grid=new char[arr.length][max]; int[] levelcount=new int[max]; for(int i=0;i<max;i++) { levelcount[i]=0; for(int j=0;j<arr.length;j++) grid[j][i]='_'; } for(int i=0;i<arr.length;i++) { int num=arr[i]; for(int j=0;num>0;j++) { grid[levelcount[j]++][j]='*'; num--; } } System.out.println(); display2D(grid); int[] sorted=new int[arr.length]; for(int i=0;i<arr.length;i++) { int putt=0; for(int j=0;j<max&&grid[arr.length-1-i][j]=='*';j++) putt++; sorted[i]=putt; } return sorted; } void display1D(int[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display1D(char[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } void display2D(char[][] arr) { for(int i=0;i<arr.length;i++) display1D(arr[i]); System.out.println(); } }
#include <iostream> #include <vector> using std::cout; using std::vector; void distribute(int dist, vector<int> &List) { if (dist > List.size() ) List.resize(dist); for (int i=0; i < dist; i++) List[i]++; } vector<int> beadSort(int *myints, int n) { vector<int> list, list2, fifth (myints, myints + n); cout << "#1 Beads falling down: "; for (int i=0; i < fifth.size(); i++) distribute (fifth[i], list); cout << '\n'; cout << "\nBeads on their sides: "; for (int i=0; i < list.size(); i++) cout << " " << list[i]; cout << '\n'; cout << "#2 Beads right side up: "; for (int i=0; i < list.size(); i++) distribute (list[i], list2); cout << '\n'; return list2; } int main() { int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1}; vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int)); cout << "Sorted list/array: "; for(unsigned int i=0; i<sorted.size(); i++) cout << sorted[i] << ' '; }
Convert this Java block to C++, preserving its control flow and logic.
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arrays.fill(row, ' '); row[5] = 'x'; } } private void horizontal(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } private void vertical(int r1, int r2, int c) { for (int r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } private void diagd(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } private void diagu(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } private void draw(int v) { var thousands = v / 1000; v %= 1000; var hundreds = v / 100; v %= 100; var tens = v / 10; var ones = v % 10; drawPart(1000 * thousands); drawPart(100 * hundreds); drawPart(10 * tens); drawPart(ones); } private void drawPart(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawPart(1); drawPart(4); break; case 6: vertical(0, 4, 10); break; case 7: drawPart(1); drawPart(6); break; case 8: drawPart(2); drawPart(6); break; case 9: drawPart(1); drawPart(8); break; case 10: horizontal(0, 4, 0); break; case 20: horizontal(0, 4, 4); break; case 30: diagu(0, 4, 4); break; case 40: diagd(0, 4, 0); break; case 50: drawPart(10); drawPart(40); break; case 60: vertical(0, 4, 0); break; case 70: drawPart(10); drawPart(60); break; case 80: drawPart(20); drawPart(60); break; case 90: drawPart(10); drawPart(80); break; case 100: horizontal(6, 10, 14); break; case 200: horizontal(6, 10, 10); break; case 300: diagu(6, 10, 14); break; case 400: diagd(6, 10, 10); break; case 500: drawPart(100); drawPart(400); break; case 600: vertical(10, 14, 10); break; case 700: drawPart(100); drawPart(600); break; case 800: drawPart(200); drawPart(600); break; case 900: drawPart(100); drawPart(800); break; case 1000: horizontal(0, 4, 14); break; case 2000: horizontal(0, 4, 10); break; case 3000: diagd(0, 4, 10); break; case 4000: diagu(0, 4, 14); break; case 5000: drawPart(1000); drawPart(4000); break; case 6000: vertical(10, 14, 0); break; case 7000: drawPart(1000); drawPart(6000); break; case 8000: drawPart(2000); drawPart(6000); break; case 9000: drawPart(1000); drawPart(8000); break; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (var row : canvas) { builder.append(row); builder.append('\n'); } return builder.toString(); } public static void main(String[] args) { for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) { System.out.printf("%d:\n", number); var c = new Cistercian(number); System.out.println(c); } } }
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); draw(v); } friend std::ostream &operator<<(std::ostream &, const Cistercian &); private: FixedSquareGrid<char, 15> canvas; void initN() { for (auto &row : canvas) { row.fill(' '); row[5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { for (size_t r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } }; std::ostream &operator<<(std::ostream &os, const Cistercian &c) { for (auto &row : c.canvas) { for (auto cell : row) { os << cell; } os << '\n'; } return os; } int main() { for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) { std::cout << number << ":\n"; Cistercian c(number); std::cout << c << '\n'; } return 0; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arrays.fill(row, ' '); row[5] = 'x'; } } private void horizontal(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } private void vertical(int r1, int r2, int c) { for (int r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } private void diagd(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } private void diagu(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } private void draw(int v) { var thousands = v / 1000; v %= 1000; var hundreds = v / 100; v %= 100; var tens = v / 10; var ones = v % 10; drawPart(1000 * thousands); drawPart(100 * hundreds); drawPart(10 * tens); drawPart(ones); } private void drawPart(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawPart(1); drawPart(4); break; case 6: vertical(0, 4, 10); break; case 7: drawPart(1); drawPart(6); break; case 8: drawPart(2); drawPart(6); break; case 9: drawPart(1); drawPart(8); break; case 10: horizontal(0, 4, 0); break; case 20: horizontal(0, 4, 4); break; case 30: diagu(0, 4, 4); break; case 40: diagd(0, 4, 0); break; case 50: drawPart(10); drawPart(40); break; case 60: vertical(0, 4, 0); break; case 70: drawPart(10); drawPart(60); break; case 80: drawPart(20); drawPart(60); break; case 90: drawPart(10); drawPart(80); break; case 100: horizontal(6, 10, 14); break; case 200: horizontal(6, 10, 10); break; case 300: diagu(6, 10, 14); break; case 400: diagd(6, 10, 10); break; case 500: drawPart(100); drawPart(400); break; case 600: vertical(10, 14, 10); break; case 700: drawPart(100); drawPart(600); break; case 800: drawPart(200); drawPart(600); break; case 900: drawPart(100); drawPart(800); break; case 1000: horizontal(0, 4, 14); break; case 2000: horizontal(0, 4, 10); break; case 3000: diagd(0, 4, 10); break; case 4000: diagu(0, 4, 14); break; case 5000: drawPart(1000); drawPart(4000); break; case 6000: vertical(10, 14, 0); break; case 7000: drawPart(1000); drawPart(6000); break; case 8000: drawPart(2000); drawPart(6000); break; case 9000: drawPart(1000); drawPart(8000); break; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (var row : canvas) { builder.append(row); builder.append('\n'); } return builder.toString(); } public static void main(String[] args) { for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) { System.out.printf("%d:\n", number); var c = new Cistercian(number); System.out.println(c); } } }
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); draw(v); } friend std::ostream &operator<<(std::ostream &, const Cistercian &); private: FixedSquareGrid<char, 15> canvas; void initN() { for (auto &row : canvas) { row.fill(' '); row[5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { for (size_t r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } }; std::ostream &operator<<(std::ostream &os, const Cistercian &c) { for (auto &row : c.canvas) { for (auto cell : row) { os << cell; } os << '\n'; } return os; } int main() { for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) { std::cout << number << ":\n"; Cistercian c(number); std::cout << c << '\n'; } return 0; }
Change the programming language of this snippet from Java to C++ without modifying what it does.
import java.util.Arrays; import java.util.List; public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE]; public Cistercian(int n) { initN(); draw(n); } public void initN() { for (var row : canvas) { Arrays.fill(row, ' '); row[5] = 'x'; } } private void horizontal(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } private void vertical(int r1, int r2, int c) { for (int r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } private void diagd(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } private void diagu(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } private void draw(int v) { var thousands = v / 1000; v %= 1000; var hundreds = v / 100; v %= 100; var tens = v / 10; var ones = v % 10; drawPart(1000 * thousands); drawPart(100 * hundreds); drawPart(10 * tens); drawPart(ones); } private void drawPart(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawPart(1); drawPart(4); break; case 6: vertical(0, 4, 10); break; case 7: drawPart(1); drawPart(6); break; case 8: drawPart(2); drawPart(6); break; case 9: drawPart(1); drawPart(8); break; case 10: horizontal(0, 4, 0); break; case 20: horizontal(0, 4, 4); break; case 30: diagu(0, 4, 4); break; case 40: diagd(0, 4, 0); break; case 50: drawPart(10); drawPart(40); break; case 60: vertical(0, 4, 0); break; case 70: drawPart(10); drawPart(60); break; case 80: drawPart(20); drawPart(60); break; case 90: drawPart(10); drawPart(80); break; case 100: horizontal(6, 10, 14); break; case 200: horizontal(6, 10, 10); break; case 300: diagu(6, 10, 14); break; case 400: diagd(6, 10, 10); break; case 500: drawPart(100); drawPart(400); break; case 600: vertical(10, 14, 10); break; case 700: drawPart(100); drawPart(600); break; case 800: drawPart(200); drawPart(600); break; case 900: drawPart(100); drawPart(800); break; case 1000: horizontal(0, 4, 14); break; case 2000: horizontal(0, 4, 10); break; case 3000: diagd(0, 4, 10); break; case 4000: diagu(0, 4, 14); break; case 5000: drawPart(1000); drawPart(4000); break; case 6000: vertical(10, 14, 0); break; case 7000: drawPart(1000); drawPart(6000); break; case 8000: drawPart(2000); drawPart(6000); break; case 9000: drawPart(1000); drawPart(8000); break; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (var row : canvas) { builder.append(row); builder.append('\n'); } return builder.toString(); } public static void main(String[] args) { for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) { System.out.printf("%d:\n", number); var c = new Cistercian(number); System.out.println(c); } } }
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); draw(v); } friend std::ostream &operator<<(std::ostream &, const Cistercian &); private: FixedSquareGrid<char, 15> canvas; void initN() { for (auto &row : canvas) { row.fill(' '); row[5] = 'x'; } } void horizontal(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } } void vertical(size_t r1, size_t r2, size_t c) { for (size_t r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } } void diagd(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } } void diagu(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } } void drawOnes(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } } void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } } void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } } void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } } void draw(int v) { int thousands = v / 1000; v %= 1000; int hundreds = v / 100; v %= 100; int tens = v / 10; int ones = v % 10; if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } }; std::ostream &operator<<(std::ostream &os, const Cistercian &c) { for (auto &row : c.canvas) { for (auto cell : row) { os << cell; } os << '\n'; } return os; } int main() { for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) { std::cout << number << ":\n"; Cistercian c(number); std::cout << c << '\n'; } return 0; }
Translate this program into C++ but keep the logic exactly as in Java.
import java.math.BigInteger; class IntegerPower { public static void main(String[] args) { BigInteger power = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValueExact()).intValueExact()); String str = power.toString(); int len = str.length(); System.out.printf("5**4**3**2 = %s...%s and has %d digits%n", str.substring(0, 20), str.substring(len - 20), len); } }
#include <iostream> #include <boost/multiprecision/gmp.hpp> #include <string> namespace mp = boost::multiprecision; int main(int argc, char const *argv[]) { uint64_t tmpres = mp::pow(mp::mpz_int(4) , mp::pow(mp::mpz_int(3) , 2).convert_to<uint64_t>() ).convert_to<uint64_t>(); mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres); std::string s = res.str(); std::cout << s.substr(0, 20) << "..." << s.substr(s.length() - 20, 20) << std::endl; return 0; }
Convert the following code from Java to C++, ensuring the logic remains intact.
using System; namespace Sphere { internal class Program { private const string Shades = ".:!*oe%&#@"; private static readonly double[] Light = {30, 30, -50}; private static void Normalize(double[] v) { double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } private static double Dot(double[] x, double[] y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } public static void DrawSphere(double r, double k, double ambient) { var vec = new double[3]; for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) { double x = i + .5; for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) { double y = j/2.0 + .5; if(x*x + y*y <= r*r) { vec[0] = x; vec[1] = y; vec[2] = Math.Sqrt(r*r - x*x - y*y); Normalize(vec); double b = Math.Pow(Dot(Light, vec), k) + ambient; int intensity = (b <= 0) ? Shades.Length - 2 : (int)Math.Max((1 - b)*(Shades.Length - 1), 0); Console.Write(Shades[intensity]); } else Console.Write(' '); } Console.WriteLine(); } } private static void Main() { Normalize(Light); DrawSphere(6, 4, .1); DrawSphere(10, 2, .4); Console.ReadKey(); } } }
#include <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
Transform the following Java implementation into C++, maintaining the same output and logic.
using System; namespace Sphere { internal class Program { private const string Shades = ".:!*oe%&#@"; private static readonly double[] Light = {30, 30, -50}; private static void Normalize(double[] v) { double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } private static double Dot(double[] x, double[] y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } public static void DrawSphere(double r, double k, double ambient) { var vec = new double[3]; for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) { double x = i + .5; for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) { double y = j/2.0 + .5; if(x*x + y*y <= r*r) { vec[0] = x; vec[1] = y; vec[2] = Math.Sqrt(r*r - x*x - y*y); Normalize(vec); double b = Math.Pow(Dot(Light, vec), k) + ambient; int intensity = (b <= 0) ? Shades.Length - 2 : (int)Math.Max((1 - b)*(Shades.Length - 1), 0); Console.Write(Shades[intensity]); } else Console.Write(' '); } Console.WriteLine(); } } private static void Main() { Normalize(Light); DrawSphere(6, 4, .1); DrawSphere(10, 2, .4); Console.ReadKey(); } } }
#include <QImage> #include <QPainter> int main() { const QColor black(0, 0, 0); const QColor white(255, 255, 255); const int size = 300; const double diameter = 0.6 * size; QImage image(size, size, QImage::Format_RGB32); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); QLinearGradient linearGradient(0, 0, 0, size); linearGradient.setColorAt(0, white); linearGradient.setColorAt(1, black); QBrush brush(linearGradient); painter.fillRect(QRect(0, 0, size, size), brush); QPointF point1(0.4 * size, 0.4 * size); QPointF point2(0.45 * size, 0.4 * size); QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1); radialGradient.setColorAt(0, white); radialGradient.setColorAt(1, black); QBrush brush2(radialGradient); painter.setPen(Qt::NoPen); painter.setBrush(brush2); painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter)); image.save("sphere.png"); return 0; }
Convert the following code from Java to C++, ensuring the logic remains intact.
package org.rosettacode; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class InvertedIndex { List<String> stopwords = Arrays.asList("a", "able", "about", "across", "after", "all", "almost", "also", "am", "among", "an", "and", "any", "are", "as", "at", "be", "because", "been", "but", "by", "can", "cannot", "could", "dear", "did", "do", "does", "either", "else", "ever", "every", "for", "from", "get", "got", "had", "has", "have", "he", "her", "hers", "him", "his", "how", "however", "i", "if", "in", "into", "is", "it", "its", "just", "least", "let", "like", "likely", "may", "me", "might", "most", "must", "my", "neither", "no", "nor", "not", "of", "off", "often", "on", "only", "or", "other", "our", "own", "rather", "said", "say", "says", "she", "should", "since", "so", "some", "than", "that", "the", "their", "them", "then", "there", "these", "they", "this", "tis", "to", "too", "twas", "us", "wants", "was", "we", "were", "what", "when", "where", "which", "while", "who", "whom", "why", "will", "with", "would", "yet", "you", "your"); Map<String, List<Tuple>> index = new HashMap<String, List<Tuple>>(); List<String> files = new ArrayList<String>(); public void indexFile(File file) throws IOException { int fileno = files.indexOf(file.getPath()); if (fileno == -1) { files.add(file.getPath()); fileno = files.size() - 1; } int pos = 0; BufferedReader reader = new BufferedReader(new FileReader(file)); for (String line = reader.readLine(); line != null; line = reader .readLine()) { for (String _word : line.split("\\W+")) { String word = _word.toLowerCase(); pos++; if (stopwords.contains(word)) continue; List<Tuple> idx = index.get(word); if (idx == null) { idx = new LinkedList<Tuple>(); index.put(word, idx); } idx.add(new Tuple(fileno, pos)); } } System.out.println("indexed " + file.getPath() + " " + pos + " words"); } public void search(List<String> words) { for (String _word : words) { Set<String> answer = new HashSet<String>(); String word = _word.toLowerCase(); List<Tuple> idx = index.get(word); if (idx != null) { for (Tuple t : idx) { answer.add(files.get(t.fileno)); } } System.out.print(word); for (String f : answer) { System.out.print(" " + f); } System.out.println(""); } } public static void main(String[] args) { try { InvertedIndex idx = new InvertedIndex(); for (int i = 1; i < args.length; i++) { idx.indexFile(new File(args[i])); } idx.search(Arrays.asList(args[0].split(","))); } catch (Exception e) { e.printStackTrace(); } } private class Tuple { private int fileno; private int position; public Tuple(int fileno, int position) { this.fileno = fileno; this.position = position; } } }
#include <algorithm> #include <fstream> #include <iostream> #include <vector> #include <string> const std::string _CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.:-_/"; const size_t MAX_NODES = 41; class node { public: node() { clear(); } node( char z ) { clear(); } ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; } void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; } bool isWord; std::vector<std::string> files; node* next[MAX_NODES]; }; class index { public: void add( std::string s, std::string fileName ) { std::transform( s.begin(), s.end(), s.begin(), tolower ); std::string h; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { if( *i == 32 ) { pushFileName( addWord( h ), fileName ); h.clear(); continue; } h.append( 1, *i ); } if( h.length() ) pushFileName( addWord( h ), fileName ); } void findWord( std::string s ) { std::vector<std::string> v = find( s ); if( !v.size() ) { std::cout << s + " was not found!\n"; return; } std::cout << s << " found in:\n"; for( std::vector<std::string>::iterator i = v.begin(); i != v.end(); i++ ) { std::cout << *i << "\n"; } std::cout << "\n"; } private: void pushFileName( node* n, std::string fn ) { std::vector<std::string>::iterator i = std::find( n->files.begin(), n->files.end(), fn ); if( i == n->files.end() ) n->files.push_back( fn ); } const std::vector<std::string>& find( std::string s ) { size_t idx; std::transform( s.begin(), s.end(), s.begin(), tolower ); node* rt = &root; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { idx = _CHARS.find( *i ); if( idx < MAX_NODES ) { if( !rt->next[idx] ) return std::vector<std::string>(); rt = rt->next[idx]; } } if( rt->isWord ) return rt->files; return std::vector<std::string>(); } node* addWord( std::string s ) { size_t idx; node* rt = &root, *n; for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { idx = _CHARS.find( *i ); if( idx < MAX_NODES ) { n = rt->next[idx]; if( n ){ rt = n; continue; } n = new node( *i ); rt->next[idx] = n; rt = n; } } rt->isWord = true; return rt; } node root; }; int main( int argc, char* argv[] ) { index t; std::string s; std::string files[] = { "file1.txt", "f_text.txt", "text_1b.txt" }; for( int x = 0; x < 3; x++ ) { std::ifstream f; f.open( files[x].c_str(), std::ios::in ); if( f.good() ) { while( !f.eof() ) { f >> s; t.add( s, files[x] ); s.clear(); } f.close(); } } while( true ) { std::cout << "Enter one word to search for, return to exit: "; std::getline( std::cin, s ); if( !s.length() ) break; t.findWord( s ); } return 0; }
Produce a functionally identical C++ code for the snippet given in Java.
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.util.Scanner; public class LCM{ public static void main(String[] args){ Scanner aScanner = new Scanner(System.in); System.out.print("Enter the value of m:"); int m = aScanner.nextInt(); System.out.print("Enter the value of n:"); int n = aScanner.nextInt(); int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0); if (lcm == 0) { int mm = m, nn = n; while (mm != nn) { while (mm < nn) { mm += m; } while (nn < mm) { nn += n; } } lcm = mm; } System.out.println("lcm(" + m + ", " + n + ") = " + lcm); } }
#include <boost/math/common_factor.hpp> #include <iostream> int main( ) { std::cout << "The least common multiple of 12 and 18 is " << boost::math::lcm( 12 , 18 ) << " ,\n" << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ; return 0 ; }
Port the following code from Java to C++ with equivalent syntax and logic.
import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class FermatNumbers { public static void main(String[] args) { System.out.println("First 10 Fermat numbers:"); for ( int i = 0 ; i < 10 ; i++ ) { System.out.printf("F[%d] = %s\n", i, fermat(i)); } System.out.printf("%nFirst 12 Fermat numbers factored:%n"); for ( int i = 0 ; i < 13 ; i++ ) { System.out.printf("F[%d] = %s\n", i, getString(getFactors(i, fermat(i)))); } } private static String getString(List<BigInteger> factors) { if ( factors.size() == 1 ) { return factors.get(0) + " (PRIME)"; } return factors.stream().map(v -> v.toString()).map(v -> v.startsWith("-") ? "(C" + v.replace("-", "") + ")" : v).collect(Collectors.joining(" * ")); } private static Map<Integer, String> COMPOSITE = new HashMap<>(); static { COMPOSITE.put(9, "5529"); COMPOSITE.put(10, "6078"); COMPOSITE.put(11, "1037"); COMPOSITE.put(12, "5488"); COMPOSITE.put(13, "2884"); } private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) { List<BigInteger> factors = new ArrayList<>(); BigInteger factor = BigInteger.ONE; while ( true ) { if ( n.isProbablePrime(100) ) { factors.add(n); break; } else { if ( COMPOSITE.containsKey(fermatIndex) ) { String stop = COMPOSITE.get(fermatIndex); if ( n.toString().startsWith(stop) ) { factors.add(new BigInteger("-" + n.toString().length())); break; } } factor = pollardRhoFast(n); if ( factor.compareTo(BigInteger.ZERO) == 0 ) { factors.add(n); break; } else { factors.add(factor); n = n.divide(factor); } } } return factors; } private static final BigInteger TWO = BigInteger.valueOf(2); private static BigInteger fermat(int n) { return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE); } @SuppressWarnings("unused") private static BigInteger pollardRho(BigInteger n) { BigInteger x = BigInteger.valueOf(2); BigInteger y = BigInteger.valueOf(2); BigInteger d = BigInteger.ONE; while ( d.compareTo(BigInteger.ONE) == 0 ) { x = pollardRhoG(x, n); y = pollardRhoG(pollardRhoG(y, n), n); d = x.subtract(y).abs().gcd(n); } if ( d.compareTo(n) == 0 ) { return BigInteger.ZERO; } return d; } private static BigInteger pollardRhoFast(BigInteger n) { long start = System.currentTimeMillis(); BigInteger x = BigInteger.valueOf(2); BigInteger y = BigInteger.valueOf(2); BigInteger d = BigInteger.ONE; int count = 0; BigInteger z = BigInteger.ONE; while ( true ) { x = pollardRhoG(x, n); y = pollardRhoG(pollardRhoG(y, n), n); d = x.subtract(y).abs(); z = z.multiply(d).mod(n); count++; if ( count == 100 ) { d = z.gcd(n); if ( d.compareTo(BigInteger.ONE) != 0 ) { break; } z = BigInteger.ONE; count = 0; } } long end = System.currentTimeMillis(); System.out.printf(" Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n", n, (end-start), d); if ( d.compareTo(n) == 0 ) { return BigInteger.ZERO; } return d; } private static BigInteger pollardRhoG(BigInteger x, BigInteger n) { return x.multiply(x).add(BigInteger.ONE).mod(n); } }
#include <iostream> #include <vector> #include <boost/integer/common_factor.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/miller_rabin.hpp> typedef boost::multiprecision::cpp_int integer; integer fermat(unsigned int n) { unsigned int p = 1; for (unsigned int i = 0; i < n; ++i) p *= 2; return 1 + pow(integer(2), p); } inline void g(integer& x, const integer& n) { x *= x; x += 1; x %= n; } integer pollard_rho(const integer& n) { integer x = 2, y = 2, d = 1, z = 1; int count = 0; for (;;) { g(x, n); g(y, n); g(y, n); d = abs(x - y); z = (z * d) % n; ++count; if (count == 100) { d = gcd(z, n); if (d != 1) break; z = 1; count = 0; } } if (d == n) return 0; return d; } std::vector<integer> get_prime_factors(integer n) { std::vector<integer> factors; for (;;) { if (miller_rabin_test(n, 25)) { factors.push_back(n); break; } integer f = pollard_rho(n); if (f == 0) { factors.push_back(n); break; } factors.push_back(f); n /= f; } return factors; } void print_vector(const std::vector<integer>& factors) { if (factors.empty()) return; auto i = factors.begin(); std::cout << *i++; for (; i != factors.end(); ++i) std::cout << ", " << *i; std::cout << '\n'; } int main() { std::cout << "First 10 Fermat numbers:\n"; for (unsigned int i = 0; i < 10; ++i) std::cout << "F(" << i << ") = " << fermat(i) << '\n'; std::cout << "\nPrime factors:\n"; for (unsigned int i = 0; i < 9; ++i) { std::cout << "F(" << i << "): "; print_vector(get_prime_factors(fermat(i))); } return 0; }
Translate this program into C++ but keep the logic exactly as in Java.
import java.util.Random; Random rand = new Random(); while(true){ int a = rand.nextInt(20); System.out.println(a); if(a == 10) break; int b = rand.nextInt(20); System.out.println(b); }
#include <iostream> #include <ctime> #include <cstdlib> int main(){ srand(time(NULL)); while(true){ const int a = rand() % 20; std::cout << a << std::endl; if(a == 10) break; const int b = rand() % 20; std::cout << b << std::endl; } return 0; }
Port the provided Java code into C++ while preserving the original functionality.
import java.io.FileWriter; import java.io.IOException; public class LinePrinter { public static void main(String[] args) { try { FileWriter lp0 = new FileWriter("/dev/lp0"); lp0.write("Hello World!"); lp0.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
#include <iostream> #include <fstream> int main(){ std::ofstream lprFile; lprFile.open( "/dev/lp0" ); lprFile << "Hello World!\n"; lprFile.close(); return 0; }
Keep all operations the same but rewrite the snippet in C++.
import java.io.FileWriter; import java.io.IOException; public class LinePrinter { public static void main(String[] args) { try { FileWriter lp0 = new FileWriter("/dev/lp0"); lp0.write("Hello World!"); lp0.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
#include <iostream> #include <fstream> int main(){ std::ofstream lprFile; lprFile.open( "/dev/lp0" ); lprFile << "Hello World!\n"; lprFile.close(); return 0; }
Port the provided Java code into C++ while preserving the original functionality.
import java.io.FileWriter; import java.io.IOException; public class LinePrinter { public static void main(String[] args) { try { FileWriter lp0 = new FileWriter("/dev/lp0"); lp0.write("Hello World!"); lp0.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
#include <iostream> #include <fstream> int main(){ std::ofstream lprFile; lprFile.open( "/dev/lp0" ); lprFile << "Hello World!\n"; lprFile.close(); return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Java version.
public class WaterBetweenTowers { public static void main(String[] args) { int i = 1; int[][] tba = new int[][]{ new int[]{1, 5, 3, 7, 2}, new int[]{5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, new int[]{2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, new int[]{5, 5, 5, 5}, new int[]{5, 6, 7, 8}, new int[]{8, 7, 7, 6}, new int[]{6, 7, 10, 7, 6} }; for (int[] tea : tba) { int rht, wu = 0, bof; do { for (rht = tea.length - 1; rht >= 0; rht--) { if (tea[rht] > 0) { break; } } if (rht < 0) { break; } bof = 0; for (int col = 0; col <= rht; col++) { if (tea[col] > 0) { tea[col]--; bof += 1; } else if (bof > 0) { wu++; } } if (bof < 2) { break; } } while (true); System.out.printf("Block %d", i++); if (wu == 0) { System.out.print(" does not hold any"); } else { System.out.printf(" holds %d", wu); } System.out.println(" water units."); } } }
#include <iostream> #include <vector> #include <algorithm> enum { EMPTY, WALL, WATER }; auto fill(const std::vector<int> b) { auto water = 0; const auto rows = *std::max_element(std::begin(b), std::end(b)); const auto cols = std::size(b); std::vector<std::vector<int>> g(rows); for (auto& r : g) { for (auto i = 0; i < cols; ++i) { r.push_back(EMPTY); } } for (auto c = 0; c < cols; ++c) { for (auto r = rows - 1u, i = 0u; i < b[c]; ++i, --r) { g[r][c] = WALL; } } for (auto c = 0; c < cols - 1; ++c) { auto start_row = rows - b[c]; while (start_row < rows) { if (g[start_row][c] == EMPTY) break; auto c2 = c + 1; bool hitWall = false; while (c2 < cols) { if (g[start_row][c2] == WALL) { hitWall = true; break; } ++c2; } if (hitWall) { for (auto i = c + 1; i < c2; ++i) { g[start_row][i] = WATER; ++water; } } ++start_row; } } return water; } int main() { std::vector<std::vector<int>> b = { { 1, 5, 3, 7, 2 }, { 5, 3, 7, 2, 6, 4, 5, 9, 1, 2 }, { 2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1 }, { 5, 5, 5, 5 }, { 5, 6, 7, 8 }, { 8, 7, 7, 6 }, { 6, 7, 10, 7, 6 } }; for (const auto v : b) { auto water = fill(v); std::cout << water << " water drops." << std::endl; } std::cin.ignore(); std::cin.get(); return 0; }
Please provide an equivalent version of this Java code in C++.
import java.util.ArrayList; import java.util.List; public class SquareFree { private static List<Long> sieve(long limit) { List<Long> primes = new ArrayList<Long>(); primes.add(2L); boolean[] c = new boolean[(int)limit + 1]; long p = 3; for (;;) { long p2 = p * p; if (p2 > limit) break; for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true; for (;;) { p += 2; if (!c[(int)p]) break; } } for (long i = 3; i <= limit; i += 2) { if (!c[(int)i]) primes.add(i); } return primes; } private static List<Long> squareFree(long from, long to) { long limit = (long)Math.sqrt((double)to); List<Long> primes = sieve(limit); List<Long> results = new ArrayList<Long>(); outer: for (long i = from; i <= to; i++) { for (long p : primes) { long p2 = p * p; if (p2 > i) break; if (i % p2 == 0) continue outer; } results.add(i); } return results; } private final static long TRILLION = 1000000000000L; public static void main(String[] args) { System.out.println("Square-free integers from 1 to 145:"); List<Long> sf = squareFree(1, 145); for (int i = 0; i < sf.size(); i++) { if (i > 0 && i % 20 == 0) { System.out.println(); } System.out.printf("%4d", sf.get(i)); } System.out.print("\n\nSquare-free integers"); System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145); sf = squareFree(TRILLION, TRILLION + 145); for (int i = 0; i < sf.size(); i++) { if (i > 0 && i % 5 == 0) System.out.println(); System.out.printf("%14d", sf.get(i)); } System.out.println("\n\nNumber of square-free integers:\n"); long[] tos = {100, 1000, 10000, 100000, 1000000}; for (long to : tos) { System.out.printf(" from %d to %d = %d\n", 1, to, squareFree(1, to).size()); } } }
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; bool square_free(integer n) { if (n % 4 == 0) return false; for (integer p = 3; p * p <= n; p += 2) { integer count = 0; for (; n % p == 0; n /= p) { if (++count > 1) return false; } } return true; } void print_square_free_numbers(integer from, integer to) { std::cout << "Square-free numbers between " << from << " and " << to << ":\n"; std::string line; for (integer i = from; i <= to; ++i) { if (square_free(i)) { if (!line.empty()) line += ' '; line += std::to_string(i); if (line.size() >= 80) { std::cout << line << '\n'; line.clear(); } } } if (!line.empty()) std::cout << line << '\n'; } void print_square_free_count(integer from, integer to) { integer count = 0; for (integer i = from; i <= to; ++i) { if (square_free(i)) ++count; } std::cout << "Number of square-free numbers between " << from << " and " << to << ": " << count << '\n'; } int main() { print_square_free_numbers(1, 145); print_square_free_numbers(1000000000000LL, 1000000000145LL); print_square_free_count(1, 100); print_square_free_count(1, 1000); print_square_free_count(1, 10000); print_square_free_count(1, 100000); print_square_free_count(1, 1000000); return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.ArrayList; import java.util.List; public class SquareFree { private static List<Long> sieve(long limit) { List<Long> primes = new ArrayList<Long>(); primes.add(2L); boolean[] c = new boolean[(int)limit + 1]; long p = 3; for (;;) { long p2 = p * p; if (p2 > limit) break; for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true; for (;;) { p += 2; if (!c[(int)p]) break; } } for (long i = 3; i <= limit; i += 2) { if (!c[(int)i]) primes.add(i); } return primes; } private static List<Long> squareFree(long from, long to) { long limit = (long)Math.sqrt((double)to); List<Long> primes = sieve(limit); List<Long> results = new ArrayList<Long>(); outer: for (long i = from; i <= to; i++) { for (long p : primes) { long p2 = p * p; if (p2 > i) break; if (i % p2 == 0) continue outer; } results.add(i); } return results; } private final static long TRILLION = 1000000000000L; public static void main(String[] args) { System.out.println("Square-free integers from 1 to 145:"); List<Long> sf = squareFree(1, 145); for (int i = 0; i < sf.size(); i++) { if (i > 0 && i % 20 == 0) { System.out.println(); } System.out.printf("%4d", sf.get(i)); } System.out.print("\n\nSquare-free integers"); System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145); sf = squareFree(TRILLION, TRILLION + 145); for (int i = 0; i < sf.size(); i++) { if (i > 0 && i % 5 == 0) System.out.println(); System.out.printf("%14d", sf.get(i)); } System.out.println("\n\nNumber of square-free integers:\n"); long[] tos = {100, 1000, 10000, 100000, 1000000}; for (long to : tos) { System.out.printf(" from %d to %d = %d\n", 1, to, squareFree(1, to).size()); } } }
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; bool square_free(integer n) { if (n % 4 == 0) return false; for (integer p = 3; p * p <= n; p += 2) { integer count = 0; for (; n % p == 0; n /= p) { if (++count > 1) return false; } } return true; } void print_square_free_numbers(integer from, integer to) { std::cout << "Square-free numbers between " << from << " and " << to << ":\n"; std::string line; for (integer i = from; i <= to; ++i) { if (square_free(i)) { if (!line.empty()) line += ' '; line += std::to_string(i); if (line.size() >= 80) { std::cout << line << '\n'; line.clear(); } } } if (!line.empty()) std::cout << line << '\n'; } void print_square_free_count(integer from, integer to) { integer count = 0; for (integer i = from; i <= to; ++i) { if (square_free(i)) ++count; } std::cout << "Number of square-free numbers between " << from << " and " << to << ": " << count << '\n'; } int main() { print_square_free_numbers(1, 145); print_square_free_numbers(1000000000000LL, 1000000000145LL); print_square_free_count(1, 100); print_square_free_count(1, 1000); print_square_free_count(1, 10000); print_square_free_count(1, 100000); print_square_free_count(1, 1000000); return 0; }
Port the following code from Java to C++ with equivalent syntax and logic.
public class JaroDistance { public static double jaro(String s, String t) { int s_len = s.length(); int t_len = t.length(); if (s_len == 0 && t_len == 0) return 1; int match_distance = Integer.max(s_len, t_len) / 2 - 1; boolean[] s_matches = new boolean[s_len]; boolean[] t_matches = new boolean[t_len]; int matches = 0; int transpositions = 0; for (int i = 0; i < s_len; i++) { int start = Integer.max(0, i-match_distance); int end = Integer.min(i+match_distance+1, t_len); for (int j = start; j < end; j++) { if (t_matches[j]) continue; if (s.charAt(i) != t.charAt(j)) continue; s_matches[i] = true; t_matches[j] = true; matches++; break; } } if (matches == 0) return 0; int k = 0; for (int i = 0; i < s_len; i++) { if (!s_matches[i]) continue; while (!t_matches[k]) k++; if (s.charAt(i) != t.charAt(k)) transpositions++; k++; } return (((double)matches / s_len) + ((double)matches / t_len) + (((double)matches - transpositions/2.0) / matches)) / 3.0; } public static void main(String[] args) { System.out.println(jaro( "MARTHA", "MARHTA")); System.out.println(jaro( "DIXON", "DICKSONX")); System.out.println(jaro("JELLYFISH", "SMELLYFISH")); } }
#include <algorithm> #include <iostream> #include <string> double jaro(const std::string s1, const std::string s2) { const uint l1 = s1.length(), l2 = s2.length(); if (l1 == 0) return l2 == 0 ? 1.0 : 0.0; const uint match_distance = std::max(l1, l2) / 2 - 1; bool s1_matches[l1]; bool s2_matches[l2]; std::fill(s1_matches, s1_matches + l1, false); std::fill(s2_matches, s2_matches + l2, false); uint matches = 0; for (uint i = 0; i < l1; i++) { const int end = std::min(i + match_distance + 1, l2); for (int k = std::max(0u, i - match_distance); k < end; k++) if (!s2_matches[k] && s1[i] == s2[k]) { s1_matches[i] = true; s2_matches[k] = true; matches++; break; } } if (matches == 0) return 0.0; double t = 0.0; uint k = 0; for (uint i = 0; i < l1; i++) if (s1_matches[i]) { while (!s2_matches[k]) k++; if (s1[i] != s2[k]) t += 0.5; k++; } const double m = matches; return (m / l1 + m / l2 + (m - t) / m) / 3.0; } int main() { using namespace std; cout << jaro("MARTHA", "MARHTA") << endl; cout << jaro("DIXON", "DICKSONX") << endl; cout << jaro("JELLYFISH", "SMELLYFISH") << endl; return 0; }
Please provide an equivalent version of this Java code in C++.
package org.rosettacode; import java.util.ArrayList; import java.util.List; public class SumAndProductPuzzle { private final long beginning; private final int maxSum; private static final int MIN_VALUE = 2; private List<int[]> firstConditionExcludes = new ArrayList<>(); private List<int[]> secondConditionExcludes = new ArrayList<>(); public static void main(String... args){ if (args.length == 0){ new SumAndProductPuzzle(100).run(); new SumAndProductPuzzle(1684).run(); new SumAndProductPuzzle(1685).run(); } else { for (String arg : args){ try{ new SumAndProductPuzzle(Integer.valueOf(arg)).run(); } catch (NumberFormatException e){ System.out.println("Please provide only integer arguments. " + "Provided argument " + arg + " was not an integer. " + "Alternatively, calling the program with no arguments " + "will run the puzzle where maximum sum equals 100, 1684, and 1865."); } } } } public SumAndProductPuzzle(int maxSum){ this.beginning = System.currentTimeMillis(); this.maxSum = maxSum; System.out.println("Run with maximum sum of " + String.valueOf(maxSum) + " started at " + String.valueOf(beginning) + "."); } public void run(){ for (int x = MIN_VALUE; x < maxSum - MIN_VALUE; x++){ for (int y = x + 1; y < maxSum - MIN_VALUE; y++){ if (isSumNoGreaterThanMax(x,y) && isSKnowsPCannotKnow(x,y) && isPKnowsNow(x,y) && isSKnowsNow(x,y) ){ System.out.println("Found solution x is " + String.valueOf(x) + " y is " + String.valueOf(y) + " in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms."); } } } System.out.println("Run with maximum sum of " + String.valueOf(maxSum) + " ended in " + String.valueOf(System.currentTimeMillis() - beginning) + "ms."); } public boolean isSumNoGreaterThanMax(int x, int y){ return x + y <= maxSum; } public boolean isSKnowsPCannotKnow(int x, int y){ if (firstConditionExcludes.contains(new int[] {x, y})){ return false; } for (int[] addends : sumAddends(x, y)){ if ( !(productFactors(addends[0], addends[1]).size() > 1) ) { firstConditionExcludes.add(new int[] {x, y}); return false; } } return true; } public boolean isPKnowsNow(int x, int y){ if (secondConditionExcludes.contains(new int[] {x, y})){ return false; } int countSolutions = 0; for (int[] factors : productFactors(x, y)){ if (isSKnowsPCannotKnow(factors[0], factors[1])){ countSolutions++; } } if (countSolutions == 1){ return true; } else { secondConditionExcludes.add(new int[] {x, y}); return false; } } public boolean isSKnowsNow(int x, int y){ int countSolutions = 0; for (int[] addends : sumAddends(x, y)){ if (isPKnowsNow(addends[0], addends[1])){ countSolutions++; } } return countSolutions == 1; } public List<int[]> sumAddends(int x, int y){ List<int[]> list = new ArrayList<>(); int sum = x + y; for (int addend = MIN_VALUE; addend < sum - addend; addend++){ if (isSumNoGreaterThanMax(addend, sum - addend)){ list.add(new int[]{addend, sum - addend}); } } return list; } public List<int[]> productFactors(int x, int y){ List<int[]> list = new ArrayList<>(); int product = x * y; for (int factor = MIN_VALUE; factor < product / factor; factor++){ if (product % factor == 0){ if (isSumNoGreaterThanMax(factor, product / factor)){ list.add(new int[]{factor, product / factor}); } } } return list; } }
#include <algorithm> #include <iostream> #include <map> #include <vector> std::ostream &operator<<(std::ostream &os, std::vector<std::pair<int, int>> &v) { for (auto &p : v) { auto sum = p.first + p.second; auto prod = p.first * p.second; os << '[' << p.first << ", " << p.second << "] S=" << sum << " P=" << prod; } return os << '\n'; } void print_count(const std::vector<std::pair<int, int>> &candidates) { auto c = candidates.size(); if (c == 0) { std::cout << "no candidates\n"; } else if (c == 1) { std::cout << "one candidate\n"; } else { std::cout << c << " candidates\n"; } } auto setup() { std::vector<std::pair<int, int>> candidates; for (int x = 2; x <= 98; x++) { for (int y = x + 1; y <= 98; y++) { if (x + y <= 100) { candidates.push_back(std::make_pair(x, y)); } } } return candidates; } void remove_by_sum(std::vector<std::pair<int, int>> &candidates, const int sum) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [sum](const std::pair<int, int> &pair) { auto s = pair.first + pair.second; return s == sum; } ), candidates.end()); } void remove_by_prod(std::vector<std::pair<int, int>> &candidates, const int prod) { candidates.erase(std::remove_if( candidates.begin(), candidates.end(), [prod](const std::pair<int, int> &pair) { auto p = pair.first * pair.second; return p == prod; } ), candidates.end()); } void statement1(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] == 1) { auto sum = pair.first + pair.second; remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } void statement2(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto prod = pair.first * pair.second; uniqueMap[prod]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto prod = pair.first * pair.second; if (uniqueMap[prod] > 1) { remove_by_prod(candidates, prod); loop = true; break; } } } while (loop); } void statement3(std::vector<std::pair<int, int>> &candidates) { std::map<int, int> uniqueMap; std::for_each( candidates.cbegin(), candidates.cend(), [&uniqueMap](const std::pair<int, int> &pair) { auto sum = pair.first + pair.second; uniqueMap[sum]++; } ); bool loop; do { loop = false; for (auto &pair : candidates) { auto sum = pair.first + pair.second; if (uniqueMap[sum] > 1) { remove_by_sum(candidates, sum); loop = true; break; } } } while (loop); } int main() { auto candidates = setup(); print_count(candidates); statement1(candidates); print_count(candidates); statement2(candidates); print_count(candidates); statement3(candidates); print_count(candidates); std::cout << candidates; return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Java version.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FairshareBetweenTwoAndMore { public static void main(String[] args) { for ( int base : Arrays.asList(2, 3, 5, 11) ) { System.out.printf("Base %d = %s%n", base, thueMorseSequence(25, base)); } } private static List<Integer> thueMorseSequence(int terms, int base) { List<Integer> sequence = new ArrayList<Integer>(); for ( int i = 0 ; i < terms ; i++ ) { int sum = 0; int n = i; while ( n > 0 ) { sum += n % base; n /= base; } sequence.add(sum % base); } return sequence; } }
#include <iostream> #include <vector> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { printf("Base %2d:", base); for (int i = 0; i < count; i++) { int t = turn(base, i); printf(" %2d", t); } printf("\n"); } void turnCount(int base, int count) { std::vector<int> cnt(base, 0); for (int i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } int minTurn = INT_MAX; int maxTurn = INT_MIN; int portion = 0; for (int i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(" With %d people: ", base); if (0 == minTurn) { printf("Only %d have a turn\n", portion); } else if (minTurn == maxTurn) { printf("%d\n", minTurn); } else { printf("%d or %d\n", minTurn, maxTurn); } } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf("How many times does each get a turn in 50000 iterations?\n"); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
Change the following Java code into C++ without altering its purpose.
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); } static String infixToPostfix(String infix) { final String ops = "-+/*^"; StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); for (String token : infix.split("\\s")) { if (token.isEmpty()) continue; char c = token.charAt(0); int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 > prec1 || (prec2 == prec1 && c != '^')) sb.append(ops.charAt(s.pop())).append(' '); else break; } s.push(idx); } } else if (c == '(') { s.push(-2); } else if (c == ')') { while (s.peek() != -2) sb.append(ops.charAt(s.pop())).append(' '); s.pop(); } else { sb.append(token).append(' '); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())).append(' '); return sb.toString(); } }
#include <ciso646> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> using std::vector; using std::string; #include <exception> #include <stdexcept> template <typename...Args> std::runtime_error error( Args...args ) { return std::runtime_error( (std::ostringstream{} << ... << args).str() ); }; template <typename T> struct stack : public std::vector <T> { using base_type = std::vector <T> ; T push ( const T& x ) { base_type::push_back( x ); return x; } const T& top () { return base_type::back(); } T pop () { T x = std::move( top() ); base_type::pop_back(); return x; } bool empty() { return base_type::empty(); } }; using Number = double; using Operator_Name = string; using Precedence = int; enum class Associates { none, left_to_right, right_to_left }; struct Operator_Info { Precedence precedence; Associates associativity; }; std::unordered_map <Operator_Name, Operator_Info> Operators = { { "^", { 4, Associates::right_to_left } }, { "*", { 3, Associates::left_to_right } }, { "/", { 3, Associates::left_to_right } }, { "+", { 2, Associates::left_to_right } }, { "-", { 2, Associates::left_to_right } }, }; Precedence precedence ( const Operator_Name& op ) { return Operators[ op ].precedence; } Associates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; } using Token = string; bool is_number ( const Token& t ) { return regex_match( t, std::regex{ R"z((\d+(\.\d*)?|\.\d+)([Ee][\+\-]?\d+)?)z" } ); } bool is_operator ( const Token& t ) { return Operators.count( t ); } bool is_open_parenthesis ( const Token& t ) { return t == "("; } bool is_close_parenthesis( const Token& t ) { return t == ")"; } bool is_parenthesis ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); } template <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs ) { std::size_t n = 0; for (auto x : xs) outs << (n++ ? " " : "") << x; return outs; } #include <iomanip> struct Progressive_Display { string token_name; string token_type; Progressive_Display() { std::cout << "\n" " INPUT │ TYPE │ ACTION │ STACK │ OUTPUT\n" "────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\n"; } Progressive_Display& operator () ( const Token& token ) { token_name = token; token_type = is_operator ( token ) ? "op" : is_parenthesis( token ) ? "()" : is_number ( token ) ? "num" : ""; return *this; } Progressive_Display& operator () ( const string & description, const stack <Token> & stack, const vector <Token> & output ) { std::cout << std::right << std::setw( 7 ) << token_name << " │ " << std::left << std::setw( 4 ) << token_type << " │ " << std::setw( 16 ) << description << " │ " << std::setw( 12 ) << (std::ostringstream{} << stack).str() << " │ " << output << "\n"; return operator () ( "" ); } }; vector <Token> parse( const vector <Token> & tokens ) { vector <Token> output; stack <Token> stack; Progressive_Display display; for (auto token : tokens) if (is_number( token )) { output.push_back( token ); display( token )( "num --> output", stack, output ); } else if (is_operator( token ) or is_parenthesis( token )) { display( token ); if (!is_open_parenthesis( token )) { while (!stack.empty() and ( (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() )) or (precedence( stack.top() ) > precedence( token )) or ( (precedence( stack.top() ) == precedence( token )) and (associativity( token ) == Associates::left_to_right)))) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } if (is_close_parenthesis( token )) { stack.pop(); display( "pop", stack, output ); } } if (!is_close_parenthesis( token )) { stack.push( token ); display( "push op", stack, output ); } } else throw error( "unexpected token: ", token ); display( "END" ); while (!stack.empty()) { output.push_back( stack.pop() ); display( "pop --> output", stack, output ); } return output; } int main( int argc, char** argv ) try { auto tokens = vector <Token> ( argv+1, argv+argc ); auto rpn_expr = parse( tokens ); std::cout << "\nInfix = " << tokens << "\nRPN = " << rpn_expr << "\n"; } catch (std::exception e) { std::cerr << "error: " << e.what() << "\n"; return 1; }
Preserve the algorithm and functionality while converting the code from Java to C++.
public class PrimeTriangle { public static void main(String[] args) { long start = System.currentTimeMillis(); for (int i = 2; i <= 20; ++i) { int[] a = new int[i]; for (int j = 0; j < i; ++j) a[j] = j + 1; if (findRow(a, 0, i)) printRow(a); } System.out.println(); StringBuilder s = new StringBuilder(); for (int i = 2; i <= 20; ++i) { int[] a = new int[i]; for (int j = 0; j < i; ++j) a[j] = j + 1; if (i > 2) s.append(" "); s.append(countRows(a, 0, i)); } System.out.println(s); long finish = System.currentTimeMillis(); System.out.printf("\nElapsed time: %d milliseconds\n", finish - start); } private static void printRow(int[] a) { for (int i = 0; i < a.length; ++i) { if (i != 0) System.out.print(" "); System.out.printf("%2d", a[i]); } System.out.println(); } private static boolean findRow(int[] a, int start, int length) { if (length == 2) return isPrime(a[start] + a[start + 1]); for (int i = 1; i + 1 < length; i += 2) { if (isPrime(a[start] + a[start + i])) { swap(a, start + i, start + 1); if (findRow(a, start + 1, length - 1)) return true; swap(a, start + i, start + 1); } } return false; } private static int countRows(int[] a, int start, int length) { int count = 0; if (length == 2) { if (isPrime(a[start] + a[start + 1])) ++count; } else { for (int i = 1; i + 1 < length; i += 2) { if (isPrime(a[start] + a[start + i])) { swap(a, start + i, start + 1); count += countRows(a, start + 1, length - 1); swap(a, start + i, start + 1); } } } return count; } private static void swap(int[] a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } private static boolean isPrime(int n) { return ((1L << n) & 0x28208a20a08a28acL) != 0; } }
#include <cassert> #include <chrono> #include <iomanip> #include <iostream> #include <numeric> #include <vector> bool is_prime(unsigned int n) { assert(n > 0 && n < 64); return (1ULL << n) & 0x28208a20a08a28ac; } template <typename Iterator> bool prime_triangle_row(Iterator begin, Iterator end) { if (std::distance(begin, end) == 2) return is_prime(*begin + *(begin + 1)); for (auto i = begin + 1; i + 1 != end; ++i) { if (is_prime(*begin + *i)) { std::iter_swap(i, begin + 1); if (prime_triangle_row(begin + 1, end)) return true; std::iter_swap(i, begin + 1); } } return false; } template <typename Iterator> void prime_triangle_count(Iterator begin, Iterator end, int& count) { if (std::distance(begin, end) == 2) { if (is_prime(*begin + *(begin + 1))) ++count; return; } for (auto i = begin + 1; i + 1 != end; ++i) { if (is_prime(*begin + *i)) { std::iter_swap(i, begin + 1); prime_triangle_count(begin + 1, end, count); std::iter_swap(i, begin + 1); } } } template <typename Iterator> void print(Iterator begin, Iterator end) { if (begin == end) return; auto i = begin; std::cout << std::setw(2) << *i++; for (; i != end; ++i) std::cout << ' ' << std::setw(2) << *i; std::cout << '\n'; } int main() { auto start = std::chrono::high_resolution_clock::now(); for (unsigned int n = 2; n < 21; ++n) { std::vector<unsigned int> v(n); std::iota(v.begin(), v.end(), 1); if (prime_triangle_row(v.begin(), v.end())) print(v.begin(), v.end()); } std::cout << '\n'; for (unsigned int n = 2; n < 21; ++n) { std::vector<unsigned int> v(n); std::iota(v.begin(), v.end(), 1); int count = 0; prime_triangle_count(v.begin(), v.end(), count); if (n > 2) std::cout << ' '; std::cout << count; } std::cout << '\n'; auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration(end - start); std::cout << "\nElapsed time: " << duration.count() << " seconds\n"; }
Rewrite this program in C++ while keeping its functionality equivalent to the Java version.
import java.util.*; import java.io.*; public class TPKA { public static void main(String... args) { double[] input = new double[11]; double userInput = 0.0; Scanner in = new Scanner(System.in); for(int i = 0; i < 11; i++) { System.out.print("Please enter a number: "); String s = in.nextLine(); try { userInput = Double.parseDouble(s); } catch (NumberFormatException e) { System.out.println("You entered invalid input, exiting"); System.exit(1); } input[i] = userInput; } for(int j = 10; j >= 0; j--) { double x = input[j]; double y = f(x); if( y < 400.0) { System.out.printf("f( %.2f ) = %.2f\n", x, y); } else { System.out.printf("f( %.2f ) = %s\n", x, "TOO LARGE"); } } } private static double f(double x) { return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3))); } }
#include <iostream> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> int main( ) { std::vector<double> input( 11 ) , results( 11 ) ; std::cout << "Please enter 11 numbers!\n" ; for ( int i = 0 ; i < input.size( ) ; i++ ) std::cin >> input[i]; std::transform( input.begin( ) , input.end( ) , results.begin( ) , [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ; for ( int i = 10 ; i > -1 ; i-- ) { std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ; if ( results[ i ] > 400 ) std::cout << "too large!" ; else std::cout << results[ i ] << " !" ; std::cout << std::endl ; } return 0 ; }
Rewrite this program in C++ while keeping its functionality equivalent to the Java version.
public class MiddleThreeDigits { public static void main(String[] args) { final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE}; final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE, Integer.MAX_VALUE}; for (long n : passing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); for (int n : failing) System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n)); } public static <T> String middleThreeDigits(T n) { String s = String.valueOf(n); if (s.charAt(0) == '-') s = s.substring(1); int len = s.length(); if (len < 3 || len % 2 == 0) return "Need odd and >= 3 digits"; int mid = len / 2; return s.substring(mid - 1, mid + 2); } }
#include <iostream> std::string middleThreeDigits(int n) { auto number = std::to_string(std::abs(n)); auto length = number.size(); if (length < 3) { return "less than three digits"; } else if (length % 2 == 0) { return "even number of digits"; } else { return number.substr(length / 2 - 1, 3); } } int main() { auto values {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0}; for (auto&& v : values) { std::cout << "middleThreeDigits(" << v << "): " << middleThreeDigits(v) << "\n"; } }
Convert the following code from Java to C++, ensuring the logic remains intact.
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class SequenceNthNumberWithExactlyNDivisors { public static void main(String[] args) { int max = 45; smallPrimes(max); for ( int n = 1; n <= max ; n++ ) { System.out.printf("A073916(%d) = %s%n", n, OEISA073916(n)); } } private static List<Integer> smallPrimes = new ArrayList<>(); private static void smallPrimes(int numPrimes) { smallPrimes.add(2); for ( int n = 3, count = 0 ; count < numPrimes ; n += 2 ) { if ( isPrime(n) ) { smallPrimes.add(n); count++; } } } private static final boolean isPrime(long test) { if ( test == 2 ) { return true; } if ( test % 2 == 0 ) { return false; } for ( long d = 3 ; d*d <= test ; d += 2 ) { if ( test % d == 0 ) { return false; } } return true; } private static int getDivisorCount(long n) { int count = 1; while ( n % 2 == 0 ) { n /= 2; count += 1; } for ( long d = 3 ; d*d <= n ; d += 2 ) { long q = n / d; long r = n % d; int dc = 0; while ( r == 0 ) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if ( n != 1 ) { count *= 2; } return count; } private static BigInteger OEISA073916(int n) { if ( isPrime(n) ) { return BigInteger.valueOf(smallPrimes.get(n-1)).pow(n - 1); } int count = 0; int result = 0; for ( int i = 1 ; count < n ; i++ ) { if ( n % 2 == 1 ) { int sqrt = (int) Math.sqrt(i); if ( sqrt*sqrt != i ) { continue; } } if ( getDivisorCount(i) == n ) { count++; result = i; } } return BigInteger.valueOf(result); } }
#include <iostream> #include <vector> std::vector<int> smallPrimes; bool is_prime(size_t test) { if (test < 2) { return false; } if (test % 2 == 0) { return test == 2; } for (size_t d = 3; d * d <= test; d += 2) { if (test % d == 0) { return false; } } return true; } void init_small_primes(size_t numPrimes) { smallPrimes.push_back(2); int count = 0; for (size_t n = 3; count < numPrimes; n += 2) { if (is_prime(n)) { smallPrimes.push_back(n); count++; } } } size_t divisor_count(size_t n) { size_t count = 1; while (n % 2 == 0) { n /= 2; count++; } for (size_t d = 3; d * d <= n; d += 2) { size_t q = n / d; size_t r = n % d; size_t dc = 0; while (r == 0) { dc += count; n = q; q = n / d; r = n % d; } count += dc; } if (n != 1) { count *= 2; } return count; } uint64_t OEISA073916(size_t n) { if (is_prime(n)) { return (uint64_t) pow(smallPrimes[n - 1], n - 1); } size_t count = 0; uint64_t result = 0; for (size_t i = 1; count < n; i++) { if (n % 2 == 1) { size_t root = (size_t) sqrt(i); if (root * root != i) { continue; } } if (divisor_count(i) == n) { count++; result = i; } } return result; } int main() { const int MAX = 15; init_small_primes(MAX); for (size_t n = 1; n <= MAX; n++) { if (n == 13) { std::cout << "A073916(" << n << ") = One more bit needed to represent result.\n"; } else { std::cout << "A073916(" << n << ") = " << OEISA073916(n) << '\n'; } } return 0; }
Keep all operations the same but rewrite the snippet in C++.
import java.util.Arrays; public class OEIS_A005179 { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return count; } public static void main(String[] args) { final int max = 15; int[] seq = new int[max]; System.out.printf("The first %d terms of the sequence are:\n", max); for (int i = 1, n = 0; n < max; ++i) { int k = count_divisors(i); if (k <= max && seq[k - 1] == 0) { seq[k- 1] = i; n++; } } System.out.println(Arrays.toString(seq)); } }
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; for (i = 0; i < MAX; ++i) seq[i] = 0; cout << "The first " << MAX << " terms of the sequence are:" << endl; for (i = 1, n = 0; n < MAX; ++i) { k = count_divisors(i); if (k <= MAX && seq[k - 1] == 0) { seq[k - 1] = i; ++n; } } for (i = 0; i < MAX; ++i) cout << seq[i] << " "; cout << endl; return 0; }
Generate a C++ translation of this Java snippet without changing its computational steps.
import java.util.Arrays; public class OEIS_A005179 { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return count; } public static void main(String[] args) { final int max = 15; int[] seq = new int[max]; System.out.printf("The first %d terms of the sequence are:\n", max); for (int i = 1, n = 0; n < max; ++i) { int k = count_divisors(i); if (k <= max && seq[k - 1] == 0) { seq[k- 1] = i; n++; } } System.out.println(Arrays.toString(seq)); } }
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { int i, k, n, seq[MAX]; for (i = 0; i < MAX; ++i) seq[i] = 0; cout << "The first " << MAX << " terms of the sequence are:" << endl; for (i = 1, n = 0; n < MAX; ++i) { k = count_divisors(i); if (k <= MAX && seq[k - 1] == 0) { seq[k - 1] = i; ++n; } } for (i = 0; i < MAX; ++i) cout << seq[i] << " "; cout << endl; return 0; }
Convert this Java snippet to C++ and keep its semantics consistent.
public class Pancake { private static int pancake(int n) { int gap = 2; int sum = 2; int adj = -1; while (sum < n) { adj++; gap = 2 * gap - 1; sum += gap; } return n + adj; } public static void main(String[] args) { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = 5 * i + j; System.out.printf("p(%2d) = %2d ", n, pancake(n)); } System.out.println(); } } }
#include <iomanip> #include <iostream> int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; } int main() { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = i * 5 + j; std::cout << "p(" << std::setw(2) << n << ") = " << std::setw(2) << pancake(n) << " "; } std::cout << '\n'; } return 0; }
Transform the following Java implementation into C++, maintaining the same output and logic.
public class Pancake { private static int pancake(int n) { int gap = 2; int sum = 2; int adj = -1; while (sum < n) { adj++; gap = 2 * gap - 1; sum += gap; } return n + adj; } public static void main(String[] args) { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = 5 * i + j; System.out.printf("p(%2d) = %2d ", n, pancake(n)); } System.out.println(); } } }
#include <iomanip> #include <iostream> int pancake(int n) { int gap = 2, sum = 2, adj = -1; while (sum < n) { adj++; gap = gap * 2 - 1; sum += gap; } return n + adj; } int main() { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = i * 5 + j; std::cout << "p(" << std::setw(2) << n << ") = " << std::setw(2) << pancake(n) << " "; } std::cout << '\n'; } return 0; }
Port the following code from Java to C++ with equivalent syntax and logic.
import static java.lang.Math.abs; import java.util.Random; public class Fen { static Random rand = new Random(); public static void main(String[] args) { System.out.println(createFen()); } static String createFen() { char[][] grid = new char[8][8]; placeKings(grid); placePieces(grid, "PPPPPPPP", true); placePieces(grid, "pppppppp", true); placePieces(grid, "RNBQBNR", false); placePieces(grid, "rnbqbnr", false); return toFen(grid); } static void placeKings(char[][] grid) { int r1, c1, r2, c2; while (true) { r1 = rand.nextInt(8); c1 = rand.nextInt(8); r2 = rand.nextInt(8); c2 = rand.nextInt(8); if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) break; } grid[r1][c1] = 'K'; grid[r2][c2] = 'k'; } static void placePieces(char[][] grid, String pieces, boolean isPawn) { int numToPlace = rand.nextInt(pieces.length()); for (int n = 0; n < numToPlace; n++) { int r, c; do { r = rand.nextInt(8); c = rand.nextInt(8); } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0))); grid[r][c] = pieces.charAt(n); } } static String toFen(char[][] grid) { StringBuilder fen = new StringBuilder(); int countEmpty = 0; for (int r = 0; r < 8; r++) { for (int c = 0; c < 8; c++) { char ch = grid[r][c]; System.out.printf("%2c ", ch == 0 ? '.' : ch); if (ch == 0) { countEmpty++; } else { if (countEmpty > 0) { fen.append(countEmpty); countEmpty = 0; } fen.append(ch); } } if (countEmpty > 0) { fen.append(countEmpty); countEmpty = 0; } fen.append("/"); System.out.println(); } return fen.append(" w - - 0 1").toString(); } }
#include <ctime> #include <iostream> #include <string> #include <algorithm> class chessBoard { public: void generateRNDBoard( int brds ) { int a, b, i; char c; for( int cc = 0; cc < brds; cc++ ) { memset( brd, 0, 64 ); std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk"; random_shuffle( pieces.begin(), pieces.end() ); while( pieces.length() ) { i = rand() % pieces.length(); c = pieces.at( i ); while( true ) { a = rand() % 8; b = rand() % 8; if( brd[a][b] == 0 ) { if( c == 'P' && !b || c == 'p' && b == 7 || ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue; break; } } brd[a][b] = c; pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 ); } print(); } } private: bool search( char c, int a, int b ) { for( int y = -1; y < 2; y++ ) { for( int x = -1; x < 2; x++ ) { if( !x && !y ) continue; if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) { if( brd[a + x][b + y] == c ) return true; } } } return false; } void print() { int e = 0; for( int y = 0; y < 8; y++ ) { for( int x = 0; x < 8; x++ ) { if( brd[x][y] == 0 ) e++; else { if( e > 0 ) { std::cout << e; e = 0; } std::cout << brd[x][y]; } } if( e > 0 ) { std::cout << e; e = 0; } if( y < 7 ) std::cout << "/"; } std::cout << " w - - 0 1\n\n"; for( int y = 0; y < 8; y++ ) { for( int x = 0; x < 8; x++ ) { if( brd[x][y] == 0 ) std::cout << "."; else std::cout << brd[x][y]; } std::cout << "\n"; } std::cout << "\n\n"; } char brd[8][8]; }; int main( int argc, char* argv[] ) { srand( ( unsigned )time( 0 ) ); chessBoard c; c.generateRNDBoard( 2 ); return 0; }
Write a version of this Java function in C++ with identical behavior.
import java.util.ArrayList; import java.util.stream.IntStream; import java.util.stream.LongStream; public class EstheticNumbers { interface RecTriConsumer<A, B, C> { void accept(RecTriConsumer<A, B, C> f, A a, B b, C c); } private static boolean isEsthetic(long n, long b) { if (n == 0) { return false; } var i = n % b; var n2 = n / b; while (n2 > 0) { var j = n2 % b; if (Math.abs(i - j) != 1) { return false; } n2 /= b; i = j; } return true; } private static void listEsths(long n, long n2, long m, long m2, int perLine, boolean all) { var esths = new ArrayList<Long>(); var dfs = new RecTriConsumer<Long, Long, Long>() { public void accept(Long n, Long m, Long i) { accept(this, n, m, i); } @Override public void accept(RecTriConsumer<Long, Long, Long> f, Long n, Long m, Long i) { if (n <= i && i <= m) { esths.add(i); } if (i == 0 || i > m) { return; } var d = i % 10; var i1 = i * 10 + d - 1; var i2 = i1 + 2; if (d == 0) { f.accept(f, n, m, i2); } else if (d == 9) { f.accept(f, n, m, i1); } else { f.accept(f, n, m, i1); f.accept(f, n, m, i2); } } }; LongStream.range(0, 10).forEach(i -> dfs.accept(n2, m2, i)); var le = esths.size(); System.out.printf("Base 10: %d esthetic numbers between %d and %d:%n", le, n, m); if (all) { for (int i = 0; i < esths.size(); i++) { System.out.printf("%d ", esths.get(i)); if ((i + 1) % perLine == 0) { System.out.println(); } } } else { for (int i = 0; i < perLine; i++) { System.out.printf("%d ", esths.get(i)); } System.out.println(); System.out.println("............"); for (int i = le - perLine; i < le; i++) { System.out.printf("%d ", esths.get(i)); } } System.out.println(); System.out.println(); } public static void main(String[] args) { IntStream.rangeClosed(2, 16).forEach(b -> { System.out.printf("Base %d: %dth to %dth esthetic numbers:%n", b, 4 * b, 6 * b); var n = 1L; var c = 0L; while (c < 6 * b) { if (isEsthetic(n, b)) { c++; if (c >= 4 * b) { System.out.printf("%s ", Long.toString(n, b)); } } n++; } System.out.println(); }); System.out.println(); listEsths(1000, 1010, 9999, 9898, 16, true); listEsths((long) 1e8, 101_010_101, 13 * (long) 1e7, 123_456_789, 9, true); listEsths((long) 1e11, 101_010_101_010L, 13 * (long) 1e10, 123_456_789_898L, 7, false); listEsths((long) 1e14, 101_010_101_010_101L, 13 * (long) 1e13, 123_456_789_898_989L, 5, false); listEsths((long) 1e17, 101_010_101_010_101_010L, 13 * (long) 1e16, 123_456_789_898_989_898L, 4, false); } }
#include <functional> #include <iostream> #include <sstream> #include <vector> std::string to(int n, int b) { static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::stringstream ss; while (n > 0) { auto rem = n % b; n = n / b; ss << BASE[rem]; } auto fwd = ss.str(); return std::string(fwd.rbegin(), fwd.rend()); } uint64_t uabs(uint64_t a, uint64_t b) { if (a < b) { return b - a; } return a - b; } bool isEsthetic(uint64_t n, uint64_t b) { if (n == 0) { return false; } auto i = n % b; n /= b; while (n > 0) { auto j = n % b; if (uabs(i, j) != 1) { return false; } n /= b; i = j; } return true; } void listEsths(uint64_t n, uint64_t n2, uint64_t m, uint64_t m2, int perLine, bool all) { std::vector<uint64_t> esths; const auto dfs = [&esths](uint64_t n, uint64_t m, uint64_t i) { auto dfs_impl = [&esths](uint64_t n, uint64_t m, uint64_t i, auto &dfs_ref) { if (i >= n && i <= m) { esths.push_back(i); } if (i == 0 || i > m) { return; } auto d = i % 10; auto i1 = i * 10 + d - 1; auto i2 = i1 + 2; if (d == 0) { dfs_ref(n, m, i2, dfs_ref); } else if (d == 9) { dfs_ref(n, m, i1, dfs_ref); } else { dfs_ref(n, m, i1, dfs_ref); dfs_ref(n, m, i2, dfs_ref); } }; dfs_impl(n, m, i, dfs_impl); }; for (int i = 0; i < 10; i++) { dfs(n2, m2, i); } auto le = esths.size(); printf("Base 10: %d esthetic numbers between %llu and %llu:\n", le, n, m); if (all) { for (size_t c = 0; c < esths.size(); c++) { auto esth = esths[c]; printf("%llu ", esth); if ((c + 1) % perLine == 0) { printf("\n"); } } printf("\n"); } else { for (int c = 0; c < perLine; c++) { auto esth = esths[c]; printf("%llu ", esth); } printf("\n............\n"); for (size_t i = le - perLine; i < le; i++) { auto esth = esths[i]; printf("%llu ", esth); } printf("\n"); } printf("\n"); } int main() { for (int b = 2; b <= 16; b++) { printf("Base %d: %dth to %dth esthetic numbers:\n", b, 4 * b, 6 * b); for (int n = 1, c = 0; c < 6 * b; n++) { if (isEsthetic(n, b)) { c++; if (c >= 4 * b) { std::cout << to(n, b) << ' '; } } } printf("\n"); } printf("\n"); listEsths(1000, 1010, 9999, 9898, 16, true); listEsths((uint64_t)1e8, 101'010'101, 13 * (uint64_t)1e7, 123'456'789, 9, true); listEsths((uint64_t)1e11, 101'010'101'010, 13 * (uint64_t)1e10, 123'456'789'898, 7, false); listEsths((uint64_t)1e14, 101'010'101'010'101, 13 * (uint64_t)1e13, 123'456'789'898'989, 5, false); listEsths((uint64_t)1e17, 101'010'101'010'101'010, 13 * (uint64_t)1e16, 123'456'789'898'989'898, 4, false); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
public class Topswops { static final int maxBest = 32; static int[] best; static private void trySwaps(int[] deck, int f, int d, int n) { if (d > best[n]) best[n] = d; for (int i = n - 1; i >= 0; i--) { if (deck[i] == -1 || deck[i] == i) break; if (d + best[i] <= best[n]) return; } int[] deck2 = deck.clone(); for (int i = 1; i < n; i++) { final int k = 1 << i; if (deck2[i] == -1) { if ((f & k) != 0) continue; } else if (deck2[i] != i) continue; deck2[0] = i; for (int j = i - 1; j >= 0; j--) deck2[i - j] = deck[j]; trySwaps(deck2, f | k, d + 1, n); } } static int topswops(int n) { assert(n > 0 && n < maxBest); best[n] = 0; int[] deck0 = new int[n + 1]; for (int i = 1; i < n; i++) deck0[i] = -1; trySwaps(deck0, 1, 0, n); return best[n]; } public static void main(String[] args) { best = new int[maxBest]; for (int i = 1; i < 11; i++) System.out.println(i + ": " + topswops(i)); } }
#include <iostream> #include <vector> #include <numeric> #include <algorithm> int topswops(int n) { std::vector<int> list(n); std::iota(std::begin(list), std::end(list), 1); int max_steps = 0; do { auto temp_list = list; for (int steps = 1; temp_list[0] != 1; ++steps) { std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]); if (steps > max_steps) max_steps = steps; } } while (std::next_permutation(std::begin(list), std::end(list))); return max_steps; } int main() { for (int i = 1; i <= 10; ++i) { std::cout << i << ": " << topswops(i) << std::endl; } return 0; }
Preserve the algorithm and functionality while converting the code from Java to C++.
public class OldRussianMeasures { final static String[] keys = {"tochka", "liniya", "centimeter", "diuym", "vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer", "versta", "milia"}; final static double[] values = {0.000254, 0.00254, 0.01,0.0254, 0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0, 1066.8, 7467.6}; public static void main(String[] a) { if (a.length == 2 && a[0].matches("[+-]?\\d*(\\.\\d+)?")) { double inputVal = lookup(a[1]); if (!Double.isNaN(inputVal)) { double magnitude = Double.parseDouble(a[0]); double meters = magnitude * inputVal; System.out.printf("%s %s to: %n%n", a[0], a[1]); for (String k: keys) System.out.printf("%10s: %g%n", k, meters / lookup(k)); return; } } System.out.println("Please provide a number and unit"); } public static double lookup(String key) { for (int i = 0; i < keys.length; i++) if (keys[i].equals(key)) return values[i]; return Double.NaN; } }
#include <iostream> #include <iomanip> using namespace std; class ormConverter { public: ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ), MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {} void convert( char c, float l ) { system( "cls" ); cout << endl << l; switch( c ) { case 'A': cout << " Arshin to:"; l *= AR; break; case 'C': cout << " Centimeter to:"; l *= CE; break; case 'D': cout << " Diuym to:"; l *= DI; break; case 'F': cout << " Fut to:"; l *= FU; break; case 'K': cout << " Kilometer to:"; l *= KI; break; case 'L': cout << " Liniya to:"; l *= LI; break; case 'M': cout << " Meter to:"; l *= ME; break; case 'I': cout << " Milia to:"; l *= MI; break; case 'P': cout << " Piad to:"; l *= PI; break; case 'S': cout << " Sazhen to:"; l *= SA; break; case 'T': cout << " Tochka to:"; l *= TO; break; case 'V': cout << " Vershok to:"; l *= VE; break; case 'E': cout << " Versta to:"; l *= VR; } float ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME, mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR; cout << left << endl << "=================" << endl << setw( 12 ) << "Arshin:" << ar << endl << setw( 12 ) << "Centimeter:" << ce << endl << setw( 12 ) << "Diuym:" << di << endl << setw( 12 ) << "Fut:" << fu << endl << setw( 12 ) << "Kilometer:" << ki << endl << setw( 12 ) << "Liniya:" << li << endl << setw( 12 ) << "Meter:" << me << endl << setw( 12 ) << "Milia:" << mi << endl << setw( 12 ) << "Piad:" << pi << endl << setw( 12 ) << "Sazhen:" << sa << endl << setw( 12 ) << "Tochka:" << to << endl << setw( 12 ) << "Vershok:" << ve << endl << setw( 12 ) << "Versta:" << vr << endl << endl << endl; } private: const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR; }; int _tmain(int argc, _TCHAR* argv[]) { ormConverter c; char s; float l; while( true ) { cout << "What unit:\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\n"; cin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0; cout << "Length (0 to Quit): "; cin >> l; if( l == 0 ) return 0; c.convert( s, l ); system( "pause" ); system( "cls" ); } return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
import java.util.function.Consumer; public class RateCounter { public static void main(String[] args) { for (double d : benchmark(10, x -> System.out.print(""), 10)) System.out.println(d); } static double[] benchmark(int n, Consumer<Integer> f, int arg) { double[] timings = new double[n]; for (int i = 0; i < n; i++) { long time = System.nanoTime(); f.accept(arg); timings[i] = System.nanoTime() - time; } return timings; } }
#include <iostream> #include <ctime> class CRateState { protected: time_t m_lastFlush; time_t m_period; size_t m_tickCount; public: CRateState(time_t period); void Tick(); }; CRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)), m_period(period), m_tickCount(0) { } void CRateState::Tick() { m_tickCount++; time_t now = std::time(NULL); if((now - m_lastFlush) >= m_period) { size_t tps = 0.0; if(m_tickCount > 0) tps = m_tickCount / (now - m_lastFlush); std::cout << tps << " tics per second" << std::endl; m_tickCount = 0; m_lastFlush = now; } } void something_we_do() { volatile size_t anchor = 0; for(size_t x = 0; x < 0xffff; ++x) { anchor = x; } } int main() { time_t start = std::time(NULL); CRateState rateWatch(5); for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL)) { something_we_do(); rateWatch.Tick(); } return 0; }
Rewrite the snippet below in C++ so it works the same as the original Java code.
public class AntiPrimesPlus { static int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (n % i == 0) { if (i == n / i) count++; else count += 2; } } return count; } public static void main(String[] args) { final int max = 15; System.out.printf("The first %d terms of the sequence are:\n", max); for (int i = 1, next = 1; next <= max; ++i) { if (next == count_divisors(i)) { System.out.printf("%d ", i); next++; } } System.out.println(); } }
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { cout << "The first " << MAX << " terms of the sequence are:" << endl; for (int i = 1, next = 1; next <= MAX; ++i) { if (next == count_divisors(i)) { cout << i << " "; next++; } } cout << endl; return 0; }
Ensure the translated C++ code behaves exactly like the original Java snippet.
import java.awt.*; import java.awt.geom.Path2D; import javax.swing.*; public class PythagorasTree extends JPanel { final int depthLimit = 7; float hue = 0.15f; public PythagorasTree() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); } private void drawTree(Graphics2D g, float x1, float y1, float x2, float y2, int depth) { if (depth == depthLimit) return; float dx = x2 - x1; float dy = y1 - y2; float x3 = x2 - dy; float y3 = y2 - dx; float x4 = x1 - dy; float y4 = y1 - dx; float x5 = x4 + 0.5F * (dx - dy); float y5 = y4 - 0.5F * (dx + dy); Path2D square = new Path2D.Float(); square.moveTo(x1, y1); square.lineTo(x2, y2); square.lineTo(x3, y3); square.lineTo(x4, y4); square.closePath(); g.setColor(Color.getHSBColor(hue + depth * 0.02f, 1, 1)); g.fill(square); g.setColor(Color.lightGray); g.draw(square); Path2D triangle = new Path2D.Float(); triangle.moveTo(x3, y3); triangle.lineTo(x4, y4); triangle.lineTo(x5, y5); triangle.closePath(); g.setColor(Color.getHSBColor(hue + depth * 0.035f, 1, 1)); g.fill(triangle); g.setColor(Color.lightGray); g.draw(triangle); drawTree(g, x4, y4, x5, y5, depth + 1); drawTree(g, x5, y5, x3, y3, depth + 1); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); drawTree((Graphics2D) g, 275, 500, 375, 500, 0); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Pythagoras Tree"); f.setResizable(false); f.add(new PythagorasTree(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100; 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( std::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 tree { public: tree() { bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear(); clr[0] = RGB( 90, 30, 0 ); clr[1] = RGB( 255, 255, 0 ); clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 ); clr[4] = RGB( 255, 0, 0 ); clr[5] = RGB( 0, 100, 190 ); } void draw( int it, POINT a, POINT b ) { if( !it ) return; bmp.setPenColor( clr[it % 6] ); POINT df = { b.x - a.x, a.y - b.y }; POINT c = { b.x - df.y, b.y - df.x }; POINT d = { a.x - df.y, a.y - df.x }; POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )}; drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c ); } void save( std::string p ) { bmp.saveBitmap( p ); } private: void drawSqr( POINT a, POINT b, POINT c, POINT d ) { HDC dc = bmp.getDC(); MoveToEx( dc, a.x, a.y, NULL ); LineTo( dc, b.x, b.y ); LineTo( dc, c.x, c.y ); LineTo( dc, d.x, d.y ); LineTo( dc, a.x, a.y ); } myBitmap bmp; DWORD clr[6]; }; int main( int argc, char* argv[] ) { POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER }, ptB = { ptA.x + LINE_LEN, ptA.y }; tree t; t.draw( 12, ptA, ptB ); t.save( "?:/pt.bmp" ); return 0; }
Port the following code from Java to C++ with equivalent syntax and logic.
public class OddWord { interface CharHandler { CharHandler handle(char c) throws Exception; } final CharHandler fwd = new CharHandler() { public CharHandler handle(char c) { System.out.print(c); return (Character.isLetter(c) ? fwd : rev); } }; class Reverser extends Thread implements CharHandler { Reverser() { setDaemon(true); start(); } private Character ch; private char recur() throws Exception { notify(); while (ch == null) wait(); char c = ch, ret = c; ch = null; if (Character.isLetter(c)) { ret = recur(); System.out.print(c); } return ret; } public synchronized void run() { try { while (true) { System.out.print(recur()); notify(); } } catch (Exception e) {} } public synchronized CharHandler handle(char c) throws Exception { while (ch != null) wait(); ch = c; notify(); while (ch != null) wait(); return (Character.isLetter(c) ? rev : fwd); } } final CharHandler rev = new Reverser(); public void loop() throws Exception { CharHandler handler = fwd; int c; while ((c = System.in.read()) >= 0) { handler = handler.handle((char) c); } } public static void main(String[] args) throws Exception { new OddWord().loop(); } }
#include <iostream> #include <cctype> #include <functional> using namespace std; bool odd() { function<void ()> prev = []{}; while(true) { int c = cin.get(); if (!isalpha(c)) { prev(); cout.put(c); return c != '.'; } prev = [=] { cout.put(c); prev(); }; } } bool even() { while(true) { int c; cout.put(c = cin.get()); if (!isalpha(c)) return c != '.'; } } int main() { bool e = false; while( e ? odd() : even() ) e = !e; return 0; }
Transform the following Java implementation into C++, maintaining the same output and logic.
public class App { private static long mod(long x, long y) { long m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } public static class RNG { private final long[] a1 = {0, 1403580, -810728}; private static final long m1 = (1L << 32) - 209; private long[] x1; private final long[] a2 = {527612, 0, -1370589}; private static final long m2 = (1L << 32) - 22853; private long[] x2; private static final long d = m1 + 1; public void seed(long state) { x1 = new long[]{state, 0, 0}; x2 = new long[]{state, 0, 0}; } public long nextInt() { long x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1); long x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2); long z = mod(x1i - x2i, m1); x1 = new long[]{x1i, x1[0], x1[1]}; x2 = new long[]{x2i, x2[0], x2[1]}; return z + 1; } public double nextFloat() { return 1.0 * nextInt() / d; } } public static void main(String[] args) { RNG rng = new RNG(); rng.seed(1234567); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(rng.nextInt()); System.out.println(); int[] counts = {0, 0, 0, 0, 0}; rng.seed(987654321); for (int i = 0; i < 100_000; i++) { int value = (int) Math.floor(rng.nextFloat() * 5.0); counts[value]++; } for (int i = 0; i < counts.length; i++) { System.out.printf("%d: %d%n", i, counts[i]); } } }
#include <array> #include <iostream> int64_t mod(int64_t x, int64_t y) { int64_t m = x % y; if (m < 0) { if (y < 0) { return m - y; } else { return m + y; } } return m; } class RNG { private: const std::array<int64_t, 3> a1{ 0, 1403580, -810728 }; const int64_t m1 = (1LL << 32) - 209; std::array<int64_t, 3> x1; const std::array<int64_t, 3> a2{ 527612, 0, -1370589 }; const int64_t m2 = (1LL << 32) - 22853; std::array<int64_t, 3> x2; const int64_t d = (1LL << 32) - 209 + 1; public: void seed(int64_t state) { x1 = { state, 0, 0 }; x2 = { state, 0, 0 }; } int64_t next_int() { int64_t x1i = mod((a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2]), m1); int64_t x2i = mod((a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2]), m2); int64_t z = mod(x1i - x2i, m1); x1 = { x1i, x1[0], x1[1] }; x2 = { x2i, x2[0], x2[1] }; return z + 1; } double next_float() { return static_cast<double>(next_int()) / d; } }; int main() { RNG rng; rng.seed(1234567); std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << rng.next_int() << '\n'; std::cout << '\n'; std::array<int, 5> counts{ 0, 0, 0, 0, 0 }; rng.seed(987654321); for (size_t i = 0; i < 100000; i++) { auto value = floor(rng.next_float() * 5.0); counts[value]++; } for (size_t i = 0; i < counts.size(); i++) { std::cout << i << ": " << counts[i] << '\n'; } return 0; }
Produce a language-to-language conversion: from Java to C++, same semantics.
import java.math.BigInteger; import java.util.LinkedList; public class SternBrocot { static LinkedList<Integer> sequence = new LinkedList<Integer>(){{ add(1); add(1); }}; private static void genSeq(int n){ for(int conIdx = 1; sequence.size() < n; conIdx++){ int consider = sequence.get(conIdx); int pre = sequence.get(conIdx - 1); sequence.add(consider + pre); sequence.add(consider); } } public static void main(String[] args){ genSeq(1200); System.out.println("The first 15 elements are: " + sequence.subList(0, 15)); for(int i = 1; i <= 10; i++){ System.out.println("First occurrence of " + i + " is at " + (sequence.indexOf(i) + 1)); } System.out.println("First occurrence of 100 is at " + (sequence.indexOf(100) + 1)); boolean failure = false; for(int i = 0; i < 999; i++){ failure |= !BigInteger.valueOf(sequence.get(i)).gcd(BigInteger.valueOf(sequence.get(i + 1))).equals(BigInteger.ONE); } System.out.println("All GCDs are" + (failure ? " not" : "") + " 1"); } }
#include <iostream> #include <iomanip> #include <algorithm> #include <vector> unsigned gcd( unsigned i, unsigned j ) { return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j; } void createSequence( std::vector<unsigned>& seq, int c ) { if( 1500 == seq.size() ) return; unsigned t = seq.at( c ) + seq.at( c + 1 ); seq.push_back( t ); seq.push_back( seq.at( c + 1 ) ); createSequence( seq, c + 1 ); } int main( int argc, char* argv[] ) { std::vector<unsigned> seq( 2, 1 ); createSequence( seq, 0 ); std::cout << "First fifteen members of the sequence:\n "; for( unsigned x = 0; x < 15; x++ ) { std::cout << seq[x] << " "; } std::cout << "\n\n"; for( unsigned x = 1; x < 11; x++ ) { std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x ); if( i != seq.end() ) { std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } } std::cout << "\n"; std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 ); if( i != seq.end() ) { std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; } std::cout << "\n"; unsigned g; bool f = false; for( int x = 0, y = 1; x < 1000; x++, y++ ) { g = gcd( seq[x], seq[y] ); if( g != 1 ) f = true; std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", " << seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" ); } std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n"; return 0; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
public class Approx { private double value; private double error; public Approx(){this.value = this.error = 0;} public Approx(Approx b){ this.value = b.value; this.error = b.error; } public Approx(double value, double error){ this.value = value; this.error = error; } public Approx add(Approx b){ value+= b.value; error = Math.sqrt(error * error + b.error * b.error); return this; } public Approx add(double b){ value+= b; return this; } public Approx sub(Approx b){ value-= b.value; error = Math.sqrt(error * error + b.error * b.error); return this; } public Approx sub(double b){ value-= b; return this; } public Approx mult(Approx b){ double oldVal = value; value*= b.value; error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + (b.error*b.error) / (b.value*b.value)); return this; } public Approx mult(double b){ value*= b; error = Math.abs(b * error); return this; } public Approx div(Approx b){ double oldVal = value; value/= b.value; error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + (b.error*b.error) / (b.value*b.value)); return this; } public Approx div(double b){ value/= b; error = Math.abs(b * error); return this; } public Approx pow(double b){ double oldVal = value; value = Math.pow(value, b); error = Math.abs(value * b * (error / oldVal)); return this; } @Override public String toString(){return value+"±"+error;} public static void main(String[] args){ Approx x1 = new Approx(100, 1.1); Approx y1 = new Approx(50, 1.2); Approx x2 = new Approx(200, 2.2); Approx y2 = new Approx(100, 2.3); x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5); System.out.println(x1); } }
#pragma once #include <cmath> #include <string> #include <sstream> #include <iomanip> class Approx { public: Approx(double _v, double _s = 0.0) : v(_v), s(_s) {} operator std::string() const { std::ostringstream os(""); os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s << std::ends; return os.str(); } Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); } Approx operator +(double d) const { return Approx(v + d, s); } Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); } Approx operator -(double d) const { return Approx(v - d, s); } Approx operator *(const Approx& a) const { const double t = v * a.v; return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); } Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); } Approx operator /(const Approx& a) const { const double t = v / a.v; return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); } Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); } Approx pow(double d) const { const double t = ::pow(v, d); return Approx(t, fabs(t * d * s / v)); } private: double v, s; };
Port the provided Java code into C++ while preserving the original functionality.
public class Approx { private double value; private double error; public Approx(){this.value = this.error = 0;} public Approx(Approx b){ this.value = b.value; this.error = b.error; } public Approx(double value, double error){ this.value = value; this.error = error; } public Approx add(Approx b){ value+= b.value; error = Math.sqrt(error * error + b.error * b.error); return this; } public Approx add(double b){ value+= b; return this; } public Approx sub(Approx b){ value-= b.value; error = Math.sqrt(error * error + b.error * b.error); return this; } public Approx sub(double b){ value-= b; return this; } public Approx mult(Approx b){ double oldVal = value; value*= b.value; error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + (b.error*b.error) / (b.value*b.value)); return this; } public Approx mult(double b){ value*= b; error = Math.abs(b * error); return this; } public Approx div(Approx b){ double oldVal = value; value/= b.value; error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) + (b.error*b.error) / (b.value*b.value)); return this; } public Approx div(double b){ value/= b; error = Math.abs(b * error); return this; } public Approx pow(double b){ double oldVal = value; value = Math.pow(value, b); error = Math.abs(value * b * (error / oldVal)); return this; } @Override public String toString(){return value+"±"+error;} public static void main(String[] args){ Approx x1 = new Approx(100, 1.1); Approx y1 = new Approx(50, 1.2); Approx x2 = new Approx(200, 2.2); Approx y2 = new Approx(100, 2.3); x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5); System.out.println(x1); } }
#pragma once #include <cmath> #include <string> #include <sstream> #include <iomanip> class Approx { public: Approx(double _v, double _s = 0.0) : v(_v), s(_s) {} operator std::string() const { std::ostringstream os(""); os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s << std::ends; return os.str(); } Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); } Approx operator +(double d) const { return Approx(v + d, s); } Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); } Approx operator -(double d) const { return Approx(v - d, s); } Approx operator *(const Approx& a) const { const double t = v * a.v; return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); } Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); } Approx operator /(const Approx& a) const { const double t = v / a.v; return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v))); } Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); } Approx pow(double d) const { const double t = ::pow(v, d); return Approx(t, fabs(t * d * s / v)); } private: double v, s; };
Port the following code from Java to C++ with equivalent syntax and logic.
import java.util.ArrayList; import java.util.List; public class ListRootedTrees { private static final List<Long> TREE_LIST = new ArrayList<>(); private static final List<Integer> OFFSET = new ArrayList<>(); static { for (int i = 0; i < 32; i++) { if (i == 1) { OFFSET.add(1); } else { OFFSET.add(0); } } } private static void append(long t) { TREE_LIST.add(1 | (t << 1)); } private static void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { System.out.print('('); } else { System.out.print(')'); } t = t >> 1; } } private static void listTrees(int n) { for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) { show(TREE_LIST.get(i), n * 2); System.out.println(); } } private static void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } var pp = pos; var ss = sl; if (sl > rem) { ss = rem; pp = OFFSET.get(ss); } else if (pp >= OFFSET.get(ss + 1)) { ss--; if (ss == 0) { return; } pp = OFFSET.get(ss); } assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } private static void makeTrees(int n) { if (OFFSET.get(n + 1) != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1); OFFSET.set(n + 1, TREE_LIST.size()); } private static void test(int n) { if (n < 1 || n > 12) { throw new IllegalArgumentException("Argument must be between 1 and 12"); } append(0); makeTrees(n); System.out.printf("Number of %d-trees: %d\n", n, OFFSET.get(n + 1) - OFFSET.get(n)); listTrees(n); } public static void main(String[] args) { test(5); } }
#include <iostream> #include <vector> std::vector<long> TREE_LIST; std::vector<int> OFFSET; void init() { for (size_t i = 0; i < 32; i++) { if (i == 1) { OFFSET.push_back(1); } else { OFFSET.push_back(0); } } } void append(long t) { TREE_LIST.push_back(1 | (t << 1)); } void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { std::cout << '('; } else { std::cout << ')'; } t = t >> 1; } } void listTrees(int n) { for (int i = OFFSET[n]; i < OFFSET[n + 1]; i++) { show(TREE_LIST[i], 2 * n); std::cout << '\n'; } } void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } auto pp = pos; auto ss = sl; if (sl > rem) { ss = rem; pp = OFFSET[ss]; } else if (pp >= OFFSET[ss + 1]) { ss--; if (ss == 0) { return; } pp = OFFSET[ss]; } assemble(n, t << (2 * ss) | TREE_LIST[pp], ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } void makeTrees(int n) { if (OFFSET[n + 1] != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET[n - 1], n - 1); OFFSET[n + 1] = TREE_LIST.size(); } void test(int n) { if (n < 1 || n > 12) { throw std::runtime_error("Argument must be between 1 and 12"); } append(0); makeTrees(n); std::cout << "Number of " << n << "-trees: " << OFFSET[n + 1] - OFFSET[n] << '\n'; listTrees(n); } int main() { init(); test(5); return 0; }
Ensure the translated C++ code behaves exactly like the original Java snippet.
import java.util.List; public class App { private static String lcs(List<String> a) { var le = a.size(); if (le == 0) { return ""; } if (le == 1) { return a.get(0); } var le0 = a.get(0).length(); var minLen = le0; for (int i = 1; i < le; i++) { if (a.get(i).length() < minLen) { minLen = a.get(i).length(); } } if (minLen == 0) { return ""; } var res = ""; var a1 = a.subList(1, a.size()); for (int i = 1; i < minLen; i++) { var suffix = a.get(0).substring(le0 - i); for (String e : a1) { if (!e.endsWith(suffix)) { return res; } } res = suffix; } return ""; } public static void main(String[] args) { var tests = List.of( List.of("baabababc", "baabc", "bbbabc"), List.of("baabababc", "baabc", "bbbazc"), List.of("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"), List.of("longest", "common", "suffix"), List.of("suffix"), List.of("") ); for (List<String> test : tests) { System.out.printf("%s -> `%s`\n", test, lcs(test)); } } }
#include <iostream> #include <string> #include <vector> #include <algorithm> std::string lcs(const std::vector<std::string>& strs) { std::vector<std::string::const_reverse_iterator> backs; std::string s; if (strs.size() == 0) return ""; if (strs.size() == 1) return strs[0]; for (auto& str : strs) backs.push_back(str.crbegin()); while (backs[0] != strs[0].crend()) { char ch = *backs[0]++; for (std::size_t i = 1; i<strs.size(); i++) { if (backs[i] == strs[i].crend()) goto done; if (*backs[i] != ch) goto done; backs[i]++; } s.push_back(ch); } done: reverse(s.begin(), s.end()); return s; } void test(const std::vector<std::string>& strs) { std::cout << "["; for (std::size_t i = 0; i<strs.size(); i++) { std::cout << '"' << strs[i] << '"'; if (i != strs.size()-1) std::cout << ", "; } std::cout << "] -> `" << lcs(strs) << "`\n"; } int main() { std::vector<std::string> t1 = {"baabababc", "baabc", "bbabc"}; std::vector<std::string> t2 = {"baabababc", "baabc", "bbazc"}; std::vector<std::string> t3 = {"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"}; std::vector<std::string> t4 = {"longest", "common", "suffix"}; std::vector<std::string> t5 = {""}; std::vector<std::string> t6 = {}; std::vector<std::string> t7 = {"foo", "foo", "foo", "foo"}; std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7}; for (auto t : tests) test(t); return 0; }
Write a version of this Java function in C++ with identical behavior.
public static void main(String[] args) { int[][] matrix = {{1, 3, 7, 8, 10}, {2, 4, 16, 14, 4}, {3, 1, 9, 18, 11}, {12, 14, 17, 18, 20}, {7, 1, 3, 9, 5}}; int sum = 0; for (int row = 1; row < matrix.length; row++) { for (int col = 0; col < row; col++) { sum += matrix[row][col]; } } System.out.println(sum); }
#include <iostream> #include <vector> template<typename T> T sum_below_diagonal(const std::vector<std::vector<T>>& matrix) { T sum = 0; for (std::size_t y = 0; y < matrix.size(); y++) for (std::size_t x = 0; x < matrix[y].size() && x < y; x++) sum += matrix[y][x]; return sum; } int main() { std::vector<std::vector<int>> matrix = { {1,3,7,8,10}, {2,4,16,14,4}, {3,1,9,18,11}, {12,14,17,18,20}, {7,1,3,9,5} }; std::cout << sum_below_diagonal(matrix) << std::endl; return 0; }
Can you help me rewrite this code in C++ instead of Java, keeping it the same logically?
import java.io.*; import java.util.Scanner; public class ReadFastaFile { public static void main(String[] args) throws FileNotFoundException { boolean first = true; try (Scanner sc = new Scanner(new File("test.fasta"))) { while (sc.hasNextLine()) { String line = sc.nextLine().trim(); if (line.charAt(0) == '>') { if (first) first = false; else System.out.println(); System.out.printf("%s: ", line.substring(1)); } else { System.out.print(line); } } } System.out.println(); } }
#include <iostream> #include <fstream> int main( int argc, char **argv ){ if( argc <= 1 ){ std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl; return -1; } std::ifstream input(argv[1]); if(!input.good()){ std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << std::endl; return -1; } std::string line, name, content; while( std::getline( input, line ).good() ){ if( line.empty() || line[0] == '>' ){ if( !name.empty() ){ std::cout << name << " : " << content << std::endl; name.clear(); } if( !line.empty() ){ name = line.substr(1); } content.clear(); } else if( !name.empty() ){ if( line.find(' ') != std::string::npos ){ name.clear(); content.clear(); } else { content += line; } } } if( !name.empty() ){ std::cout << name << " : " << content << std::endl; } return 0; }
Write a version of this Java function in C++ with identical behavior.
public class PCG32 { private static final long N = 6364136223846793005L; private long state = 0x853c49e6748fea9bL; private long inc = 0xda3e39cb94b95bdbL; public void seed(long seedState, long seedSequence) { state = 0; inc = (seedSequence << 1) | 1; nextInt(); state = state + seedState; nextInt(); } public int nextInt() { long old = state; state = old * N + inc; int shifted = (int) (((old >>> 18) ^ old) >>> 27); int rot = (int) (old >>> 59); return (shifted >>> rot) | (shifted << ((~rot + 1) & 31)); } public double nextFloat() { var u = Integer.toUnsignedLong(nextInt()); return (double) u / (1L << 32); } public static void main(String[] args) { var r = new PCG32(); r.seed(42, 54); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(Integer.toUnsignedString(r.nextInt())); System.out.println(); int[] counts = {0, 0, 0, 0, 0}; r.seed(987654321, 1); for (int i = 0; i < 100_000; i++) { int j = (int) Math.floor(r.nextFloat() * 5.0); counts[j]++; } System.out.println("The counts for 100,000 repetitions are:"); for (int i = 0; i < counts.length; i++) { System.out.printf(" %d : %d\n", i, counts[i]); } } }
#include <array> #include <iostream> class PCG32 { private: const uint64_t N = 6364136223846793005; uint64_t state = 0x853c49e6748fea9b; uint64_t inc = 0xda3e39cb94b95bdb; public: uint32_t nextInt() { uint64_t old = state; state = old * N + inc; uint32_t shifted = (uint32_t)(((old >> 18) ^ old) >> 27); uint32_t rot = old >> 59; return (shifted >> rot) | (shifted << ((~rot + 1) & 31)); } double nextFloat() { return ((double)nextInt()) / (1LL << 32); } void seed(uint64_t seed_state, uint64_t seed_sequence) { state = 0; inc = (seed_sequence << 1) | 1; nextInt(); state = state + seed_state; nextInt(); } }; int main() { auto r = new PCG32(); r->seed(42, 54); std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << r->nextInt() << '\n'; std::cout << '\n'; std::array<int, 5> counts{ 0, 0, 0, 0, 0 }; r->seed(987654321, 1); for (size_t i = 0; i < 100000; i++) { int j = (int)floor(r->nextFloat() * 5.0); counts[j]++; } std::cout << "The counts for 100,000 repetitions are:\n"; for (size_t i = 0; i < counts.size(); i++) { std::cout << " " << i << " : " << counts[i] << '\n'; } return 0; }
Generate an equivalent C++ version of this Java code.
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.Path2D; import static java.lang.Math.*; import java.util.Random; import javax.swing.*; public class SierpinskiPentagon extends JPanel { final double degrees072 = toRadians(72); final double scaleFactor = 1 / (2 + cos(degrees072) * 2); final int margin = 20; int limit = 0; Random r = new Random(); public SierpinskiPentagon() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); new Timer(3000, (ActionEvent e) -> { limit++; if (limit >= 5) limit = 0; repaint(); }).start(); } void drawPentagon(Graphics2D g, double x, double y, double side, int depth) { double angle = 3 * degrees072; if (depth == 0) { Path2D p = new Path2D.Double(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { x = x + cos(angle) * side; y = y - sin(angle) * side; p.lineTo(x, y); angle += degrees072; } g.setColor(RandomHue.next()); g.fill(p); } else { side *= scaleFactor; double distance = side + side * cos(degrees072) * 2; for (int i = 0; i < 5; i++) { x = x + cos(angle) * distance; y = y - sin(angle) * distance; drawPentagon(g, x, y, side, depth - 1); angle += degrees072; } } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int w = getWidth(); double radius = w / 2 - 2 * margin; double side = radius * sin(PI / 5) * 2; drawPentagon(g, w / 2, 3 * margin, side, limit); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Sierpinski Pentagon"); f.setResizable(true); f.add(new SierpinskiPentagon(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } } class RandomHue { final static double goldenRatioConjugate = (sqrt(5) - 1) / 2; private static double hue = Math.random(); static Color next() { hue = (hue + goldenRatioConjugate) % 1; return Color.getHSBColor((float) hue, 1, 1); } }
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { double x, y; friend std::ostream& operator<<(std::ostream& os, const Point& p); }; std::ostream& operator<<(std::ostream& os, const Point& p) { auto f(std::cout.flags()); os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' '; std::cout.flags(f); return os; } struct Turtle { private: Point pos; double theta; bool tracing; public: Turtle() : theta(0.0), tracing(false) { pos.x = 0.0; pos.y = 0.0; } Turtle(double x, double y) : theta(0.0), tracing(false) { pos.x = x; pos.y = y; } Point position() { return pos; } void position(const Point& p) { pos = p; } double heading() { return theta; } void heading(double angle) { theta = angle; } void forward(double dist) { auto dx = dist * cos(theta); auto dy = dist * sin(theta); pos.x += dx; pos.y += dy; if (tracing) { std::cout << pos; } } void right(double angle) { theta -= angle; } void begin_fill() { if (!tracing) { std::cout << "<polygon points=\""; tracing = true; } } void end_fill() { if (tracing) { std::cout << "\"/>\n"; tracing = false; } } }; void pentagon(Turtle& turtle, double size) { turtle.right(degrees(36)); turtle.begin_fill(); for (size_t i = 0; i < 5; i++) { turtle.forward(size); turtle.right(degrees(72)); } turtle.end_fill(); } void sierpinski(int order, Turtle& turtle, double size) { turtle.heading(0.0); auto new_size = size * side_ratio; if (order-- > 1) { for (size_t j = 0; j < 4; j++) { turtle.right(degrees(36)); double small = size * side_ratio / part_ratio; auto distList = { small, size, size, small }; auto dist = *(distList.begin() + j); Turtle spawn{ turtle.position().x, turtle.position().y }; spawn.heading(turtle.heading()); spawn.forward(dist); sierpinski(order, spawn, new_size); } sierpinski(order, turtle, new_size); } else { pentagon(turtle, size); } if (order > 0) { std::cout << '\n'; } } int main() { const int order = 5; double size = 500; Turtle turtle{ size / 2.0, size }; std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n"; std::cout << "<!DOCTYPE svg PUBLIC \" - std::cout << " \"http: std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n"; std::cout << " version=\"1.1\" xmlns=\"http: size *= part_ratio; sierpinski(order, turtle, size); std::cout << "</svg>"; }
Preserve the algorithm and functionality while converting the code from Java to C++.
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.Path2D; import static java.lang.Math.*; import java.util.Random; import javax.swing.*; public class SierpinskiPentagon extends JPanel { final double degrees072 = toRadians(72); final double scaleFactor = 1 / (2 + cos(degrees072) * 2); final int margin = 20; int limit = 0; Random r = new Random(); public SierpinskiPentagon() { setPreferredSize(new Dimension(640, 640)); setBackground(Color.white); new Timer(3000, (ActionEvent e) -> { limit++; if (limit >= 5) limit = 0; repaint(); }).start(); } void drawPentagon(Graphics2D g, double x, double y, double side, int depth) { double angle = 3 * degrees072; if (depth == 0) { Path2D p = new Path2D.Double(); p.moveTo(x, y); for (int i = 0; i < 5; i++) { x = x + cos(angle) * side; y = y - sin(angle) * side; p.lineTo(x, y); angle += degrees072; } g.setColor(RandomHue.next()); g.fill(p); } else { side *= scaleFactor; double distance = side + side * cos(degrees072) * 2; for (int i = 0; i < 5; i++) { x = x + cos(angle) * distance; y = y - sin(angle) * distance; drawPentagon(g, x, y, side, depth - 1); angle += degrees072; } } } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int w = getWidth(); double radius = w / 2 - 2 * margin; double side = radius * sin(PI / 5) * 2; drawPentagon(g, w / 2, 3 * margin, side, limit); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Sierpinski Pentagon"); f.setResizable(true); f.add(new SierpinskiPentagon(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } } class RandomHue { final static double goldenRatioConjugate = (sqrt(5) - 1) / 2; private static double hue = Math.random(); static Color next() { hue = (hue + goldenRatioConjugate) % 1; return Color.getHSBColor((float) hue, 1, 1); } }
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { double x, y; friend std::ostream& operator<<(std::ostream& os, const Point& p); }; std::ostream& operator<<(std::ostream& os, const Point& p) { auto f(std::cout.flags()); os << std::setprecision(3) << std::fixed << p.x << ',' << p.y << ' '; std::cout.flags(f); return os; } struct Turtle { private: Point pos; double theta; bool tracing; public: Turtle() : theta(0.0), tracing(false) { pos.x = 0.0; pos.y = 0.0; } Turtle(double x, double y) : theta(0.0), tracing(false) { pos.x = x; pos.y = y; } Point position() { return pos; } void position(const Point& p) { pos = p; } double heading() { return theta; } void heading(double angle) { theta = angle; } void forward(double dist) { auto dx = dist * cos(theta); auto dy = dist * sin(theta); pos.x += dx; pos.y += dy; if (tracing) { std::cout << pos; } } void right(double angle) { theta -= angle; } void begin_fill() { if (!tracing) { std::cout << "<polygon points=\""; tracing = true; } } void end_fill() { if (tracing) { std::cout << "\"/>\n"; tracing = false; } } }; void pentagon(Turtle& turtle, double size) { turtle.right(degrees(36)); turtle.begin_fill(); for (size_t i = 0; i < 5; i++) { turtle.forward(size); turtle.right(degrees(72)); } turtle.end_fill(); } void sierpinski(int order, Turtle& turtle, double size) { turtle.heading(0.0); auto new_size = size * side_ratio; if (order-- > 1) { for (size_t j = 0; j < 4; j++) { turtle.right(degrees(36)); double small = size * side_ratio / part_ratio; auto distList = { small, size, size, small }; auto dist = *(distList.begin() + j); Turtle spawn{ turtle.position().x, turtle.position().y }; spawn.heading(turtle.heading()); spawn.forward(dist); sierpinski(order, spawn, new_size); } sierpinski(order, turtle, new_size); } else { pentagon(turtle, size); } if (order > 0) { std::cout << '\n'; } } int main() { const int order = 5; double size = 500; Turtle turtle{ size / 2.0, size }; std::cout << "<?xml version=\"1.0\" standalone=\"no\"?>\n"; std::cout << "<!DOCTYPE svg PUBLIC \" - std::cout << " \"http: std::cout << "<svg height=\"" << size << "\" width=\"" << size << "\" style=\"fill:blue\" transform=\"translate(" << size / 2 << ", " << size / 2 << ") rotate(-36)\"\n"; std::cout << " version=\"1.1\" xmlns=\"http: size *= part_ratio; sierpinski(order, turtle, size); std::cout << "</svg>"; }
Port the provided Java code into C++ while preserving the original functionality.
public class RepString { static final String[] input = {"1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", "0100101"}; public static void main(String[] args) { for (String s : input) System.out.printf("%s : %s%n", s, repString(s)); } static String repString(String s) { int len = s.length(); outer: for (int part = len / 2; part > 0; part--) { int tail = len % part; if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail))) continue; for (int j = 0; j < len / part - 1; j++) { int a = j * part; int b = (j + 1) * part; int c = (j + 2) * part; if (!s.substring(a, b).equals(s.substring(b, c))) continue outer; } return s.substring(0, part); } return "none"; } }
#include <string> #include <vector> #include <boost/regex.hpp> bool is_repstring( const std::string & teststring , std::string & repunit ) { std::string regex( "^(.+)\\1+(.*)$" ) ; boost::regex e ( regex ) ; boost::smatch what ; if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) { std::string firstbracket( what[1 ] ) ; std::string secondbracket( what[ 2 ] ) ; if ( firstbracket.length( ) >= secondbracket.length( ) && firstbracket.find( secondbracket ) != std::string::npos ) { repunit = firstbracket ; } } return !repunit.empty( ) ; } int main( ) { std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" , "1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ; std::string theRep ; for ( std::string myString : teststrings ) { if ( is_repstring( myString , theRep ) ) { std::cout << myString << " is a rep string! Here is a repeating string:\n" ; std::cout << theRep << " " ; } else { std::cout << myString << " is no rep string!" ; } theRep.clear( ) ; std::cout << std::endl ; } return 0 ; }
Convert this Java snippet to C++ and keep its semantics consistent.
public class RepString { static final String[] input = {"1001110011", "1110111011", "0010010010", "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1", "0100101"}; public static void main(String[] args) { for (String s : input) System.out.printf("%s : %s%n", s, repString(s)); } static String repString(String s) { int len = s.length(); outer: for (int part = len / 2; part > 0; part--) { int tail = len % part; if (tail > 0 && !s.substring(0, tail).equals(s.substring(len - tail))) continue; for (int j = 0; j < len / part - 1; j++) { int a = j * part; int b = (j + 1) * part; int c = (j + 2) * part; if (!s.substring(a, b).equals(s.substring(b, c))) continue outer; } return s.substring(0, part); } return "none"; } }
#include <string> #include <vector> #include <boost/regex.hpp> bool is_repstring( const std::string & teststring , std::string & repunit ) { std::string regex( "^(.+)\\1+(.*)$" ) ; boost::regex e ( regex ) ; boost::smatch what ; if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) { std::string firstbracket( what[1 ] ) ; std::string secondbracket( what[ 2 ] ) ; if ( firstbracket.length( ) >= secondbracket.length( ) && firstbracket.find( secondbracket ) != std::string::npos ) { repunit = firstbracket ; } } return !repunit.empty( ) ; } int main( ) { std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" , "1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ; std::string theRep ; for ( std::string myString : teststrings ) { if ( is_repstring( myString , theRep ) ) { std::cout << myString << " is a rep string! Here is a repeating string:\n" ; std::cout << theRep << " " ; } else { std::cout << myString << " is no rep string!" ; } theRep.clear( ) ; std::cout << std::endl ; } return 0 ; }
Produce a language-to-language conversion: from Java to C++, same semantics.
char a = 'a'; String b = "abc"; char doubleQuote = '"'; char singleQuote = '\''; String singleQuotes = "''"; String doubleQuotes = "\"\"";
auto strA = R"(this is a newline-separated raw string)";
Write the same code in C++ as shown below in Java.
import java.io.*; import java.util.*; public class ChangeableWords { public static void main(String[] args) { try { final String fileName = "unixdict.txt"; List<String> dictionary = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String line; while ((line = reader.readLine()) != null) { if (line.length() > 11) dictionary.add(line); } } System.out.printf("Changeable words in %s:\n", fileName); int n = 1; for (String word1 : dictionary) { for (String word2 : dictionary) { if (word1 != word2 && hammingDistance(word1, word2) == 1) System.out.printf("%2d: %-14s -> %s\n", n++, word1, word2); } } } catch (Exception e) { e.printStackTtexture(); } } private static int hammingDistance(String str1, String str2) { int len1 = str1.length(); int len2 = str2.length(); if (len1 != len2) return 0; int count = 0; for (int i = 0; i < len1; ++i) { if (str1.charAt(i) != str2.charAt(i)) ++count; if (count == 2) break; } return count; } }
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include <vector> int hamming_distance(const std::string& str1, const std::string& str2) { size_t len1 = str1.size(); size_t len2 = str2.size(); if (len1 != len2) return 0; int count = 0; for (size_t i = 0; i < len1; ++i) { if (str1[i] != str2[i]) ++count; if (count == 2) break; } return count; } int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string line; std::vector<std::string> dictionary; while (getline(in, line)) { if (line.size() > 11) dictionary.push_back(line); } std::cout << "Changeable words in " << filename << ":\n"; int n = 1; for (const std::string& word1 : dictionary) { for (const std::string& word2 : dictionary) { if (hamming_distance(word1, word2) == 1) std::cout << std::setw(2) << std::right << n++ << ": " << std::setw(14) << std::left << word1 << " -> " << word2 << '\n'; } } return EXIT_SUCCESS; }
Convert this Java snippet to C++ and keep its semantics consistent.
public class FourIsMagic { public static void main(String[] args) { for ( long n : new long[] {6, 60, 89, 300, 670, 2000, 2467, 20000, 24500,200000, 230000, 246571, 2300000, 2465712, 20000000, 24657123, 230000000, 245000000, -246570000, 123456789712345l, 8777777777777777777L, Long.MAX_VALUE}) { String magic = fourIsMagic(n); System.out.printf("%d = %s%n", n, toSentence(magic)); } } private static final String toSentence(String s) { return s.substring(0,1).toUpperCase() + s.substring(1) + "."; } private static final String[] nums = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; private static final String[] tens = new String[] {"zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"}; private static final String fourIsMagic(long n) { if ( n == 4 ) { return numToString(n) + " is magic"; } String result = numToString(n); return result + " is " + numToString(result.length()) + ", " + fourIsMagic(result.length()); } private static final String numToString(long n) { if ( n < 0 ) { return "negative " + numToString(-n); } int index = (int) n; if ( n <= 19 ) { return nums[index]; } if ( n <= 99 ) { return tens[index/10] + (n % 10 > 0 ? " " + numToString(n % 10) : ""); } String label = null; long factor = 0; if ( n <= 999 ) { label = "hundred"; factor = 100; } else if ( n <= 999999) { label = "thousand"; factor = 1000; } else if ( n <= 999999999) { label = "million"; factor = 1000000; } else if ( n <= 999999999999L) { label = "billion"; factor = 1000000000; } else if ( n <= 999999999999999L) { label = "trillion"; factor = 1000000000000L; } else if ( n <= 999999999999999999L) { label = "quadrillion"; factor = 1000000000000000L; } else { label = "quintillion"; factor = 1000000000000000000L; } return numToString(n / factor) + " " + label + (n % factor > 0 ? " " + numToString(n % factor ) : ""); } }
#include <iostream> #include <string> #include <cctype> #include <cstdint> typedef std::uint64_t integer; const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" }; const char* tens[] = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" }; struct named_number { const char* name_; integer number_; }; const named_number named_numbers[] = { { "hundred", 100 }, { "thousand", 1000 }, { "million", 1000000 }, { "billion", 1000000000 }, { "trillion", 1000000000000 }, { "quadrillion", 1000000000000000ULL }, { "quintillion", 1000000000000000000ULL } }; const named_number& get_named_number(integer n) { constexpr size_t names_len = std::size(named_numbers); for (size_t i = 0; i + 1 < names_len; ++i) { if (n < named_numbers[i + 1].number_) return named_numbers[i]; } return named_numbers[names_len - 1]; } std::string cardinal(integer n) { std::string result; if (n < 20) result = small[n]; else if (n < 100) { result = tens[n/10 - 2]; if (n % 10 != 0) { result += "-"; result += small[n % 10]; } } else { const named_number& num = get_named_number(n); integer p = num.number_; result = cardinal(n/p); result += " "; result += num.name_; if (n % p != 0) { result += " "; result += cardinal(n % p); } } return result; } inline char uppercase(char ch) { return static_cast<char>(std::toupper(static_cast<unsigned char>(ch))); } std::string magic(integer n) { std::string result; for (unsigned int i = 0; ; ++i) { std::string text(cardinal(n)); if (i == 0) text[0] = uppercase(text[0]); result += text; if (n == 4) { result += " is magic."; break; } integer len = text.length(); result += " is "; result += cardinal(len); result += ", "; n = len; } return result; } void test_magic(integer n) { std::cout << magic(n) << '\n'; } int main() { test_magic(5); test_magic(13); test_magic(78); test_magic(797); test_magic(2739); test_magic(4000); test_magic(7893); test_magic(93497412); test_magic(2673497412U); test_magic(10344658531277200972ULL); return 0; }
Port the following code from Java to C++ with equivalent syntax and logic.
public static int findNumOfDec(double x){ String str = String.valueOf(x); if(str.endsWith(".0")) return 0; else return (str.substring(str.indexOf('.')).length() - 1); }
#include <iomanip> #include <iostream> #include <sstream> int findNumOfDec(double x) { std::stringstream ss; ss << std::fixed << std::setprecision(14) << x; auto s = ss.str(); auto pos = s.find('.'); if (pos == std::string::npos) { return 0; } auto tail = s.find_last_not_of('0'); return tail - pos; } void test(double x) { std::cout << x << " has " << findNumOfDec(x) << " decimals\n"; } int main() { test(12.0); test(12.345); test(12.345555555555); test(12.3450); test(12.34555555555555555555); test(1.2345e+54); return 0; }
Write a version of this Java function in C++ with identical behavior.
enum Fruits{ APPLE, BANANA, CHERRY }
enum fruits { apple, banana, cherry }; enum fruits { apple = 0, banana = 1, cherry = 2 };
Convert this Java block to C++, preserving its control flow and logic.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ParseIPAddress { public static void main(String[] args) { String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "2001:db8:85a3:0:0:8a2e:370:7334"}; System.out.printf("%-40s %-32s %s%n", "Test Case", "Hex Address", "Port"); for ( String ip : tests ) { try { String [] parsed = parseIP(ip); System.out.printf("%-40s %-32s %s%n", ip, parsed[0], parsed[1]); } catch (IllegalArgumentException e) { System.out.printf("%-40s Invalid address: %s%n", ip, e.getMessage()); } } } private static final Pattern IPV4_PAT = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+)){0,1}$"); private static final Pattern IPV6_DOUBL_COL_PAT = Pattern.compile("^\\[{0,1}([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+)){0,1}$"); private static String ipv6Pattern; static { ipv6Pattern = "^\\[{0,1}"; for ( int i = 1 ; i <= 7 ; i ++ ) { ipv6Pattern += "([0-9a-f]+):"; } ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+)){0,1}$"; } private static final Pattern IPV6_PAT = Pattern.compile(ipv6Pattern); private static String[] parseIP(String ip) { String hex = ""; String port = ""; Matcher ipv4Matcher = IPV4_PAT.matcher(ip); if ( ipv4Matcher.matches() ) { for ( int i = 1 ; i <= 4 ; i++ ) { hex += toHex4(ipv4Matcher.group(i)); } if ( ipv4Matcher.group(5) != null ) { port = ipv4Matcher.group(5); } return new String[] {hex, port}; } Matcher ipv6DoubleColonMatcher = IPV6_DOUBL_COL_PAT.matcher(ip); if ( ipv6DoubleColonMatcher.matches() ) { String p1 = ipv6DoubleColonMatcher.group(1); if ( p1.isEmpty() ) { p1 = "0"; } String p2 = ipv6DoubleColonMatcher.group(2); if ( p2.isEmpty() ) { p2 = "0"; } ip = p1 + getZero(8 - numCount(p1) - numCount(p2)) + p2; if ( ipv6DoubleColonMatcher.group(3) != null ) { ip = "[" + ip + "]:" + ipv6DoubleColonMatcher.group(3); } } Matcher ipv6Matcher = IPV6_PAT.matcher(ip); if ( ipv6Matcher.matches() ) { for ( int i = 1 ; i <= 8 ; i++ ) { hex += String.format("%4s", toHex6(ipv6Matcher.group(i))).replace(" ", "0"); } if ( ipv6Matcher.group(9) != null ) { port = ipv6Matcher.group(9); } return new String[] {hex, port}; } throw new IllegalArgumentException("ERROR 103: Unknown address: " + ip); } private static int numCount(String s) { return s.split(":").length; } private static String getZero(int count) { StringBuilder sb = new StringBuilder(); sb.append(":"); while ( count > 0 ) { sb.append("0:"); count--; } return sb.toString(); } private static String toHex4(String s) { int val = Integer.parseInt(s); if ( val < 0 || val > 255 ) { throw new IllegalArgumentException("ERROR 101: Invalid value : " + s); } return String.format("%2s", Integer.toHexString(val)).replace(" ", "0"); } private static String toHex6(String s) { int val = Integer.parseInt(s, 16); if ( val < 0 || val > 65536 ) { throw new IllegalArgumentException("ERROR 102: Invalid hex value : " + s); } return s; } }
#include <boost/asio/ip/address.hpp> #include <cstdint> #include <iostream> #include <iomanip> #include <limits> #include <string> using boost::asio::ip::address; using boost::asio::ip::address_v4; using boost::asio::ip::address_v6; using boost::asio::ip::make_address; using boost::asio::ip::make_address_v4; using boost::asio::ip::make_address_v6; template<typename uint> bool parse_int(const std::string& str, int base, uint& n) { try { size_t pos = 0; unsigned long u = stoul(str, &pos, base); if (pos != str.length() || u > std::numeric_limits<uint>::max()) return false; n = static_cast<uint>(u); return true; } catch (const std::exception& ex) { return false; } } void parse_ip_address_and_port(const std::string& input, address& addr, uint16_t& port) { size_t pos = input.rfind(':'); if (pos != std::string::npos && pos > 1 && pos + 1 < input.length() && parse_int(input.substr(pos + 1), 10, port) && port > 0) { if (input[0] == '[' && input[pos - 1] == ']') { addr = make_address_v6(input.substr(1, pos - 2)); return; } else { try { addr = make_address_v4(input.substr(0, pos)); return; } catch (const std::exception& ex) { } } } port = 0; addr = make_address(input); } void print_address_and_port(const address& addr, uint16_t port) { std::cout << std::hex << std::uppercase << std::setfill('0'); if (addr.is_v4()) { address_v4 addr4 = addr.to_v4(); std::cout << "address family: IPv4\n"; std::cout << "address number: " << std::setw(8) << addr4.to_uint() << '\n'; } else if (addr.is_v6()) { address_v6 addr6 = addr.to_v6(); address_v6::bytes_type bytes(addr6.to_bytes()); std::cout << "address family: IPv6\n"; std::cout << "address number: "; for (unsigned char byte : bytes) std::cout << std::setw(2) << static_cast<unsigned int>(byte); std::cout << '\n'; } if (port != 0) std::cout << "port: " << std::dec << port << '\n'; else std::cout << "port not specified\n"; } void test(const std::string& input) { std::cout << "input: " << input << '\n'; try { address addr; uint16_t port = 0; parse_ip_address_and_port(input, addr, port); print_address_and_port(addr, port); } catch (const std::exception& ex) { std::cout << "parsing failed\n"; } std::cout << '\n'; } int main(int argc, char** argv) { test("127.0.0.1"); test("127.0.0.1:80"); test("::ffff:127.0.0.1"); test("::1"); test("[::1]:80"); test("1::80"); test("2605:2700:0:3::4713:93e3"); test("[2605:2700:0:3::4713:93e3]:80"); return 0; }
Generate an equivalent C++ version of this Java code.
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector; public class RTextonyms { private static final Map<Character, Character> mapping; private int total, elements, textonyms, max_found; private String filename, mappingResult; private Vector<String> max_strings; private Map<String, Vector<String>> values; static { mapping = new HashMap<Character, Character>(); mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2'); mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3'); mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4'); mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5'); mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6'); mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7'); mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8'); mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9'); } public RTextonyms(String filename) { this.filename = filename; this.total = this.elements = this.textonyms = this.max_found = 0; this.values = new HashMap<String, Vector<String>>(); this.max_strings = new Vector<String>(); return; } public void add(String line) { String mapping = ""; total++; if (!get_mapping(line)) { return; } mapping = mappingResult; if (values.get(mapping) == null) { values.put(mapping, new Vector<String>()); } int num_strings; num_strings = values.get(mapping).size(); textonyms += num_strings == 1 ? 1 : 0; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.add(mapping); max_found = num_strings; } else if (num_strings == max_found) { max_strings.add(mapping); } values.get(mapping).add(line); return; } public void results() { System.out.printf("Read %,d words from %s%n%n", total, filename); System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements, filename); System.out.printf("They require %,d digit combinations to represent them.%n", values.size()); System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms); System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1); for (String key : max_strings) { System.out.printf("%16s maps to: %s%n", key, values.get(key).toString()); } System.out.println(); return; } public void match(String key) { Vector<String> match; match = values.get(key); if (match == null) { System.out.printf("Key %s not found%n", key); } else { System.out.printf("Key %s matches: %s%n", key, match.toString()); } return; } private boolean get_mapping(String line) { mappingResult = line; StringBuilder mappingBuilder = new StringBuilder(); for (char cc : line.toCharArray()) { if (Character.isAlphabetic(cc)) { mappingBuilder.append(mapping.get(Character.toUpperCase(cc))); } else if (Character.isDigit(cc)) { mappingBuilder.append(cc); } else { return false; } } mappingResult = mappingBuilder.toString(); return true; } public static void main(String[] args) { String filename; if (args.length > 0) { filename = args[0]; } else { filename = "./unixdict.txt"; } RTextonyms tc; tc = new RTextonyms(filename); Path fp = Paths.get(filename); try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) { while (fs.hasNextLine()) { tc.add(fs.nextLine()); } } catch (IOException ex) { ex.printStackTrace(); } List<String> numbers = Arrays.asList( "001", "228", "27484247", "7244967473642", "." ); tc.results(); for (String number : numbers) { if (number.equals(".")) { System.out.println(); } else { tc.match(number); } } return; } }
#include <fstream> #include <iostream> #include <unordered_map> #include <vector> struct Textonym_Checker { private: int total; int elements; int textonyms; int max_found; std::vector<std::string> max_strings; std::unordered_map<std::string, std::vector<std::string>> values; int get_mapping(std::string &result, const std::string &input) { static std::unordered_map<char, char> mapping = { {'A', '2'}, {'B', '2'}, {'C', '2'}, {'D', '3'}, {'E', '3'}, {'F', '3'}, {'G', '4'}, {'H', '4'}, {'I', '4'}, {'J', '5'}, {'K', '5'}, {'L', '5'}, {'M', '6'}, {'N', '6'}, {'O', '6'}, {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'}, {'T', '8'}, {'U', '8'}, {'V', '8'}, {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'} }; result = input; for (char &c : result) { if (!isalnum(c)) return 0; if (isalpha(c)) c = mapping[toupper(c)]; } return 1; } public: Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { } ~Textonym_Checker() { } void add(const std::string &str) { std::string mapping; total++; if (!get_mapping(mapping, str)) return; const int num_strings = values[mapping].size(); if (num_strings == 1) textonyms++; elements++; if (num_strings > max_found) { max_strings.clear(); max_strings.push_back(mapping); max_found = num_strings; } else if (num_strings == max_found) max_strings.push_back(mapping); values[mapping].push_back(str); } void results(const std::string &filename) { std::cout << "Read " << total << " words from " << filename << "\n\n"; std::cout << "There are " << elements << " words in " << filename; std::cout << " which can be represented by the digit key mapping.\n"; std::cout << "They require " << values.size() << " digit combinations to represent them.\n"; std::cout << textonyms << " digit combinations represent Textonyms.\n\n"; std::cout << "The numbers mapping to the most words map to "; std::cout << max_found + 1 << " words each:\n"; for (auto it1 : max_strings) { std::cout << '\t' << it1 << " maps to: "; for (auto it2 : values[it1]) std::cout << it2 << " "; std::cout << '\n'; } std::cout << '\n'; } void match(const std::string &str) { auto match = values.find(str); if (match == values.end()) { std::cout << "Key '" << str << "' not found\n"; } else { std::cout << "Key '" << str << "' matches: "; for (auto it : values[str]) std::cout << it << " "; std::cout << '\n'; } } }; int main() { auto filename = "unixdict.txt"; std::ifstream input(filename); Textonym_Checker tc; if (input.is_open()) { std::string line; while (getline(input, line)) tc.add(line); } input.close(); tc.results(filename); tc.match("001"); tc.match("228"); tc.match("27484247"); tc.match("7244967473642"); }