Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a language-to-language conversion: from C++ to C#, same semantics.
#include <iostream> #include <iterator> #include <cstddef> template<typename InIter> void extract_ranges(InIter begin, InIter end, std::ostream& os) { if (begin == end) return; int current = *begin++; os << current; int count = 1; while (begin != end) { int next = *begin++; if (next == current+1) ++count; else { if (count > 2) os << '-'; else os << ','; if (count > 1) os << current << ','; os << next; count = 1; } current = next; } if (count > 1) os << (count > 2? '-' : ',') << current; } template<typename T, std::size_t n> T* end(T (&array)[n]) { return array+n; } int main() { int data[] = { 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 }; extract_ranges(data, end(data), std::cout); std::cout << std::endl; }
using System; using System.Collections.Generic; using System.Linq; class RangeExtraction { static void Main() { const string testString = "0, 1, 2, 4, 6, 7, 8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39"; var result = String.Join(",", RangesToStrings(GetRanges(testString))); Console.Out.WriteLine(result); } public static IEnumerable<IEnumerable<int>> GetRanges(string testString) { var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x)); var current = new List<int>(); foreach (var n in numbers) { if (current.Count == 0) { current.Add(n); } else { if (current.Max() + 1 == n) { current.Add(n); } else { yield return current; current = new List<int> { n }; } } } yield return current; } public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges) { foreach (var range in ranges) { if (range.Count() == 1) { yield return range.Single().ToString(); } else if (range.Count() == 2) { yield return range.Min() + "," + range.Max(); } else { yield return range.Min() + "-" + range.Max(); } } } }
Keep all operations the same but rewrite the snippet in C++.
using System; namespace TypeDetection { class C { } struct S { } enum E { NONE, } class Program { static void ShowType<T>(T t) { Console.WriteLine("The type of '{0}' is {1}", t, t.GetType()); } static void Main() { ShowType(5); ShowType(7.5); ShowType('d'); ShowType(true); ShowType("Rosetta"); ShowType(new C()); ShowType(new S()); ShowType(E.NONE); ShowType(new int[] { 1, 2, 3 }); } } }
#include <iostream> template <typename T> auto typeString(const T&) { return typeid(T).name(); } class C {}; struct S {}; int main() { std::cout << typeString(1) << '\n'; std::cout << typeString(1L) << '\n'; std::cout << typeString(1.0f) << '\n'; std::cout << typeString(1.0) << '\n'; std::cout << typeString('c') << '\n'; std::cout << typeString("string") << '\n'; std::cout << typeString(C{}) << '\n'; std::cout << typeString(S{}) << '\n'; std::cout << typeString(nullptr) << '\n'; }
Keep all operations the same but rewrite the snippet in C++.
using System; namespace TypeDetection { class C { } struct S { } enum E { NONE, } class Program { static void ShowType<T>(T t) { Console.WriteLine("The type of '{0}' is {1}", t, t.GetType()); } static void Main() { ShowType(5); ShowType(7.5); ShowType('d'); ShowType(true); ShowType("Rosetta"); ShowType(new C()); ShowType(new S()); ShowType(E.NONE); ShowType(new int[] { 1, 2, 3 }); } } }
#include <iostream> template <typename T> auto typeString(const T&) { return typeid(T).name(); } class C {}; struct S {}; int main() { std::cout << typeString(1) << '\n'; std::cout << typeString(1L) << '\n'; std::cout << typeString(1.0f) << '\n'; std::cout << typeString(1.0) << '\n'; std::cout << typeString('c') << '\n'; std::cout << typeString("string") << '\n'; std::cout << typeString(C{}) << '\n'; std::cout << typeString(S{}) << '\n'; std::cout << typeString(nullptr) << '\n'; }
Ensure the translated C# code behaves exactly like the original C++ snippet.
#include <iostream> int main( int argc, char* argv[] ) { int triangle[] = { 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55, 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23, 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42, 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72, 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36, 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52, 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15, 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93 }; const int size = sizeof( triangle ) / sizeof( int ); const int tn = static_cast<int>(sqrt(2.0 * size)); assert(tn * (tn + 1) == 2 * size); for (int n = tn - 1; n > 0; --n) for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]); std::cout << "Maximum total: " << triangle[0] << "\n\n"; }
using System; namespace RosetaCode { class MainClass { public static void Main (string[] args) { int[,] list = new int[18,19]; string input = @"55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 27 83 58 35 71 11 25 57 29 85 14 64 36 96 27 11 58 56 92 18 55 02 90 03 60 48 49 41 46 33 36 47 23 92 50 48 02 36 59 42 79 72 20 82 77 42 56 78 38 80 39 75 02 71 66 66 01 03 55 72 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93"; var charArray = input.Split ('\n'); for (int i=0; i < charArray.Length; i++) { var numArr = charArray[i].Trim().Split(' '); for (int j = 0; j<numArr.Length; j++) { int number = Convert.ToInt32 (numArr[j]); list [i, j] = number; } } for (int i = 16; i >= 0; i--) { for (int j = 0; j < 18; j++) { list[i,j] = Math.Max(list[i, j] + list[i+1, j], list[i,j] + list[i+1, j+1]); } } Console.WriteLine (string.Format("Maximum total: {0}", list [0, 0])); } } }
Generate an equivalent C# version of this C++ code.
#include <iostream> #include <set> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; int main(void) { fs::path p(fs::current_path()); std::set<std::string> tree; for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it) tree.insert(it->path().filename().native()); for (auto entry : tree) std::cout << entry << '\n'; }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Unix_ls { public class UnixLS { public static void Main(string[] args) { UnixLS ls = new UnixLS(); ls.list(args.Length.Equals(0) ? "." : args[0]); } private void list(string folder) { foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly)) { Console.WriteLine(fileSystemInfo.Name); } } } }
Write a version of this C++ function in C# with identical behavior.
#include <iostream> #include <set> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; int main(void) { fs::path p(fs::current_path()); std::set<std::string> tree; for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it) tree.insert(it->path().filename().native()); for (auto entry : tree) std::cout << entry << '\n'; }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Unix_ls { public class UnixLS { public static void Main(string[] args) { UnixLS ls = new UnixLS(); ls.list(args.Length.Equals(0) ? "." : args[0]); } private void list(string folder) { foreach (FileSystemInfo fileSystemInfo in new DirectoryInfo(folder).EnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly)) { Console.WriteLine(fileSystemInfo.Name); } } } }
Port the provided C++ code into C# while preserving the original functionality.
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr( int d ) { while( d % 4 > 0 ) { d++; } sz = d; sqr = new int[sz * sz]; fillSqr(); } ~magicSqr() { delete [] sqr; } void display() const { cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n"; cout << "It's Magic Sum is: " << magicNumber() << "\n\n"; ostringstream cvr; cvr << sz * sz; int l = cvr.str().size(); for( int y = 0; y < sz; y++ ) { int yy = y * sz; for( int x = 0; x < sz; x++ ) { cout << setw( l + 2 ) << sqr[yy + x]; } cout << "\n"; } cout << "\n\n"; } private: void fillSqr() { static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } }; int i = 0; for( int curRow = 0; curRow < sz; curRow++ ) { for( int curCol = 0; curCol < sz; curCol++ ) { sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i; i++; } } } int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; } int* sqr; int sz; }; int main( int argc, char* argv[] ) { magicSqr s( 8 ); s.display(); return 0; }
using System; namespace MagicSquareDoublyEven { class Program { static void Main(string[] args) { int n = 8; var result = MagicSquareDoublyEven(n); for (int i = 0; i < result.GetLength(0); i++) { for (int j = 0; j < result.GetLength(1); j++) Console.Write("{0,2} ", result[i, j]); Console.WriteLine(); } Console.WriteLine("\nMagic constant: {0} ", (n * n + 1) * n / 2); Console.ReadLine(); } private static int[,] MagicSquareDoublyEven(int n) { if (n < 4 || n % 4 != 0) throw new ArgumentException("base must be a positive " + "multiple of 4"); int bits = 0b1001_0110_0110_1001; int size = n * n; int mult = n / 4; int[,] result = new int[n, n]; for (int r = 0, i = 0; r < n; r++) { for (int c = 0; c < n; c++, i++) { int bitPos = c / mult + (r / mult) * 4; result[r, c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i; } } return result; } } }
Ensure the translated C# code behaves exactly like the original C++ snippet.
#include <algorithm> #include <coroutine> #include <iostream> #include <memory> #include <tuple> #include <variant> using namespace std; class BinaryTree { using Node = tuple<BinaryTree, int, BinaryTree>; unique_ptr<Node> m_tree; public: BinaryTree() = default; BinaryTree(BinaryTree&& leftChild, int value, BinaryTree&& rightChild) : m_tree {make_unique<Node>(move(leftChild), value, move(rightChild))} {} BinaryTree(int value) : BinaryTree(BinaryTree{}, value, BinaryTree{}){} BinaryTree(BinaryTree&& leftChild, int value) : BinaryTree(move(leftChild), value, BinaryTree{}){} BinaryTree(int value, BinaryTree&& rightChild) : BinaryTree(BinaryTree{}, value, move(rightChild)){} explicit operator bool() const { return (bool)m_tree; } int Value() const { return get<1>(*m_tree); } const BinaryTree& LeftChild() const { return get<0>(*m_tree); } const BinaryTree& RightChild() const { return get<2>(*m_tree); } }; struct TreeWalker { struct promise_type { int val; suspend_never initial_suspend() noexcept {return {};} suspend_never return_void() noexcept {return {};} suspend_always final_suspend() noexcept {return {};} void unhandled_exception() noexcept { } TreeWalker get_return_object() { return TreeWalker{coroutine_handle<promise_type>::from_promise(*this)}; } suspend_always yield_value(int x) noexcept { val=x; return {}; } }; coroutine_handle<promise_type> coro; TreeWalker(coroutine_handle<promise_type> h): coro(h) {} ~TreeWalker() { if(coro) coro.destroy(); } class Iterator { const coroutine_handle<promise_type>* m_h = nullptr; public: Iterator() = default; constexpr Iterator(const coroutine_handle<promise_type>* h) : m_h(h){} Iterator& operator++() { m_h->resume(); return *this; } Iterator operator++(int) { auto old(*this); m_h->resume(); return old; } int operator*() const { return m_h->promise().val; } bool operator!=(monostate) const noexcept { return !m_h->done(); return m_h && !m_h->done(); } bool operator==(monostate) const noexcept { return !operator!=(monostate{}); } }; constexpr Iterator begin() const noexcept { return Iterator(&coro); } constexpr monostate end() const noexcept { return monostate{}; } }; namespace std { template<> class iterator_traits<TreeWalker::Iterator> { public: using difference_type = std::ptrdiff_t; using size_type = std::size_t; using value_type = int; using pointer = int*; using reference = int&; using iterator_category = std::input_iterator_tag; }; } TreeWalker WalkFringe(const BinaryTree& tree) { if(tree) { auto& left = tree.LeftChild(); auto& right = tree.RightChild(); if(!left && !right) { co_yield tree.Value(); } for(auto v : WalkFringe(left)) { co_yield v; } for(auto v : WalkFringe(right)) { co_yield v; } } co_return; } void PrintTree(const BinaryTree& tree) { if(tree) { cout << "("; PrintTree(tree.LeftChild()); cout << tree.Value(); PrintTree(tree.RightChild()); cout <<")"; } } void Compare(const BinaryTree& tree1, const BinaryTree& tree2) { auto walker1 = WalkFringe(tree1); auto walker2 = WalkFringe(tree2); bool sameFringe = ranges::equal(walker1.begin(), walker1.end(), walker2.begin(), walker2.end()); PrintTree(tree1); cout << (sameFringe ? " has same fringe as " : " has different fringe than "); PrintTree(tree2); cout << "\n"; } int main() { BinaryTree tree1(BinaryTree{6}, 77, BinaryTree{BinaryTree{3}, 77, BinaryTree{77, BinaryTree{9}}}); BinaryTree tree2(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{ BinaryTree{3}, 77, BinaryTree{9}}}); BinaryTree tree3(BinaryTree{BinaryTree{BinaryTree{6}, 77}, 77, BinaryTree{77, BinaryTree{9}}}); Compare(tree1, tree2); Compare(tree1, tree3); }
using System; using System.Collections.Generic; using System.Linq; namespace Same_Fringe { class Program { static void Main() { var rnd = new Random(110456); var randList = Enumerable.Range(0, 20).Select(i => rnd.Next(1000)).ToList(); var bt1 = new BinTree<int>(randList); Shuffle(randList, 428); var bt2 = new BinTree<int>(randList); Console.WriteLine(bt1.CompareTo(bt2) ? "True compare worked" : "True compare failed"); bt1.Insert(0); Console.WriteLine(bt1.CompareTo(bt2) ? "False compare failed" : "False compare worked"); } static void Shuffle<T>(List<T> values, int seed) { var rnd = new Random(seed); for (var i = 0; i < values.Count - 2; i++) { var iSwap = rnd.Next(values.Count - i) + i; var tmp = values[iSwap]; values[iSwap] = values[i]; values[i] = tmp; } } } class BinTree<T> where T:IComparable { private BinTree<T> _left; private BinTree<T> _right; private T _value; private BinTree<T> Left { get { return _left; } } private BinTree<T> Right { get { return _right; } } private T Value { get { return _value; } } public bool IsLeaf { get { return Left == null; } } private BinTree(BinTree<T> left, BinTree<T> right, T value) { _left = left; _right = right; _value = value; } public BinTree(T value) : this(null, null, value) { } public BinTree(IEnumerable<T> values) { _value = values.First(); foreach (var value in values.Skip(1)) { Insert(value); } } public void Insert(T value) { if (IsLeaf) { if (value.CompareTo(Value) < 0) { _left = new BinTree<T>(value); _right = new BinTree<T>(Value); } else { _left = new BinTree<T>(Value); _right = new BinTree<T>(value); _value = value; } } else { if (value.CompareTo(Value) < 0) { Left.Insert(value); } else { Right.Insert(value); } } } public IEnumerable<T> GetLeaves() { if (IsLeaf) { yield return Value; yield break; } foreach (var val in Left.GetLeaves()) { yield return val; } foreach (var val in Right.GetLeaves()) { yield return val; } } internal bool CompareTo(BinTree<T> other) { return other.GetLeaves().Zip(GetLeaves(), (t1, t2) => t1.CompareTo(t2) == 0).All(f => f); } } }
Transform the following C++ implementation into C#, maintaining the same output and logic.
#include <iostream> #include <vector> enum class Piece { empty, black, white }; typedef std::pair<int, int> position; bool isAttacking(const position &queen, const position &pos) { return queen.first == pos.first || queen.second == pos.second || abs(queen.first - pos.first) == abs(queen.second - pos.second); } bool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { auto pos = std::make_pair(i, j); for (auto queen : pBlackQueens) { if (queen == pos || !placingBlack && isAttacking(queen, pos)) { goto inner; } } for (auto queen : pWhiteQueens) { if (queen == pos || placingBlack && isAttacking(queen, pos)) { goto inner; } } if (placingBlack) { pBlackQueens.push_back(pos); placingBlack = false; } else { pWhiteQueens.push_back(pos); if (place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.pop_back(); pWhiteQueens.pop_back(); placingBlack = true; } inner: {} } } if (!placingBlack) { pBlackQueens.pop_back(); } return false; } void printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) { std::vector<Piece> board(n * n); std::fill(board.begin(), board.end(), Piece::empty); for (auto &queen : blackQueens) { board[queen.first * n + queen.second] = Piece::black; } for (auto &queen : whiteQueens) { board[queen.first * n + queen.second] = Piece::white; } for (size_t i = 0; i < board.size(); ++i) { if (i != 0 && i % n == 0) { std::cout << '\n'; } switch (board[i]) { case Piece::black: std::cout << "B "; break; case Piece::white: std::cout << "W "; break; case Piece::empty: default: int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { std::cout << "x "; } else { std::cout << "* "; } break; } } std::cout << "\n\n"; } int main() { std::vector<position> nms = { {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, }; for (auto nm : nms) { std::cout << nm.second << " black and " << nm.second << " white queens on a " << nm.first << " x " << nm.first << " board:\n"; std::vector<position> blackQueens, whiteQueens; if (place(nm.second, nm.first, blackQueens, whiteQueens)) { printBoard(nm.first, blackQueens, whiteQueens); } else { std::cout << "No solution exists.\n\n"; } } return 0; }
using System; using System.Collections.Generic; namespace PeacefulChessQueenArmies { using Position = Tuple<int, int>; enum Piece { Empty, Black, White } class Program { static bool IsAttacking(Position queen, Position pos) { return queen.Item1 == pos.Item1 || queen.Item2 == pos.Item2 || Math.Abs(queen.Item1 - pos.Item1) == Math.Abs(queen.Item2 - pos.Item2); } static bool Place(int m, int n, List<Position> pBlackQueens, List<Position> pWhiteQueens) { if (m == 0) { return true; } bool placingBlack = true; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { var pos = new Position(i, j); foreach (var queen in pBlackQueens) { if (queen.Equals(pos) || !placingBlack && IsAttacking(queen, pos)) { goto inner; } } foreach (var queen in pWhiteQueens) { if (queen.Equals(pos) || placingBlack && IsAttacking(queen, pos)) { goto inner; } } if (placingBlack) { pBlackQueens.Add(pos); placingBlack = false; } else { pWhiteQueens.Add(pos); if (Place(m - 1, n, pBlackQueens, pWhiteQueens)) { return true; } pBlackQueens.RemoveAt(pBlackQueens.Count - 1); pWhiteQueens.RemoveAt(pWhiteQueens.Count - 1); placingBlack = true; } inner: { } } } if (!placingBlack) { pBlackQueens.RemoveAt(pBlackQueens.Count - 1); } return false; } static void PrintBoard(int n, List<Position> blackQueens, List<Position> whiteQueens) { var board = new Piece[n * n]; foreach (var queen in blackQueens) { board[queen.Item1 * n + queen.Item2] = Piece.Black; } foreach (var queen in whiteQueens) { board[queen.Item1 * n + queen.Item2] = Piece.White; } for (int i = 0; i < board.Length; i++) { if (i != 0 && i % n == 0) { Console.WriteLine(); } switch (board[i]) { case Piece.Black: Console.Write("B "); break; case Piece.White: Console.Write("W "); break; case Piece.Empty: int j = i / n; int k = i - j * n; if (j % 2 == k % 2) { Console.Write(" "); } else { Console.Write("# "); } break; } } Console.WriteLine("\n"); } static void Main() { var nms = new int[,] { {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7}, }; for (int i = 0; i < nms.GetLength(0); i++) { Console.WriteLine("{0} black and {0} white queens on a {1} x {1} board:", nms[i, 1], nms[i, 0]); List<Position> blackQueens = new List<Position>(); List<Position> whiteQueens = new List<Position>(); if (Place(nms[i, 1], nms[i, 0], blackQueens, whiteQueens)) { PrintBoard(nms[i, 0], blackQueens, whiteQueens); } else { Console.WriteLine("No solution exists.\n"); } } } } }
Write the same algorithm in C# as shown in this C++ implementation.
#include <iostream> #include <iterator> #include <sstream> #include <vector> using namespace std; class MTF { public: string encode( string str ) { fillSymbolTable(); vector<int> output; for( string::iterator it = str.begin(); it != str.end(); it++ ) { for( int i = 0; i < 26; i++ ) { if( *it == symbolTable[i] ) { output.push_back( i ); moveToFront( i ); break; } } } string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { ostringstream ss; ss << *it; r += ss.str() + " "; } return r; } string decode( string str ) { fillSymbolTable(); istringstream iss( str ); vector<int> output; copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) ); string r; for( vector<int>::iterator it = output.begin(); it != output.end(); it++ ) { r.append( 1, symbolTable[*it] ); moveToFront( *it ); } return r; } private: void moveToFront( int i ) { char t = symbolTable[i]; for( int z = i - 1; z >= 0; z-- ) symbolTable[z + 1] = symbolTable[z]; symbolTable[0] = t; } void fillSymbolTable() { for( int x = 0; x < 26; x++ ) symbolTable[x] = x + 'a'; } char symbolTable[26]; }; int main() { MTF mtf; string a, str[] = { "broood", "bananaaa", "hiphophiphop" }; for( int x = 0; x < 3; x++ ) { a = str[x]; cout << a << " -> encoded = "; a = mtf.encode( a ); cout << a << "; decoded = " << mtf.decode( a ) << endl; } return 0; }
using System; using System.Collections.Generic; using System.Text; namespace MoveToFront { class Program { private static char[] symbolTable; private static void setSymbolTable() { symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray(); } private static void moveToFront(int charIndex) { char toFront = symbolTable[charIndex]; for (int j = charIndex; j > 0; j--) { symbolTable[j] = symbolTable[j - 1]; } symbolTable[0] = toFront; } public static int[] Encode(string input) { setSymbolTable(); var output = new List<int>(); foreach (char c in input) { for (int i = 0; i < 26; i++) { if (symbolTable[i] == c) { output.Add(i); moveToFront(i); break; } } } return output.ToArray(); } public static string Decode(int[] input) { setSymbolTable(); var output = new StringBuilder(input.Length); foreach (int n in input) { output.Append(symbolTable[n]); moveToFront(n); } return output.ToString(); } static void Main(string[] args) { string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" }; int[] encoding; foreach (string s in testInputs) { Console.WriteLine($"Encoding for '{s}':"); encoding = Encode(s); foreach (int i in encoding) { Console.Write($"{i} "); } Console.WriteLine($"\nDecoding for '{s}':"); Console.WriteLine($"{Decode(encoding)}\n"); } } } }
Maintain the same structure and functionality when rewriting this code in C++.
using System; using static System.Console; class Program { static void Main(string[] args) { for (int i=0,j=-6,k=1,c=0,s=0;s<1600000;s+=c+=k+=j+=6) Write("{0,-7}{1}",s, (i+=i==3?-4:1)==0?"\n":" "); } }
#include <array> #include <cstdio> #include <numeric> void PrintContainer(const auto& vec) { int count = 0; for(auto value : vec) { printf("%7d%c", value, ++count % 10 == 0 ? '\n' : ' '); } } int main() { auto cube = [](auto x){return x * x * x;}; std::array<int, 50> a; std::iota(a.begin(), a.end(), 0); std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube); PrintContainer(a); }
Change the programming language of this snippet from C# to C++ without modifying what it does.
using System.Diagnostics; namespace Execute { class Program { static void Main(string[] args) { Process.Start("cmd.exe", "/c dir"); } } }
system("pause");
Ensure the translated C# code behaves exactly like the original C++ snippet.
#include <vector> #include <list> #include <algorithm> #include <iostream> template <typename T> struct Node { T value; Node* prev_node; }; template <typename Container> Container lis(const Container& values) { using E = typename Container::value_type; using NodePtr = Node<E>*; using ConstNodePtr = const NodePtr; std::vector<NodePtr> pileTops; std::vector<Node<E>> nodes(values.size()); auto cur_node = std::begin(nodes); for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node) { auto node = &*cur_node; node->value = *cur_value; auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node, [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; }); if (lb != pileTops.begin()) node->prev_node = *std::prev(lb); if (lb == pileTops.end()) pileTops.push_back(node); else *lb = node; } Container result(pileTops.size()); auto r = std::rbegin(result); for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r) *r = node->value; return result; } template <typename Container> void show_lis(const Container& values) { auto&& result = lis(values); for (auto& r : result) { std::cout << r << ' '; } std::cout << std::endl; } int main() { show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 }); show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }); }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; public static class LIS { public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) => values == null ? throw new ArgumentNullException() : FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse(); private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) { if (index == values.Count) return current; if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0) return FindRecImpl(values, current, index + 1, comparer); return Max( FindRecImpl(values, current, index + 1, comparer), FindRecImpl(values, current + values[index], index + 1, comparer) ); } private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a; class Sequence<T> : IEnumerable<T> { public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null); public Sequence(T value, Sequence<T> tail) { Value = value; Tail = tail; Length = tail == null ? 0 : tail.Length + 1; } public T Value { get; } public Sequence<T> Tail { get; } public int Length { get; } public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s); public IEnumerator<T> GetEnumerator() { for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
Maintain the same structure and functionality when rewriting this code in C++.
using System; using System.Collections; using System.Collections.Generic; using System.Text; using static System.Linq.Enumerable; public static class BraceExpansion { enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat } const char L = '{', R = '}', S = ','; public static void Main() { string[] input = { "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", @"{,{,gotta have{ ,\, again\, }}more }cowbell!", @"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}" }; foreach (string text in input) Expand(text); } static void Expand(string input) { Token token = Tokenize(input); foreach (string value in token) Console.WriteLine(value); Console.WriteLine(); } static Token Tokenize(string input) { var tokens = new List<Token>(); var buffer = new StringBuilder(); bool escaping = false; int level = 0; foreach (char c in input) { (escaping, level, tokens, buffer) = c switch { _ when escaping => (false, level, tokens, buffer.Append(c)), '\\' => (true, level, tokens, buffer.Append(c)), L => (escaping, level + 1, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.OpenBrace)), buffer), S when level > 0 => (escaping, level, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.Separator)), buffer), R when level > 0 => (escaping, level - 1, tokens.With(buffer.Flush()).With(new Token(c.ToString(), TokenType.CloseBrace)).Merge(), buffer), _ => (escaping, level, tokens, buffer.Append(c)) }; } if (buffer.Length > 0) tokens.Add(buffer.Flush()); for (int i = 0; i < tokens.Count; i++) { if (tokens[i].Type == TokenType.OpenBrace || tokens[i].Type == TokenType.Separator) { tokens[i] = tokens[i].Value; } } return new Token(tokens, TokenType.Concat); } static List<Token> Merge(this List<Token> list) { int separators = 0; int last = list.Count - 1; for (int i = list.Count - 3; i >= 0; i--) { if (list[i].Type == TokenType.Separator) { separators++; Concat(list, i + 1, last); list.RemoveAt(i); last = i; } else if (list[i].Type == TokenType.OpenBrace) { Concat(list, i + 1, last); if (separators > 0) { list[i] = new Token(list.Range((i+1)..^1), TokenType.Alternate); list.RemoveRange(i+1, list.Count - i - 1); } else { list[i] = L.ToString(); list[^1] = R.ToString(); Concat(list, i, list.Count); } break; } } return list; } static void Concat(List<Token> list, int s, int e) { for (int i = e - 2; i >= s; i--) { (Token a, Token b) = (list[i], list[i+1]); switch (a.Type, b.Type) { case (TokenType.Text, TokenType.Text): list[i] = a.Value + b.Value; list.RemoveAt(i+1); break; case (TokenType.Concat, TokenType.Concat): a.SubTokens.AddRange(b.SubTokens); list.RemoveAt(i+1); break; case (TokenType.Concat, TokenType.Text) when b.Value == "": list.RemoveAt(i+1); break; case (TokenType.Text, TokenType.Concat) when a.Value == "": list.RemoveAt(i); break; default: list[i] = new Token(new [] { a, b }, TokenType.Concat); list.RemoveAt(i+1); break; } } } private struct Token : IEnumerable<string> { private List<Token>? _subTokens; public string Value { get; } public TokenType Type { get; } public List<Token> SubTokens => _subTokens ??= new List<Token>(); public Token(string value, TokenType type) => (Value, Type, _subTokens) = (value, type, null); public Token(IEnumerable<Token> subTokens, TokenType type) => (Value, Type, _subTokens) = ("", type, subTokens.ToList()); public static implicit operator Token(string value) => new Token(value, TokenType.Text); public IEnumerator<string> GetEnumerator() => (Type switch { TokenType.Concat => SubTokens.Select(t => t.AsEnumerable()).CartesianProduct().Select(p => string.Join("", p)), TokenType.Alternate => from t in SubTokens from s in t select s, _ => Repeat(Value, 1) }).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) { IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() }; return sequences.Aggregate( emptyProduct, (accumulator, sequence) => from acc in accumulator from item in sequence select acc.Concat(new [] { item })); } static List<Token> With(this List<Token> list, Token token) { list.Add(token); return list; } static IEnumerable<Token> Range(this List<Token> list, Range range) { int start = range.Start.GetOffset(list.Count); int end = range.End.GetOffset(list.Count); for (int i = start; i < end; i++) yield return list[i]; } static string Flush(this StringBuilder builder) { string result = builder.ToString(); builder.Clear(); return result; } }
#include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> namespace detail { template <typename ForwardIterator> class tokenizer { ForwardIterator _tbegin, _tend, _end; public: tokenizer(ForwardIterator begin, ForwardIterator end) : _tbegin(begin), _tend(begin), _end(end) { } template <typename Lambda> bool next(Lambda istoken) { if (_tbegin == _end) { return false; } _tbegin = _tend; for (; _tend != _end && !istoken(*_tend); ++_tend) { if (*_tend == '\\' && std::next(_tend) != _end) { ++_tend; } } if (_tend == _tbegin) { _tend++; } return _tbegin != _end; } ForwardIterator begin() const { return _tbegin; } ForwardIterator end() const { return _tend; } bool operator==(char c) { return *_tbegin == c; } }; template <typename List> void append_all(List & lista, const List & listb) { if (listb.size() == 1) { for (auto & a : lista) { a += listb.back(); } } else { List tmp; for (auto & a : lista) { for (auto & b : listb) { tmp.push_back(a + b); } } lista = std::move(tmp); } } template <typename String, typename List, typename Tokenizer> List expand(Tokenizer & token) { std::vector<List> alts{ { String() } }; while (token.next([](char c) { return c == '{' || c == ',' || c == '}'; })) { if (token == '{') { append_all(alts.back(), expand<String, List>(token)); } else if (token == ',') { alts.push_back({ String() }); } else if (token == '}') { if (alts.size() == 1) { for (auto & a : alts.back()) { a = '{' + a + '}'; } return alts.back(); } else { for (std::size_t i = 1; i < alts.size(); i++) { alts.front().insert(alts.front().end(), std::make_move_iterator(std::begin(alts[i])), std::make_move_iterator(std::end(alts[i]))); } return std::move(alts.front()); } } else { for (auto & a : alts.back()) { a.append(token.begin(), token.end()); } } } List result{ String{ '{' } }; append_all(result, alts.front()); for (std::size_t i = 1; i < alts.size(); i++) { for (auto & a : result) { a += ','; } append_all(result, alts[i]); } return result; } } template < typename ForwardIterator, typename String = std::basic_string< typename std::iterator_traits<ForwardIterator>::value_type >, typename List = std::vector<String> > List expand(ForwardIterator begin, ForwardIterator end) { detail::tokenizer<ForwardIterator> token(begin, end); List list{ String() }; while (token.next([](char c) { return c == '{'; })) { if (token == '{') { detail::append_all(list, detail::expand<String, List>(token)); } else { for (auto & a : list) { a.append(token.begin(), token.end()); } } } return list; } template < typename Range, typename String = std::basic_string<typename Range::value_type>, typename List = std::vector<String> > List expand(const Range & range) { using Iterator = typename Range::const_iterator; return expand<Iterator, String, List>(std::begin(range), std::end(range)); } int main() { for (std::string string : { R"(~/{Downloads,Pictures}/*.{jpg,gif,png})", R"(It{{em,alic}iz,erat}e{d,}, please.)", R"({,{,gotta have{ ,\, again\, }}more }cowbell!)", R"({}} some {\\{edge,edgy} }{ cases, here\\\})", R"(a{b{1,2}c)", R"(a{1,2}b}c)", R"(a{1,{2},3}b)", R"(a{b{1,2}c{}})", R"(more{ darn{ cowbell,},})", R"(ab{c,d\,e{f,g\h},i\,j{k,l\,m}n,o\,p}qr)", R"({a,{\,b}c)", R"(a{b,{{c}})", R"({a{\}b,c}d)", R"({a,b{{1,2}e}f)", R"({}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\})", R"({{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{)", }) { std::cout << string << '\n'; for (auto expansion : expand(string)) { std::cout << " " << expansion << '\n'; } std::cout << '\n'; } return 0; }
Generate a C++ translation of this C# snippet without changing its computational steps.
using System; using System.ComponentModel; using System.Windows.Forms; class RosettaInteractionForm : Form { class NumberModel: INotifyPropertyChanged { Random rnd = new Random(); public event PropertyChangedEventHandler PropertyChanged = delegate {}; int _value; public int Value { get { return _value; } set { _value = value; PropertyChanged(this, new PropertyChangedEventArgs("Value")); } } public void ResetToRandom(){ Value = rnd.Next(5000); } } NumberModel model = new NumberModel{ Value = 0}; RosettaInteractionForm() { var tbNumber = new MaskedTextBox { Mask="0000", ResetOnSpace = false, Dock = DockStyle.Top }; tbNumber.DataBindings.Add("Text", model, "Value"); var btIncrement = new Button{Text = "Increment", Dock = DockStyle.Bottom}; btIncrement.Click += delegate { model.Value++; }; var btDecrement = new Button{Text = "Decrement", Dock = DockStyle.Bottom}; btDecrement.Click += delegate { model.Value--; }; var btRandom = new Button{ Text="Reset to Random", Dock = DockStyle.Bottom }; btRandom.Click += delegate { if (MessageBox.Show("Are you sure?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes) model.ResetToRandom(); }; Controls.Add(tbNumber); Controls.Add(btIncrement); Controls.Add(btDecrement); Controls.Add(btRandom); } static void Main() { Application.Run(new RosettaInteractionForm()); } }
#ifndef INTERACTION_H #define INTERACTION_H #include <QWidget> class QPushButton ; class QLineEdit ; class QVBoxLayout ; class MyWidget : public QWidget { Q_OBJECT public : MyWidget( QWidget *parent = 0 ) ; private : QLineEdit *entryField ; QPushButton *increaseButton ; QPushButton *randomButton ; QVBoxLayout *myLayout ; private slots : void doIncrement( ) ; void findRandomNumber( ) ; } ; #endif
Ensure the translated C# code behaves exactly like the original C++ snippet.
#include <random> #include <iostream> #include <iterator> #include <algorithm> using namespace std; mt19937 engine; unsigned int one_of_n(unsigned int n) { unsigned int choice; for(unsigned int i = 0; i < n; ++i) { uniform_int_distribution<unsigned int> distribution(0, i); if(!distribution(engine)) choice = i; } return choice; } int main() { engine = mt19937(random_device()()); unsigned int results[10] = {0}; for(unsigned int i = 0; i < 1000000; ++i) results[one_of_n(10)]++; ostream_iterator<unsigned int> out_it(cout, " "); copy(results, results+10, out_it); cout << '\n'; }
class Program { private static Random rnd = new Random(); public static int one_of_n(int n) { int currentChoice = 1; for (int i = 2; i <= n; i++) { double outerLimit = 1D / (double)i; if (rnd.NextDouble() < outerLimit) currentChoice = i; } return currentChoice; } static void Main(string[] args) { Dictionary<int, int> results = new Dictionary<int, int>(); for (int i = 1; i < 11; i++) results.Add(i, 0); for (int i = 0; i < 1000000; i++) { int result = one_of_n(10); results[result] = results[result] + 1; } for (int i = 1; i < 11; i++) Console.WriteLine("{0}\t{1}", i, results[i]); Console.ReadLine(); } }
Ensure the translated C++ code behaves exactly like the original C# snippet.
using System; namespace AdditionChains { class Program { static int[] Prepend(int n, int[] seq) { int[] result = new int[seq.Length + 1]; Array.Copy(seq, 0, result, 1, seq.Length); result[0] = n; return result; } static Tuple<int, int> CheckSeq(int pos, int[] seq, int n, int min_len) { if (pos > min_len || seq[0] > n) return new Tuple<int, int>(min_len, 0); if (seq[0] == n) return new Tuple<int, int>(pos, 1); if (pos < min_len) return TryPerm(0, pos, seq, n, min_len); return new Tuple<int, int>(min_len, 0); } static Tuple<int, int> TryPerm(int i, int pos, int[] seq, int n, int min_len) { if (i > pos) return new Tuple<int, int>(min_len, 0); Tuple<int, int> res1 = CheckSeq(pos + 1, Prepend(seq[0] + seq[i], seq), n, min_len); Tuple<int, int> res2 = TryPerm(i + 1, pos, seq, n, res1.Item1); if (res2.Item1 < res1.Item1) return res2; if (res2.Item1 == res1.Item1) return new Tuple<int, int>(res2.Item1, res1.Item2 + res2.Item2); throw new Exception("TryPerm exception"); } static Tuple<int, int> InitTryPerm(int x) { return TryPerm(0, 0, new int[] { 1 }, x, 12); } static void FindBrauer(int num) { Tuple<int, int> res = InitTryPerm(num); Console.WriteLine(); Console.WriteLine("N = {0}", num); Console.WriteLine("Minimum length of chains: L(n)= {0}", res.Item1); Console.WriteLine("Number of minimum length Brauer chains: {0}", res.Item2); } static void Main(string[] args) { int[] nums = new int[] { 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 }; Array.ForEach(nums, n => FindBrauer(n)); } } }
#include <iostream> #include <tuple> #include <vector> std::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int); std::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) { if (pos > minLen || seq[0] > n) return { minLen, 0 }; else if (seq[0] == n) return { pos, 1 }; else if (pos < minLen) return tryPerm(0, pos, seq, n, minLen); else return { minLen, 0 }; } std::pair<int, int> tryPerm(int i, int pos, const std::vector<int>& seq, int n, int minLen) { if (i > pos) return { minLen, 0 }; std::vector<int> seq2{ seq[0] + seq[i] }; seq2.insert(seq2.end(), seq.cbegin(), seq.cend()); auto res1 = checkSeq(pos + 1, seq2, n, minLen); auto res2 = tryPerm(i + 1, pos, seq, n, res1.first); if (res2.first < res1.first) return res2; else if (res2.first == res1.first) return { res2.first, res1.second + res2.second }; else throw std::runtime_error("tryPerm exception"); } std::pair<int, int> initTryPerm(int x) { return tryPerm(0, 0, { 1 }, x, 12); } void findBrauer(int num) { auto res = initTryPerm(num); std::cout << '\n'; std::cout << "N = " << num << '\n'; std::cout << "Minimum length of chains: L(n)= " << res.first << '\n'; std::cout << "Number of minimum length Brauer chains: " << res.second << '\n'; } int main() { std::vector<int> nums{ 7, 14, 21, 29, 32, 42, 64, 47, 79, 191, 382, 379 }; for (int i : nums) { findBrauer(i); } return 0; }
Translate the given C++ code snippet into C# without altering its behavior.
template <typename Function> void repeat(Function f, unsigned int n) { for(unsigned int i=n; 0<i; i--) f(); }
using System; namespace Repeat { class Program { static void Repeat(int count, Action<int> fn) { if (null == fn) { throw new ArgumentNullException("fn"); } for (int i = 0; i < count; i++) { fn.Invoke(i + 1); } } static void Main(string[] args) { Repeat(3, x => Console.WriteLine("Example {0}", x)); } } }
Change the programming language of this snippet from C++ to C# without modifying what it does.
#include <iostream> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int main(void) { std::cout << mul_inv(42, 2017) << std::endl; return 0; }
public class Program { static void Main() { System.Console.WriteLine(42.ModInverse(2017)); } } public static class IntExtensions { public static int ModInverse(this int a, int m) { if (m == 1) return 0; int m0 = m; (int x, int y) = (1, 0); while (a > 1) { int q = a / m; (a, m) = (m, a % m); (x, y) = (y, x - q * y); } return x < 0 ? x + m0 : x; } }
Generate a C++ translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChemicalCalculator { class Program { static Dictionary<string, double> atomicMass = new Dictionary<string, double>() { {"H", 1.008 }, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.630}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.90550}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.710}, {"Sb", 121.760}, {"Te", 127.60}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.500}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.98040}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299}, }; static double Evaluate(string s) { s += "["; double sum = 0.0; string symbol = ""; string number = ""; for (int i = 0; i < s.Length; ++i) { var c = s[i]; if ('@' <= c && c <= '[') { int n = 1; if (number != "") { n = int.Parse(number); } if (symbol != "") { sum += atomicMass[symbol] * n; } if (c == '[') { break; } symbol = c.ToString(); number = ""; } else if ('a' <= c && c <= 'z') { symbol += c; } else if ('0' <= c && c <= '9') { number += c; } else { throw new Exception(string.Format("Unexpected symbol {0} in molecule", c)); } } return sum; } static string ReplaceFirst(string text, string search, string replace) { int pos = text.IndexOf(search); if (pos < 0) { return text; } return text.Substring(0, pos) + replace + text.Substring(pos + search.Length); } static string ReplaceParens(string s) { char letter = 's'; while (true) { var start = s.IndexOf('('); if (start == -1) { break; } for (int i = start + 1; i < s.Length; ++i) { if (s[i] == ')') { var expr = s.Substring(start + 1, i - start - 1); var symbol = string.Format("@{0}", letter); s = ReplaceFirst(s, s.Substring(start, i + 1 - start), symbol); atomicMass[symbol] = Evaluate(expr); letter++; break; } if (s[i] == '(') { start = i; continue; } } } return s; } static void Main() { var molecules = new string[]{ "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" }; foreach (var molecule in molecules) { var mass = Evaluate(ReplaceParens(molecule)); Console.WriteLine("{0,17} -> {1,7:0.000}", molecule, mass); } } } }
#include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> std::map<std::string, double> atomicMass = { {"H", 1.008}, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F", 18.998403163}, {"Ne", 20.1797}, {"Na", 22.98976928}, {"Mg", 24.305}, {"Al", 26.9815385}, {"Si", 28.085}, {"P", 30.973761998}, {"S", 32.06}, {"Cl", 35.45}, {"Ar", 39.948}, {"K", 39.0983}, {"Ca", 40.078}, {"Sc", 44.955908}, {"Ti", 47.867}, {"V", 50.9415}, {"Cr", 51.9961}, {"Mn", 54.938044}, {"Fe", 55.845}, {"Co", 58.933194}, {"Ni", 58.6934}, {"Cu", 63.546}, {"Zn", 65.38}, {"Ga", 69.723}, {"Ge", 72.630}, {"As", 74.921595}, {"Se", 78.971}, {"Br", 79.904}, {"Kr", 83.798}, {"Rb", 85.4678}, {"Sr", 87.62}, {"Y", 88.90584}, {"Zr", 91.224}, {"Nb", 92.90637}, {"Mo", 95.95}, {"Ru", 101.07}, {"Rh", 102.90550}, {"Pd", 106.42}, {"Ag", 107.8682}, {"Cd", 112.414}, {"In", 114.818}, {"Sn", 118.710}, {"Sb", 121.760}, {"Te", 127.60}, {"I", 126.90447}, {"Xe", 131.293}, {"Cs", 132.90545196}, {"Ba", 137.327}, {"La", 138.90547}, {"Ce", 140.116}, {"Pr", 140.90766}, {"Nd", 144.242}, {"Pm", 145}, {"Sm", 150.36}, {"Eu", 151.964}, {"Gd", 157.25}, {"Tb", 158.92535}, {"Dy", 162.500}, {"Ho", 164.93033}, {"Er", 167.259}, {"Tm", 168.93422}, {"Yb", 173.054}, {"Lu", 174.9668}, {"Hf", 178.49}, {"Ta", 180.94788}, {"W", 183.84}, {"Re", 186.207}, {"Os", 190.23}, {"Ir", 192.217}, {"Pt", 195.084}, {"Au", 196.966569}, {"Hg", 200.592}, {"Tl", 204.38}, {"Pb", 207.2}, {"Bi", 208.98040}, {"Po", 209}, {"At", 210}, {"Rn", 222}, {"Fr", 223}, {"Ra", 226}, {"Ac", 227}, {"Th", 232.0377}, {"Pa", 231.03588}, {"U", 238.02891}, {"Np", 237}, {"Pu", 244}, {"Am", 243}, {"Cm", 247}, {"Bk", 247}, {"Cf", 251}, {"Es", 252}, {"Fm", 257}, {"Uue", 315}, {"Ubn", 299}, }; double evaluate(std::string s) { s += '['; double sum = 0.0; std::string symbol; std::string number; for (auto c : s) { if ('@' <= c && c <= '[') { int n = 1; if (number != "") { n = stoi(number); } if (symbol != "") { sum += atomicMass[symbol] * n; } if (c == '[') { break; } symbol = c; number = ""; } else if ('a' <= c && c <= 'z') { symbol += c; } else if ('0' <= c && c <= '9') { number += c; } else { std::string msg = "Unexpected symbol "; msg += c; msg += " in molecule"; throw std::runtime_error(msg); } } return sum; } std::string replaceFirst(const std::string &text, const std::string &search, const std::string &replace) { auto pos = text.find(search); if (pos == std::string::npos) { return text; } auto beg = text.substr(0, pos); auto end = text.substr(pos + search.length()); return beg + replace + end; } std::string replaceParens(std::string s) { char letter = 'a'; while (true) { auto start = s.find("("); if (start == std::string::npos) { break; } for (size_t i = start + 1; i < s.length(); i++) { if (s[i] == ')') { auto expr = s.substr(start + 1, i - start - 1); std::string symbol = "@"; symbol += letter; auto search = s.substr(start, i + 1 - start); s = replaceFirst(s, search, symbol); atomicMass[symbol] = evaluate(expr); letter++; break; } if (s[i] == '(') { start = i; continue; } } } return s; } int main() { std::vector<std::string> molecules = { "H", "H2", "H2O", "H2O2", "(HO)2", "Na2SO4", "C6H12", "COOH(C(CH3)2)3CH3", "C6H4O2(OH)4", "C27H46O", "Uue" }; for (auto molecule : molecules) { auto mass = evaluate(replaceParens(molecule)); std::cout << std::setw(17) << molecule << " -> " << std::setw(7) << std::fixed << std::setprecision(3) << mass << '\n'; } return 0; }
Produce a language-to-language conversion: from C++ to C#, same semantics.
#include <iostream> #include <vector> constexpr int N = 2200; constexpr int N2 = 2 * N * N; int main() { using namespace std; vector<bool> found(N + 1); vector<bool> aabb(N2 + 1); int s = 3; for (int a = 1; a < N; ++a) { int aa = a * a; for (int b = 1; b < N; ++b) { aabb[aa + b * b] = true; } } for (int c = 1; c <= N; ++c) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= N; ++d) { if (aabb[s1]) { found[d] = true; } s1 += s2; s2 += 2; } } cout << "The values of d <= " << N << " which can't be represented:" << endl; for (int d = 1; d <= N; ++d) { if (!found[d]) { cout << d << " "; } } cout << endl; return 0; }
using System; namespace PythagoreanQuadruples { class Program { const int MAX = 2200; const int MAX2 = MAX * MAX * 2; static void Main(string[] args) { bool[] found = new bool[MAX + 1]; bool[] a2b2 = new bool[MAX2 + 1]; int s = 3; for(int a = 1; a <= MAX; a++) { int a2 = a * a; for (int b=a; b<=MAX; b++) { a2b2[a2 + b * b] = true; } } for (int c = 1; c <= MAX; c++) { int s1 = s; s += 2; int s2 = s; for (int d = c + 1; d <= MAX; d++) { if (a2b2[s1]) found[d] = true; s1 += s2; s2 += 2; } } Console.WriteLine("The values of d <= {0} which can't be represented:", MAX); for (int d = 1; d < MAX; d++) { if (!found[d]) Console.Write("{0} ", d); } Console.WriteLine(); } } }
Preserve the algorithm and functionality while converting the code from C# to C++.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.Console; public enum Colour { Red, Green, White, Yellow, Blue } public enum Nationality { Englishman, Swede, Dane, Norwegian,German } public enum Pet { Dog, Birds, Cats, Horse, Zebra } public enum Drink { Coffee, Tea, Milk, Beer, Water } public enum Smoke { PallMall, Dunhill, Blend, BlueMaster, Prince} public static class ZebraPuzzle { private static (Colour[] colours, Drink[] drinks, Smoke[] smokes, Pet[] pets, Nationality[] nations) _solved; static ZebraPuzzle() { var solve = from colours in Permute<Colour>() where (colours,Colour.White).IsRightOf(colours, Colour.Green) from nations in Permute<Nationality>() where nations[0] == Nationality.Norwegian where (nations, Nationality.Englishman).IsSameIndex(colours, Colour.Red) where (nations,Nationality.Norwegian).IsNextTo(colours,Colour.Blue) from drinks in Permute<Drink>() where drinks[2] == Drink.Milk where (drinks, Drink.Coffee).IsSameIndex(colours, Colour.Green) where (drinks, Drink.Tea).IsSameIndex(nations, Nationality.Dane) from pets in Permute<Pet>() where (pets, Pet.Dog).IsSameIndex(nations, Nationality.Swede) from smokes in Permute<Smoke>() where (smokes, Smoke.PallMall).IsSameIndex(pets, Pet.Birds) where (smokes, Smoke.Dunhill).IsSameIndex(colours, Colour.Yellow) where (smokes, Smoke.Blend).IsNextTo(pets, Pet.Cats) where (smokes, Smoke.Dunhill).IsNextTo(pets, Pet.Horse) where (smokes, Smoke.BlueMaster).IsSameIndex(drinks, Drink.Beer) where (smokes, Smoke.Prince).IsSameIndex(nations, Nationality.German) where (drinks,Drink.Water).IsNextTo(smokes,Smoke.Blend) select (colours, drinks, smokes, pets, nations); _solved = solve.First(); } private static int IndexOf<T>(this T[] arr, T obj) => Array.IndexOf(arr, obj); private static bool IsRightOf<T, U>(this (T[] a, T v) right, U[] a, U v) => right.a.IndexOf(right.v) == a.IndexOf(v) + 1; private static bool IsSameIndex<T, U>(this (T[] a, T v)x, U[] a, U v) => x.a.IndexOf(x.v) == a.IndexOf(v); private static bool IsNextTo<T, U>(this (T[] a, T v)x, U[] a, U v) => (x.a,x.v).IsRightOf(a, v) || (a,v).IsRightOf(x.a,x.v); public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values) { if (values.Count() == 1) return values.ToSingleton(); return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v)); } public static IEnumerable<T[]> Permute<T>() => ToEnumerable<T>().Permutations().Select(p=>p.ToArray()); private static IEnumerable<T> ToSingleton<T>(this T item){ yield return item; } private static IEnumerable<T> ToEnumerable<T>() => Enum.GetValues(typeof(T)).Cast<T>(); public static new String ToString() { var sb = new StringBuilder(); sb.AppendLine("House Colour Drink Nationality Smokes Pet"); sb.AppendLine("───── ────── ──────── ─────────── ────────── ─────"); var (colours, drinks, smokes, pets, nations) = _solved; for (var i = 0; i < 5; i++) sb.AppendLine($"{i+1,5} {colours[i],-6} {drinks[i],-8} {nations[i],-11} {smokes[i],-10} {pets[i],-10}"); return sb.ToString(); } public static void Main(string[] arguments) { var owner = _solved.nations[_solved.pets.IndexOf(Pet.Zebra)]; WriteLine($"The zebra owner is {owner}"); Write(ToString()); Read(); } }
#include <stdio.h> #include <string.h> #define defenum(name, val0, val1, val2, val3, val4) \ enum name { val0, val1, val2, val3, val4 }; \ const char *name ## _str[] = { # val0, # val1, # val2, # val3, # val4 } defenum( Attrib, Color, Man, Drink, Animal, Smoke ); defenum( Colors, Red, Green, White, Yellow, Blue ); defenum( Mans, English, Swede, Dane, German, Norwegian ); defenum( Drinks, Tea, Coffee, Milk, Beer, Water ); defenum( Animals, Dog, Birds, Cats, Horse, Zebra ); defenum( Smokes, PallMall, Dunhill, Blend, BlueMaster, Prince ); void printHouses(int ha[5][5]) { const char **attr_names[5] = {Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str}; printf("%-10s", "House"); for (const char *name : Attrib_str) printf("%-10s", name); printf("\n"); for (int i = 0; i < 5; i++) { printf("%-10d", i); for (int j = 0; j < 5; j++) printf("%-10s", attr_names[j][ha[i][j]]); printf("\n"); } } struct HouseNoRule { int houseno; Attrib a; int v; } housenos[] = { {2, Drink, Milk}, {0, Man, Norwegian} }; struct AttrPairRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5], int i) { return (ha[i][a1] >= 0 && ha[i][a2] >= 0) && ((ha[i][a1] == v1 && ha[i][a2] != v2) || (ha[i][a1] != v1 && ha[i][a2] == v2)); } } pairs[] = { {Man, English, Color, Red}, {Man, Swede, Animal, Dog}, {Man, Dane, Drink, Tea}, {Color, Green, Drink, Coffee}, {Smoke, PallMall, Animal, Birds}, {Smoke, Dunhill, Color, Yellow}, {Smoke, BlueMaster, Drink, Beer}, {Man, German, Smoke, Prince} }; struct NextToRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5], int i) { return (ha[i][a1] == v1) && ((i == 0 && ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2) || (i == 4 && ha[i - 1][a2] != v2) || (ha[i + 1][a2] >= 0 && ha[i + 1][a2] != v2 && ha[i - 1][a2] != v2)); } } nexttos[] = { {Smoke, Blend, Animal, Cats}, {Smoke, Dunhill, Animal, Horse}, {Man, Norwegian, Color, Blue}, {Smoke, Blend, Drink, Water} }; struct LeftOfRule { Attrib a1; int v1; Attrib a2; int v2; bool invalid(int ha[5][5]) { return (ha[0][a2] == v2) || (ha[4][a1] == v1); } bool invalid(int ha[5][5], int i) { return ((i > 0 && ha[i][a1] >= 0) && ((ha[i - 1][a1] == v1 && ha[i][a2] != v2) || (ha[i - 1][a1] != v1 && ha[i][a2] == v2))); } } leftofs[] = { {Color, Green, Color, White} }; bool invalid(int ha[5][5]) { for (auto &rule : leftofs) if (rule.invalid(ha)) return true; for (int i = 0; i < 5; i++) { #define eval_rules(rules) for (auto &rule : rules) if (rule.invalid(ha, i)) return true; eval_rules(pairs); eval_rules(nexttos); eval_rules(leftofs); } return false; } void search(bool used[5][5], int ha[5][5], const int hno, const int attr) { int nexthno, nextattr; if (attr < 4) { nextattr = attr + 1; nexthno = hno; } else { nextattr = 0; nexthno = hno + 1; } if (ha[hno][attr] != -1) { search(used, ha, nexthno, nextattr); } else { for (int i = 0; i < 5; i++) { if (used[attr][i]) continue; used[attr][i] = true; ha[hno][attr] = i; if (!invalid(ha)) { if ((hno == 4) && (attr == 4)) { printHouses(ha); } else { search(used, ha, nexthno, nextattr); } } used[attr][i] = false; } ha[hno][attr] = -1; } } int main() { bool used[5][5] = {}; int ha[5][5]; memset(ha, -1, sizeof(ha)); for (auto &rule : housenos) { ha[rule.houseno][rule.a] = rule.v; used[rule.a][rule.v] = true; } search(used, ha, 0, 0); return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
using System; using System.Linq; class Program { static void Main(string[] args) { double x, xi, y, yi, z, zi; x = 2.0; xi = 0.5; y = 4.0; yi = 0.25; z = x + y; zi = 1.0 / (x + y); var numlist = new[] { x, y, z }; var numlisti = new[] { xi, yi, zi }; var multiplied = numlist.Zip(numlisti, (n1, n2) => { Func<double, double> multiplier = m => n1 * n2 * m; return multiplier; }); foreach (var multiplier in multiplied) Console.WriteLine(multiplier(0.5)); } }
#include <array> #include <iostream> int main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / ( x + y ); const std::array values{x, y, z}; const std::array inverses{xi, yi, zi}; auto multiplier = [](double a, double b) { return [=](double m){return a * b * m;}; }; for(size_t i = 0; i < values.size(); ++i) { auto new_function = multiplier(values[i], inverses[i]); double value = new_function(i + 1.0); std::cout << value << "\n"; } }
Port the provided C++ code into C# while preserving the original functionality.
#include <array> #include <iostream> int main() { double x = 2.0; double xi = 0.5; double y = 4.0; double yi = 0.25; double z = x + y; double zi = 1.0 / ( x + y ); const std::array values{x, y, z}; const std::array inverses{xi, yi, zi}; auto multiplier = [](double a, double b) { return [=](double m){return a * b * m;}; }; for(size_t i = 0; i < values.size(); ++i) { auto new_function = multiplier(values[i], inverses[i]); double value = new_function(i + 1.0); std::cout << value << "\n"; } }
using System; using System.Linq; class Program { static void Main(string[] args) { double x, xi, y, yi, z, zi; x = 2.0; xi = 0.5; y = 4.0; yi = 0.25; z = x + y; zi = 1.0 / (x + y); var numlist = new[] { x, y, z }; var numlisti = new[] { xi, yi, zi }; var multiplied = numlist.Zip(numlisti, (n1, n2) => { Func<double, double> multiplier = m => n1 * n2 * m; return multiplier; }); foreach (var multiplier in multiplied) Console.WriteLine(multiplier(0.5)); } }
Transform the following C# implementation into C++, maintaining the same output and logic.
using System.Collections.Generic; using System.Linq; using System.Text; namespace SokobanSolver { public class SokobanSolver { private class Board { public string Cur { get; internal set; } public string Sol { get; internal set; } public int X { get; internal set; } public int Y { get; internal set; } public Board(string cur, string sol, int x, int y) { Cur = cur; Sol = sol; X = x; Y = y; } } private string destBoard, currBoard; private int playerX, playerY, nCols; SokobanSolver(string[] board) { nCols = board[0].Length; StringBuilder destBuf = new StringBuilder(); StringBuilder currBuf = new StringBuilder(); for (int r = 0; r < board.Length; r++) { for (int c = 0; c < nCols; c++) { char ch = board[r][c]; destBuf.Append(ch != '$' && ch != '@' ? ch : ' '); currBuf.Append(ch != '.' ? ch : ' '); if (ch == '@') { this.playerX = c; this.playerY = r; } } } destBoard = destBuf.ToString(); currBoard = currBuf.ToString(); } private string Move(int x, int y, int dx, int dy, string trialBoard) { int newPlayerPos = (y + dy) * nCols + x + dx; if (trialBoard[newPlayerPos] != ' ') return null; char[] trial = trialBoard.ToCharArray(); trial[y * nCols + x] = ' '; trial[newPlayerPos] = '@'; return new string(trial); } private string Push(int x, int y, int dx, int dy, string trialBoard) { int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx; if (trialBoard[newBoxPos] != ' ') return null; char[] trial = trialBoard.ToCharArray(); trial[y * nCols + x] = ' '; trial[(y + dy) * nCols + x + dx] = '@'; trial[newBoxPos] = '$'; return new string(trial); } private bool IsSolved(string trialBoard) { for (int i = 0; i < trialBoard.Length; i++) if ((destBoard[i] == '.') != (trialBoard[i] == '$')) return false; return true; } private string Solve() { char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } }; int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } }; ISet<string> history = new HashSet<string>(); LinkedList<Board> open = new LinkedList<Board>(); history.Add(currBoard); open.AddLast(new Board(currBoard, string.Empty, playerX, playerY)); while (!open.Count.Equals(0)) { Board item = open.First(); open.RemoveFirst(); string cur = item.Cur; string sol = item.Sol; int x = item.X; int y = item.Y; for (int i = 0; i < dirs.GetLength(0); i++) { string trial = cur; int dx = dirs[i, 0]; int dy = dirs[i, 1]; if (trial[(y + dy) * nCols + x + dx] == '$') { if ((trial = Push(x, y, dx, dy, trial)) != null) { if (!history.Contains(trial)) { string newSol = sol + dirLabels[i, 1]; if (IsSolved(trial)) return newSol; open.AddLast(new Board(trial, newSol, x + dx, y + dy)); history.Add(trial); } } } else if ((trial = Move(x, y, dx, dy, trial)) != null) { if (!history.Contains(trial)) { string newSol = sol + dirLabels[i, 0]; open.AddLast(new Board(trial, newSol, x + dx, y + dy)); history.Add(trial); } } } } return "No solution"; } public static void Main(string[] a) { string level = "#######," + "# #," + "# #," + "#. # #," + "#. $$ #," + "#.$$ #," + "#.# @#," + "#######"; System.Console.WriteLine("Level:\n"); foreach (string line in level.Split(',')) { System.Console.WriteLine(line); } System.Console.WriteLine("\nSolution:\n"); System.Console.WriteLine(new SokobanSolver(level.Split(',')).Solve()); } } }
#include <iostream> #include <string> #include <vector> #include <queue> #include <regex> #include <tuple> #include <set> #include <array> using namespace std; class Board { public: vector<vector<char>> sData, dData; int px, py; Board(string b) { regex pattern("([^\\n]+)\\n?"); sregex_iterator end, iter(b.begin(), b.end(), pattern); int w = 0; vector<string> data; for(; iter != end; ++iter){ data.push_back((*iter)[1]); w = max(w, (*iter)[1].length()); } for(int v = 0; v < data.size(); ++v){ vector<char> sTemp, dTemp; for(int u = 0; u < w; ++u){ if(u > data[v].size()){ sTemp.push_back(' '); dTemp.push_back(' '); }else{ char s = ' ', d = ' ', c = data[v][u]; if(c == '#') s = '#'; else if(c == '.' || c == '*' || c == '+') s = '.'; if(c == '@' || c == '+'){ d = '@'; px = u; py = v; }else if(c == '$' || c == '*') d = '*'; sTemp.push_back(s); dTemp.push_back(d); } } sData.push_back(sTemp); dData.push_back(dTemp); } } bool move(int x, int y, int dx, int dy, vector<vector<char>> &data) { if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') return false; data[y][x] = ' '; data[y+dy][x+dx] = '@'; return true; } bool push(int x, int y, int dx, int dy, vector<vector<char>> &data) { if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ') return false; data[y][x] = ' '; data[y+dy][x+dx] = '@'; data[y+2*dy][x+2*dx] = '*'; return true; } bool isSolved(const vector<vector<char>> &data) { for(int v = 0; v < data.size(); ++v) for(int u = 0; u < data[v].size(); ++u) if((sData[v][u] == '.') ^ (data[v][u] == '*')) return false; return true; } string solve() { set<vector<vector<char>>> visited; queue<tuple<vector<vector<char>>, string, int, int>> open; open.push(make_tuple(dData, "", px, py)); visited.insert(dData); array<tuple<int, int, char, char>, 4> dirs; dirs[0] = make_tuple(0, -1, 'u', 'U'); dirs[1] = make_tuple(1, 0, 'r', 'R'); dirs[2] = make_tuple(0, 1, 'd', 'D'); dirs[3] = make_tuple(-1, 0, 'l', 'L'); while(open.size() > 0){ vector<vector<char>> temp, cur = get<0>(open.front()); string cSol = get<1>(open.front()); int x = get<2>(open.front()); int y = get<3>(open.front()); open.pop(); for(int i = 0; i < 4; ++i){ temp = cur; int dx = get<0>(dirs[i]); int dy = get<1>(dirs[i]); if(temp[y+dy][x+dx] == '*'){ if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){ if(isSolved(temp)) return cSol + get<3>(dirs[i]); open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){ if(isSolved(temp)) return cSol + get<2>(dirs[i]); open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } } } return "No solution"; } }; int main() { string level = "#######\n" "# #\n" "# #\n" "#. # #\n" "#. $$ #\n" "#.$$ #\n" "#.# @#\n" "#######"; Board b(level); cout << level << endl << endl << b.solve() << endl; return 0; }
Rewrite the snippet below in C++ so it works the same as the original C# code.
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) { int gb = 1, dg = ++digs + gb, z; BI t1 = 1, t2 = 9, t3 = 1, te, su = 0, t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1; for (BI n = 0; n < dg; n++) { if (n > 0) t3 *= BI.Pow(n, 6); te = t1 * t2 / t3; if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z); else te /= BI.Pow (10, -z); if (show && n < 10) WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t); su += te; if (te < 10) { if (show) WriteLine("\n{0} iterations required for {1} digits " + "after the decimal point.\n", n, --digs); break; } for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j; t2 += 126 + 532 * (d += 2); } string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) / su / 32 * 3 * BI.Pow((BI)10, dg + 5))); return s[0] + "." + s.Substring(1, digs); } static void Main(string[] args) { WriteLine(dump(70, true)); } }
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } big_int almkvist_giullera(int n) { return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) / (pow(factorial(n), 6) * 3); } int main() { std::cout << "n | Integer portion of nth term\n" << "------------------------------------------------\n"; for (int n = 0; n < 10; ++n) std::cout << n << " | " << std::setw(44) << almkvist_giullera(n) << '\n'; big_float epsilon(pow(big_float(10), -70)); big_float prev = 0, pi = 0; rational sum = 0; for (int n = 0;; ++n) { rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3)); sum += term; pi = sqrt(big_float(1 / sum)); if (abs(pi - prev) < epsilon) break; prev = pi; } std::cout << "\nPi to 70 decimal places is:\n" << std::fixed << std::setprecision(70) << pi << '\n'; }
Produce a functionally identical C# code for the snippet given in C++.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result = 1; for (int i = 2; i <= n; ++i) result *= i; return result; } big_int almkvist_giullera(int n) { return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) / (pow(factorial(n), 6) * 3); } int main() { std::cout << "n | Integer portion of nth term\n" << "------------------------------------------------\n"; for (int n = 0; n < 10; ++n) std::cout << n << " | " << std::setw(44) << almkvist_giullera(n) << '\n'; big_float epsilon(pow(big_float(10), -70)); big_float prev = 0, pi = 0; rational sum = 0; for (int n = 0;; ++n) { rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3)); sum += term; pi = sqrt(big_float(1 / sum)); if (abs(pi - prev) < epsilon) break; prev = pi; } std::cout << "\nPi to 70 decimal places is:\n" << std::fixed << std::setprecision(70) << pi << '\n'; }
using System; using BI = System.Numerics.BigInteger; using static System.Console; class Program { static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) { q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }   static string dump(int digs, bool show = false) { int gb = 1, dg = ++digs + gb, z; BI t1 = 1, t2 = 9, t3 = 1, te, su = 0, t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1; for (BI n = 0; n < dg; n++) { if (n > 0) t3 *= BI.Pow(n, 6); te = t1 * t2 / t3; if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z); else te /= BI.Pow (10, -z); if (show && n < 10) WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t); su += te; if (te < 10) { if (show) WriteLine("\n{0} iterations required for {1} digits " + "after the decimal point.\n", n, --digs); break; } for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j; t2 += 126 + 532 * (d += 2); } string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) / su / 32 * 3 * BI.Pow((BI)10, dg + 5))); return s[0] + "." + s.Substring(1, digs); } static void Main(string[] args) { WriteLine(dump(70, true)); } }
Change the following C# code into C++ without altering its purpose.
using System.Collections.Generic; using System.Linq; using static System.Console; class Program { static bool soas(int n, IEnumerable<int> f) { if (n <= 0) return false; if (f.Contains(n)) return true; switch(n.CompareTo(f.Sum())) { case 1: return false; case 0: return true; case -1: var rf = f.Reverse().ToList(); var d = n - rf[0]; rf.RemoveAt(0); return soas(d, rf) || soas(n, rf); } return true; } static bool ip(int n) { var f = Enumerable.Range(1, n >> 1).Where(d => n % d == 0).ToList(); return Enumerable.Range(1, n - 1).ToList().TrueForAll(i => soas(i, f)); } static void Main() { int c = 0, m = 333; for (int i = 1; i <= m; i += i == 1 ? 1 : 2) if (ip(i) || i == 1) Write("{0,3} {1}", i, ++c % 10 == 0 ? "\n" : ""); Write("\nFound {0} practical numbers between 1 and {1} inclusive.\n", c, m); do Write("\n{0,5} is a{1}practical number.", m = m < 500 ? m << 1 : m * 10 + 6, ip(m) ? " " : "n im"); while (m < 1e4); } }
#include <algorithm> #include <iostream> #include <numeric> #include <sstream> #include <vector> template <typename iterator> bool sum_of_any_subset(int n, iterator begin, iterator end) { if (begin == end) return false; if (std::find(begin, end, n) != end) return true; int total = std::accumulate(begin, end, 0); if (n == total) return true; if (n > total) return false; --end; int d = n - *end; return (d > 0 && sum_of_any_subset(d, begin, end)) || sum_of_any_subset(n, begin, end); } std::vector<int> factors(int n) { std::vector<int> f{1}; for (int i = 2; i * i <= n; ++i) { if (n % i == 0) { f.push_back(i); if (i * i != n) f.push_back(n / i); } } std::sort(f.begin(), f.end()); return f; } bool is_practical(int n) { std::vector<int> f = factors(n); for (int i = 1; i < n; ++i) { if (!sum_of_any_subset(i, f.begin(), f.end())) return false; } return true; } std::string shorten(const std::vector<int>& v, size_t n) { std::ostringstream out; size_t size = v.size(), i = 0; if (n > 0 && size > 0) out << v[i++]; for (; i < n && i < size; ++i) out << ", " << v[i]; if (size > i + n) { out << ", ..."; i = size - n; } for (; i < size; ++i) out << ", " << v[i]; return out.str(); } int main() { std::vector<int> practical; for (int n = 1; n <= 333; ++n) { if (is_practical(n)) practical.push_back(n); } std::cout << "Found " << practical.size() << " practical numbers:\n" << shorten(practical, 10) << '\n'; for (int n : {666, 6666, 66666, 672, 720, 222222}) std::cout << n << " is " << (is_practical(n) ? "" : "not ") << "a practical number.\n"; return 0; }
Change the programming language of this snippet from C# to C++ without modifying what it does.
using System.Linq; using System.Collections.Generic; using TG = System.Tuple<int, int>; using static System.Console; class Program { static void Main(string[] args) { const int mil = (int)1e6; foreach (var amt in new int[] { 1, 2, 6, 12, 18 }) { int lmt = mil * amt, lg = 0, ng, d, ld = 0; var desc = new string[] { "A", "", "De" }; int[] mx = new int[] { 0, 0, 0 }, bi = new int[] { 0, 0, 0 }, c = new int[] { 2, 2, 2 }; WriteLine("For primes up to {0:n0}:", lmt); var pr = PG.Primes(lmt).ToArray(); for (int i = 0; i < pr.Length; i++) { ng = pr[i].Item2; d = ng.CompareTo(lg) + 1; if (ld == d) c[2 - d]++; else { if (c[d] > mx[d]) { mx[d] = c[d]; bi[d] = i - mx[d] - 1; } c[d] = 2; } ld = d; lg = ng; } for (int r = 0; r <= 2; r += 2) { Write("{0}scending, found run of {1} consecutive primes:\n {2} ", desc[r], mx[r] + 1, pr[bi[r]++].Item1); foreach (var itm in pr.Skip(bi[r]).Take(mx[r])) Write("({0}) {1} ", itm.Item2, itm.Item1); WriteLine(r == 0 ? "" : "\n"); } } } } class PG { public static IEnumerable<TG> Primes(int lim) { bool[] flags = new bool[lim + 1]; int j = 3, lj = 2; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return new TG(j, j - lj); lj = j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) { yield return new TG(j, j - lj); lj = j; } } }
#include <cstdint> #include <iostream> #include <vector> #include <primesieve.hpp> void print_diffs(const std::vector<uint64_t>& vec) { for (size_t i = 0, n = vec.size(); i != n; ++i) { if (i != 0) std::cout << " (" << vec[i] - vec[i - 1] << ") "; std::cout << vec[i]; } std::cout << '\n'; } int main() { std::cout.imbue(std::locale("")); std::vector<uint64_t> asc, desc; std::vector<std::vector<uint64_t>> max_asc, max_desc; size_t max_asc_len = 0, max_desc_len = 0; uint64_t prime; const uint64_t limit = 1000000; for (primesieve::iterator pi; (prime = pi.next_prime()) < limit; ) { size_t alen = asc.size(); if (alen > 1 && prime - asc[alen - 1] <= asc[alen - 1] - asc[alen - 2]) asc.erase(asc.begin(), asc.end() - 1); asc.push_back(prime); if (asc.size() >= max_asc_len) { if (asc.size() > max_asc_len) { max_asc_len = asc.size(); max_asc.clear(); } max_asc.push_back(asc); } size_t dlen = desc.size(); if (dlen > 1 && prime - desc[dlen - 1] >= desc[dlen - 1] - desc[dlen - 2]) desc.erase(desc.begin(), desc.end() - 1); desc.push_back(prime); if (desc.size() >= max_desc_len) { if (desc.size() > max_desc_len) { max_desc_len = desc.size(); max_desc.clear(); } max_desc.push_back(desc); } } std::cout << "Longest run(s) of ascending prime gaps up to " << limit << ":\n"; for (const auto& v : max_asc) print_diffs(v); std::cout << "\nLongest run(s) of descending prime gaps up to " << limit << ":\n"; for (const auto& v : max_desc) print_diffs(v); return 0; }
Write a version of this C# function in C++ with identical behavior.
double d = 1; d = 1d; d = 1D; d = 1.2; d = 1.2d; d = .2; d = 12e-12; d = 12E-12; d = 1_234e-1_2; float f = 1; f = 1f; f = 1F; f = 1.2f; f = .2f; f = 12e-12f; f = 12E-12f; f = 1_234e-1_2f; decimal m = 1; m = 1m; m = 1m; m = 1.2m; m = .2m; m = 12e-12m; m = 12E-12m; m = 1_234e-1_2m;
#include <iostream> int main() { auto double1 = 2.5; auto float1 = 2.5f; auto longdouble1 = 2.5l; auto double2 = 2.5e-3; auto float2 = 2.5e3f; auto double3 = 0x1p4; auto float3 = 0xbeefp-8f; std::cout << "\ndouble1: " << double1; std::cout << "\nfloat1: " << float1; std::cout << "\nlongdouble1: " << longdouble1; std::cout << "\ndouble2: " << double2; std::cout << "\nfloat2: " << float2; std::cout << "\ndouble3: " << double3; std::cout << "\nfloat3: " << float3; std::cout << "\n"; }
Write a version of this C# function in C++ with identical behavior.
using System; using static System.Console; class Program { const int lmt = (int)1e6, first = 2500; static int[] f = new int[10]; static void Main(string[] args) { f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++) f[b] = f[a] * (b + 1); int pc = 0, nth = 0, lv = 0; for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) { if (i < first) Write("{0,5:n0}{1}", i, pc++ % 5 == 4 ? "\n" : " "); nth++; lv = i; } Write("\nCount of Erdős primes between 1 and {0:n0}: {1}\n{2} Erdős prime (the last one under {3:n0}): {4:n0}", first, pc, ord(nth), lmt, lv); } static string ord(int n) { return string.Format("{0:n0}", n) + new string[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[n % 10]; } static bool is_erdos_prime(int p) { if (!is_pr(p)) return false; int m = 0, t; while ((t = p - f[m++]) > 0) if (is_pr(t)) return false; return true; bool is_pr(int x) { if (x < 4) return x > 1; if ((x & 1) == 0) return false; for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false; return true; } } }
#include <cstdint> #include <iomanip> #include <iostream> #include <set> #include <primesieve.hpp> class erdos_prime_generator { public: erdos_prime_generator() {} uint64_t next(); private: bool erdos(uint64_t p) const; primesieve::iterator iter_; std::set<uint64_t> primes_; }; uint64_t erdos_prime_generator::next() { uint64_t prime; for (;;) { prime = iter_.next_prime(); primes_.insert(prime); if (erdos(prime)) break; } return prime; } bool erdos_prime_generator::erdos(uint64_t p) const { for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) { if (primes_.find(p - f) != primes_.end()) return false; } return true; } int main() { std::wcout.imbue(std::locale("")); erdos_prime_generator epgen; const int max_print = 2500; const int max_count = 7875; uint64_t p; std::wcout << L"Erd\x151s primes less than " << max_print << L":\n"; for (int count = 1; count <= max_count; ++count) { p = epgen.next(); if (p < max_print) std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\n' : ' '); } std::wcout << L"\n\nThe " << max_count << L"th Erd\x151s prime is " << p << L".\n"; return 0; }
Convert this C# block to C++, preserving its control flow and logic.
using System; using static System.Console; class Program { const int lmt = (int)1e6, first = 2500; static int[] f = new int[10]; static void Main(string[] args) { f[0] = 1; for (int a = 0, b = 1; b < f.Length; a = b++) f[b] = f[a] * (b + 1); int pc = 0, nth = 0, lv = 0; for (int i = 2; i < lmt; i++) if (is_erdos_prime(i)) { if (i < first) Write("{0,5:n0}{1}", i, pc++ % 5 == 4 ? "\n" : " "); nth++; lv = i; } Write("\nCount of Erdős primes between 1 and {0:n0}: {1}\n{2} Erdős prime (the last one under {3:n0}): {4:n0}", first, pc, ord(nth), lmt, lv); } static string ord(int n) { return string.Format("{0:n0}", n) + new string[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}[n % 10]; } static bool is_erdos_prime(int p) { if (!is_pr(p)) return false; int m = 0, t; while ((t = p - f[m++]) > 0) if (is_pr(t)) return false; return true; bool is_pr(int x) { if (x < 4) return x > 1; if ((x & 1) == 0) return false; for (int i = 3; i * i <= x; i += 2) if (x % i == 0) return false; return true; } } }
#include <cstdint> #include <iomanip> #include <iostream> #include <set> #include <primesieve.hpp> class erdos_prime_generator { public: erdos_prime_generator() {} uint64_t next(); private: bool erdos(uint64_t p) const; primesieve::iterator iter_; std::set<uint64_t> primes_; }; uint64_t erdos_prime_generator::next() { uint64_t prime; for (;;) { prime = iter_.next_prime(); primes_.insert(prime); if (erdos(prime)) break; } return prime; } bool erdos_prime_generator::erdos(uint64_t p) const { for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) { if (primes_.find(p - f) != primes_.end()) return false; } return true; } int main() { std::wcout.imbue(std::locale("")); erdos_prime_generator epgen; const int max_print = 2500; const int max_count = 7875; uint64_t p; std::wcout << L"Erd\x151s primes less than " << max_print << L":\n"; for (int count = 1; count <= max_count; ++count) { p = epgen.next(); if (p < max_print) std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\n' : ' '); } std::wcout << L"\n\nThe " << max_count << L"th Erd\x151s prime is " << p << L".\n"; return 0; }
Generate a C# translation of this C++ snippet without changing its computational steps.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size() < 1) return; wid = max_wid; hei = static_cast<int>(puzz.size()) / wid; max = wid * hei; int len = max, c = 0; arr = vector<node>(len, node({ 0, 0 })); weHave = vector<bool>(len + 1, false); for (const auto& s : puzz) { if (s == "*") { max--; arr[c++].val = -1; continue; } arr[c].val = atoi(s.c_str()); if (arr[c].val > 0) weHave[arr[c].val] = true; c++; } solveIt(); c = 0; for (auto&& s : puzz) { if (s == ".") s = std::to_string(arr[c].val); c++; } } private: bool search(int x, int y, int w, int dr) { if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true; node& n = arr[x + y * wid]; n.neighbors = getNeighbors(x, y); if (weHave[w]) { for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == w) if (search(a, b, w + dr, dr)) return true; } } return false; } for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == 0) { arr[a + b * wid].val = w; if (search(a, b, w + dr, dr)) return true; arr[a + b * wid].val = 0; } } } return false; } hood_t getNeighbors(int x, int y) { hood_t retval; for (int xx = 0; xx < 4; xx++) { int a = x + dx[xx], b = y + dy[xx]; if (a < 0 || b < 0 || a >= wid || b >= hei) continue; if (arr[a + b * wid].val > -1) retval.set(xx); } return retval; } void solveIt() { int x, y, z; findStart(x, y, z); if (z == 99999) { cout << "\nCan't find start point!\n"; return; } search(x, y, z + 1, 1); if (z > 1) search(x, y, z - 1, -1); } void findStart(int& x, int& y, int& z) { z = 99999; for (int b = 0; b < hei; b++) for (int a = 0; a < wid; a++) if (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z) { x = a; y = b; z = arr[a + wid * b].val; } } vector<int> dx = vector<int>({ -1, 1, 0, 0 }); vector<int> dy = vector<int>({ 0, 0, -1, 1 }); int wid, hei, max; vector<node> arr; vector<bool> weHave; }; int main(int argc, char* argv[]) { int wid; string p; p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9; istringstream iss(p); vector<string> puzz; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz)); nSolver s; s.solve(puzz, wid); int c = 0; for (const auto& s : puzz) { if (s != "*" && s != ".") { if (atoi(s.c_str()) < 10) cout << "0"; cout << s << " "; } else cout << " "; if (++c >= wid) { cout << endl; c = 0; } } cout << endl << endl; return system("pause"); }
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves; public static void Main() { var numbrixSolver = new Solver(numbrixMoves); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 46, 45, 0, 55, 74, 0, 0 }, { 0, 38, 0, 0, 43, 0, 0, 78, 0 }, { 0, 35, 0, 0, 0, 0, 0, 71, 0 }, { 0, 0, 33, 0, 0, 0, 59, 0, 0 }, { 0, 17, 0, 0, 0, 0, 0, 67, 0 }, { 0, 18, 0, 0, 11, 0, 0, 64, 0 }, { 0, 0, 24, 21, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 11, 12, 15, 18, 21, 62, 61, 0 }, { 0, 6, 0, 0, 0, 0, 0, 60, 0 }, { 0, 33, 0, 0, 0, 0, 0, 57, 0 }, { 0, 32, 0, 0, 0, 0, 0, 56, 0 }, { 0, 37, 0, 1, 0, 0, 0, 73, 0 }, { 0, 38, 0, 0, 0, 0, 0, 72, 0 }, { 0, 43, 44, 47, 48, 51, 76, 77, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Produce a language-to-language conversion: from C# to C++, same semantics.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] numbrixMoves = {(1,0),(0,1),(-1,0),(0,-1)}; private (int dx, int dy)[] moves; public static void Main() { var numbrixSolver = new Solver(numbrixMoves); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 46, 45, 0, 55, 74, 0, 0 }, { 0, 38, 0, 0, 43, 0, 0, 78, 0 }, { 0, 35, 0, 0, 0, 0, 0, 71, 0 }, { 0, 0, 33, 0, 0, 0, 59, 0, 0 }, { 0, 17, 0, 0, 0, 0, 0, 67, 0 }, { 0, 18, 0, 0, 11, 0, 0, 64, 0 }, { 0, 0, 24, 21, 0, 1, 2, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); Print(numbrixSolver.Solve(false, new [,] { { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 11, 12, 15, 18, 21, 62, 61, 0 }, { 0, 6, 0, 0, 0, 0, 0, 60, 0 }, { 0, 33, 0, 0, 0, 0, 0, 57, 0 }, { 0, 32, 0, 0, 0, 0, 0, 56, 0 }, { 0, 37, 0, 1, 0, 0, 0, 73, 0 }, { 0, 38, 0, 0, 0, 0, 0, 72, 0 }, { 0, 43, 44, 47, 48, 51, 76, 77, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, })); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size() < 1) return; wid = max_wid; hei = static_cast<int>(puzz.size()) / wid; max = wid * hei; int len = max, c = 0; arr = vector<node>(len, node({ 0, 0 })); weHave = vector<bool>(len + 1, false); for (const auto& s : puzz) { if (s == "*") { max--; arr[c++].val = -1; continue; } arr[c].val = atoi(s.c_str()); if (arr[c].val > 0) weHave[arr[c].val] = true; c++; } solveIt(); c = 0; for (auto&& s : puzz) { if (s == ".") s = std::to_string(arr[c].val); c++; } } private: bool search(int x, int y, int w, int dr) { if ((w > max && dr > 0) || (w < 1 && dr < 0) || (w == max && weHave[w])) return true; node& n = arr[x + y * wid]; n.neighbors = getNeighbors(x, y); if (weHave[w]) { for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == w) if (search(a, b, w + dr, dr)) return true; } } return false; } for (int d = 0; d < 4; d++) { if (n.neighbors[d]) { int a = x + dx[d], b = y + dy[d]; if (arr[a + b * wid].val == 0) { arr[a + b * wid].val = w; if (search(a, b, w + dr, dr)) return true; arr[a + b * wid].val = 0; } } } return false; } hood_t getNeighbors(int x, int y) { hood_t retval; for (int xx = 0; xx < 4; xx++) { int a = x + dx[xx], b = y + dy[xx]; if (a < 0 || b < 0 || a >= wid || b >= hei) continue; if (arr[a + b * wid].val > -1) retval.set(xx); } return retval; } void solveIt() { int x, y, z; findStart(x, y, z); if (z == 99999) { cout << "\nCan't find start point!\n"; return; } search(x, y, z + 1, 1); if (z > 1) search(x, y, z - 1, -1); } void findStart(int& x, int& y, int& z) { z = 99999; for (int b = 0; b < hei; b++) for (int a = 0; a < wid; a++) if (arr[a + wid * b].val > 0 && arr[a + wid * b].val < z) { x = a; y = b; z = arr[a + wid * b].val; } } vector<int> dx = vector<int>({ -1, 1, 0, 0 }); vector<int> dy = vector<int>({ 0, 0, -1, 1 }); int wid, hei, max; vector<node> arr; vector<bool> weHave; }; int main(int argc, char* argv[]) { int wid; string p; p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; wid = 9; istringstream iss(p); vector<string> puzz; copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter<vector<string> >(puzz)); nSolver s; s.solve(puzz, wid); int c = 0; for (const auto& s : puzz) { if (s != "*" && s != ".") { if (atoi(s.c_str()) < 10) cout << "0"; cout << s << " "; } else cout << " "; if (++c >= wid) { cout << endl; c = 0; } } cout << endl << endl; return system("pause"); }
Write a version of this C++ function in C# with identical behavior.
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; }; } auto Add(auto a, auto b) { return [=](auto f) { return [=](auto x) { return a(f)(b(f)(x)); }; }; } auto Multiply(auto a, auto b) { return [=](auto f) { return a(b(f)); }; } auto Exp(auto a, auto b) { return b(a); } auto IsZero(auto a){ return a([](auto){ return False; })(True); } auto Predecessor(auto a) { return [=](auto f) { return [=](auto x) { return a( [=](auto g) { return [=](auto h){ return h(g(f)); }; } )([=](auto){ return x; })([](auto y){ return y; }); }; }; } auto Subtract(auto a, auto b) { { return b([](auto c){ return Predecessor(c); })(a); }; } namespace { auto Divr(decltype(Zero), auto) { return Zero; } auto Divr(auto a, auto b) { auto a_minus_b = Subtract(a, b); auto isZero = IsZero(a_minus_b); return isZero (Zero) (Successor(Divr(isZero(Zero)(a_minus_b), b))); } } auto Divide(auto a, auto b) { return Divr(Successor(a), b); } template <int N> constexpr auto ToChurch() { if constexpr(N<=0) return Zero; else return Successor(ToChurch<N-1>()); } int ToInt(auto church) { return church([](int n){ return n + 1; })(0); } int main() { auto three = Successor(Successor(Successor(Zero))); auto four = Successor(three); auto six = ToChurch<6>(); auto ten = ToChurch<10>(); auto thousand = Exp(ten, three); std::cout << "\n 3 + 4 = " << ToInt(Add(three, four)); std::cout << "\n 3 * 4 = " << ToInt(Multiply(three, four)); std::cout << "\n 3^4 = " << ToInt(Exp(three, four)); std::cout << "\n 4^3 = " << ToInt(Exp(four, three)); std::cout << "\n 0^0 = " << ToInt(Exp(Zero, Zero)); std::cout << "\n 4 - 3 = " << ToInt(Subtract(four, three)); std::cout << "\n 3 - 4 = " << ToInt(Subtract(three, four)); std::cout << "\n 6 / 3 = " << ToInt(Divide(six, three)); std::cout << "\n 3 / 6 = " << ToInt(Divide(three, six)); auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand)); auto looloolool = Successor(looloolooo); std::cout << "\n 10^9 + 10^6 + 10^3 + 1 = " << ToInt(looloolool); std::cout << "\n golden ratio = " << thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << "\n"; }
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
Generate a C++ translation of this C# snippet without changing its computational steps.
using System; public delegate Church Church(Church f); public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f; public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr); public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1)); public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; } public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
#include <iostream> auto Zero = [](auto){ return [](auto x){ return x; }; }; auto True = [](auto a){ return [=](auto){ return a; }; }; auto False = [](auto){ return [](auto b){ return b; }; }; auto Successor(auto a) { return [=](auto f) { return [=](auto x) { return a(f)(f(x)); }; }; } auto Add(auto a, auto b) { return [=](auto f) { return [=](auto x) { return a(f)(b(f)(x)); }; }; } auto Multiply(auto a, auto b) { return [=](auto f) { return a(b(f)); }; } auto Exp(auto a, auto b) { return b(a); } auto IsZero(auto a){ return a([](auto){ return False; })(True); } auto Predecessor(auto a) { return [=](auto f) { return [=](auto x) { return a( [=](auto g) { return [=](auto h){ return h(g(f)); }; } )([=](auto){ return x; })([](auto y){ return y; }); }; }; } auto Subtract(auto a, auto b) { { return b([](auto c){ return Predecessor(c); })(a); }; } namespace { auto Divr(decltype(Zero), auto) { return Zero; } auto Divr(auto a, auto b) { auto a_minus_b = Subtract(a, b); auto isZero = IsZero(a_minus_b); return isZero (Zero) (Successor(Divr(isZero(Zero)(a_minus_b), b))); } } auto Divide(auto a, auto b) { return Divr(Successor(a), b); } template <int N> constexpr auto ToChurch() { if constexpr(N<=0) return Zero; else return Successor(ToChurch<N-1>()); } int ToInt(auto church) { return church([](int n){ return n + 1; })(0); } int main() { auto three = Successor(Successor(Successor(Zero))); auto four = Successor(three); auto six = ToChurch<6>(); auto ten = ToChurch<10>(); auto thousand = Exp(ten, three); std::cout << "\n 3 + 4 = " << ToInt(Add(three, four)); std::cout << "\n 3 * 4 = " << ToInt(Multiply(three, four)); std::cout << "\n 3^4 = " << ToInt(Exp(three, four)); std::cout << "\n 4^3 = " << ToInt(Exp(four, three)); std::cout << "\n 0^0 = " << ToInt(Exp(Zero, Zero)); std::cout << "\n 4 - 3 = " << ToInt(Subtract(four, three)); std::cout << "\n 3 - 4 = " << ToInt(Subtract(three, four)); std::cout << "\n 6 / 3 = " << ToInt(Divide(six, three)); std::cout << "\n 3 / 6 = " << ToInt(Divide(three, six)); auto looloolooo = Add(Exp(thousand, three), Add(Exp(ten, six), thousand)); auto looloolool = Successor(looloolooo); std::cout << "\n 10^9 + 10^6 + 10^3 + 1 = " << ToInt(looloolool); std::cout << "\n golden ratio = " << thousand([](double x){ return 1.0 + 1.0 / x; })(1.0) << "\n"; }
Convert this C++ snippet to C# and keep its semantics consistent.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2; dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0; dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val == 0 ) { x = a; y = b; z = 1; arr[a + wid * b].val = z; return; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)}, private (int dx, int dy)[] moves; public static void Main() { Print(new Solver(hopidoMoves).Solve(false, ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Port the provided C# code into C++ while preserving the original functionality.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] hopidoMoves = {(-3,0),(0,-3),(0,3),(3,0),(-2,-2),(-2,2),(2,-2),(2,2)}, private (int dx, int dy)[] moves; public static void Main() { Print(new Solver(hopidoMoves).Solve(false, ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx[3] = 2; dy[3] = 2; dx[4] = -3; dy[4] = 0; dx[5] = 3; dy[5] = 0; dx[6] = 0; dy[6] = -3; dx[7] = 0; dy[7] = 3; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val == 0 ) { x = a; y = b; z = 1; arr[a + wid * b].val = z; return; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; wid = 7; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Can you help me rewrite this code in C# instead of C++, keeping it the same logically?
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (const int n,const int i,const int g,const int e,const int l){ if (fe(g,l,false) and fe(g+l,e,true)){ if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);} else { if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;} }} if (l<=gNG-g-i-1) fn(n,i,g,e,l+1); } void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);} ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;} inline bool fe (const int n,const int i, const bool g){ for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g; return true; } int fl (){ if (En == 1) return 1; Tx.set(); Tb.set(); En=0; fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0); return En; }}; std::vector<N<_G>> ng; std::vector<N<_N>> gn; int En, zN, zG; void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);} public: Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) { for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN)); for (int i=0; i<zN; i++) { ng.push_back(N<_G>(n[i],zG)); if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true); }} bool solve(){ int i{}, g{}; for (int l = 0; l<zN; l++) { if ((g = ng[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]); } for (int l = 0; l<zG; l++) { if ((g = gn[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]); } if (i == En) return false; else En = i; if (i == zN+zG) return true; else return solve(); } const std::string toStr() const { std::ostringstream n; for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;} return n.str(); }};
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"), ("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"), ("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM") }) { Solve(x, y); Console.WriteLine(); } } static void Solve(string rowLetters, string columnLetters) { var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray(); var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray(); Solve(r, c); } static void Solve(int[][] rowRuns, int[][] columnRuns) { int len = columnRuns.Length; var rows = rowRuns.Select(row => Generate(len, row)).ToList(); var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList(); Reduce(rows, columns); foreach (var list in rows) { if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced()); else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced()); } } static List<BitSet> Generate(int length, params int[] runs) { var list = new List<BitSet>(); BitSet initial = BitSet.Empty; int[] sums = new int[runs.Length]; sums[0] = 0; for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1; for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]); Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0); return list; } static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) { if (index == runs.Length) { result.Add(current); return; } while (current.Value < max.Value) { Generate(result, max, runs, sums, current, index + 1, shift); current = current.ShiftLeftAt(sums[index] + shift); shift++; } } static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) { for (int count = 1; count > 0; ) { foreach (var (rowIndex, row) in rows.WithIndex()) { var allOn = row.Aggregate((a, b) => a & b); var allOff = row.Aggregate((a, b) => a | b); foreach (var (columnIndex, column) in columns.WithIndex()) { count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex)); count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex)); } } foreach (var (columnIndex, column) in columns.WithIndex()) { var allOn = column.Aggregate((a, b) => a & b); var allOff = column.Aggregate((a, b) => a | b); foreach (var (rowIndex, row) in rows.WithIndex()) { count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex)); count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex)); } } } } static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T element in source) { yield return (i++, element); } } static string Reverse(this string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); } static string Spaced(this IEnumerable<char> s) => string.Join(" ", s); struct BitSet { public static BitSet Empty => default; private readonly int bits; public int Value => bits; private BitSet(int bits) => this.bits = bits; public BitSet Add(int item) => new BitSet(bits | (1 << item)); public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1))); public bool Contains(int item) => (bits & (1 << item)) != 0; public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1))); public override string ToString() => Convert.ToString(bits, 2); public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits); public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits); } }
Change the programming language of this snippet from C# to C++ without modifying what it does.
using System; using System.Collections.Generic; using static System.Linq.Enumerable; public static class NonogramSolver { public static void Main2() { foreach (var (x, y) in new [] { ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"), ("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"), ("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM") }) { Solve(x, y); Console.WriteLine(); } } static void Solve(string rowLetters, string columnLetters) { var r = rowLetters.Split(" ").Select(row => row.Select(s => s - 'A' + 1).ToArray()).ToArray(); var c = columnLetters.Split(" ").Select(column => column.Select(s => s - 'A' + 1).ToArray()).ToArray(); Solve(r, c); } static void Solve(int[][] rowRuns, int[][] columnRuns) { int len = columnRuns.Length; var rows = rowRuns.Select(row => Generate(len, row)).ToList(); var columns = columnRuns.Select(column => Generate(rowRuns.Length, column)).ToList(); Reduce(rows, columns); foreach (var list in rows) { if (list.Count != 1) Console.WriteLine(Repeat('?', len).Spaced()); else Console.WriteLine(list[0].ToString().PadLeft(len, '0').Replace('1', '#').Replace('0', '.').Reverse().Spaced()); } } static List<BitSet> Generate(int length, params int[] runs) { var list = new List<BitSet>(); BitSet initial = BitSet.Empty; int[] sums = new int[runs.Length]; sums[0] = 0; for (int i = 1; i < runs.Length; i++) sums[i] = sums[i - 1] + runs[i - 1] + 1; for (int r = 0; r < runs.Length; r++) initial = initial.AddRange(sums[r], runs[r]); Generate(list, BitSet.Empty.Add(length), runs, sums, initial, 0, 0); return list; } static void Generate(List<BitSet> result, BitSet max, int[] runs, int[] sums, BitSet current, int index, int shift) { if (index == runs.Length) { result.Add(current); return; } while (current.Value < max.Value) { Generate(result, max, runs, sums, current, index + 1, shift); current = current.ShiftLeftAt(sums[index] + shift); shift++; } } static void Reduce(List<List<BitSet>> rows, List<List<BitSet>> columns) { for (int count = 1; count > 0; ) { foreach (var (rowIndex, row) in rows.WithIndex()) { var allOn = row.Aggregate((a, b) => a & b); var allOff = row.Aggregate((a, b) => a | b); foreach (var (columnIndex, column) in columns.WithIndex()) { count = column.RemoveAll(c => allOn.Contains(columnIndex) && !c.Contains(rowIndex)); count += column.RemoveAll(c => !allOff.Contains(columnIndex) && c.Contains(rowIndex)); } } foreach (var (columnIndex, column) in columns.WithIndex()) { var allOn = column.Aggregate((a, b) => a & b); var allOff = column.Aggregate((a, b) => a | b); foreach (var (rowIndex, row) in rows.WithIndex()) { count += row.RemoveAll(r => allOn.Contains(rowIndex) && !r.Contains(columnIndex)); count += row.RemoveAll(r => !allOff.Contains(rowIndex) && r.Contains(columnIndex)); } } } } static IEnumerable<(int index, T element)> WithIndex<T>(this IEnumerable<T> source) { int i = 0; foreach (T element in source) { yield return (i++, element); } } static string Reverse(this string s) { char[] array = s.ToCharArray(); Array.Reverse(array); return new string(array); } static string Spaced(this IEnumerable<char> s) => string.Join(" ", s); struct BitSet { public static BitSet Empty => default; private readonly int bits; public int Value => bits; private BitSet(int bits) => this.bits = bits; public BitSet Add(int item) => new BitSet(bits | (1 << item)); public BitSet AddRange(int start, int count) => new BitSet(bits | (((1 << (start + count)) - 1) - ((1 << start) - 1))); public bool Contains(int item) => (bits & (1 << item)) != 0; public BitSet ShiftLeftAt(int index) => new BitSet((bits >> index << (index + 1)) | (bits & ((1 << index) - 1))); public override string ToString() => Convert.ToString(bits, 2); public static BitSet operator &(BitSet a, BitSet b) => new BitSet(a.bits & b.bits); public static BitSet operator |(BitSet a, BitSet b) => new BitSet(a.bits | b.bits); } }
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (const int n,const int i,const int g,const int e,const int l){ if (fe(g,l,false) and fe(g+l,e,true)){ if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);} else { if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;} }} if (l<=gNG-g-i-1) fn(n,i,g,e,l+1); } void fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);} ng_val fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;} inline bool fe (const int n,const int i, const bool g){ for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g; return true; } int fl (){ if (En == 1) return 1; Tx.set(); Tb.set(); En=0; fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0); return En; }}; std::vector<N<_G>> ng; std::vector<N<_N>> gn; int En, zN, zG; void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);} public: Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) { for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN)); for (int i=0; i<zN; i++) { ng.push_back(N<_G>(n[i],zG)); if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true); }} bool solve(){ int i{}, g{}; for (int l = 0; l<zN; l++) { if ((g = ng[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]); } for (int l = 0; l<zG; l++) { if ((g = gn[l].fl()) == 0) return false; else i+=g; for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]); } if (i == En) return false; else En = i; if (i == zN+zG) return true; else return solve(); } const std::string toStr() const { std::ostringstream n; for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;} return n.str(); }};
Port the provided C++ code into C# while preserving the original functionality.
#include <iomanip> #include <ctime> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <fstream> const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25; class Cell { public: Cell() : val( 0 ), cntOverlap( 0 ) {} char val; int cntOverlap; }; class Word { public: Word( std::string s, int cs, int rs, int ce, int re, int dc, int dr ) : word( s ), cols( cs ), rows( rs ), cole( ce ), rowe( re ), dx( dc ), dy( dr ) {} bool operator ==( const std::string& s ) { return 0 == word.compare( s ); } std::string word; int cols, rows, cole, rowe, dx, dy; }; class words { public: void create( std::string& file ) { std::ifstream f( file.c_str(), std::ios_base::in ); std::string word; while( f >> word ) { if( word.length() < MIN_WORD_LEN || word.length() > WID || word.length() > HEI ) continue; if( word.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" ) != word.npos ) continue; dictionary.push_back( word ); } f.close(); std::random_shuffle( dictionary.begin(), dictionary.end() ); buildPuzzle(); } void printOut() { std::cout << "\t"; for( int x = 0; x < WID; x++ ) std::cout << x << " "; std::cout << "\n\n"; for( int y = 0; y < HEI; y++ ) { std::cout << y << "\t"; for( int x = 0; x < WID; x++ ) std::cout << puzzle[x][y].val << " "; std::cout << "\n"; } size_t wid1 = 0, wid2 = 0; for( size_t x = 0; x < used.size(); x++ ) { if( x & 1 ) { if( used[x].word.length() > wid1 ) wid1 = used[x].word.length(); } else { if( used[x].word.length() > wid2 ) wid2 = used[x].word.length(); } } std::cout << "\n"; std::vector<Word>::iterator w = used.begin(); while( w != used.end() ) { std::cout << std::right << std::setw( wid1 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") (" << ( *w ).cole << ", " << ( *w ).rowe << ")\t"; w++; if( w == used.end() ) break; std::cout << std::setw( wid2 ) << ( *w ).word << " (" << ( *w ).cols << ", " << ( *w ).rows << ") (" << ( *w ).cole << ", " << ( *w ).rowe << ")\n"; w++; } std::cout << "\n\n"; } private: void addMsg() { std::string msg = "ROSETTACODE"; int stp = 9, p = rand() % stp; for( size_t x = 0; x < msg.length(); x++ ) { puzzle[p % WID][p / HEI].val = msg.at( x ); p += rand() % stp + 4; } } int getEmptySpaces() { int es = 0; for( int y = 0; y < HEI; y++ ) { for( int x = 0; x < WID; x++ ) { if( !puzzle[x][y].val ) es++; } } return es; } bool check( std::string word, int c, int r, int dc, int dr ) { for( size_t a = 0; a < word.length(); a++ ) { if( c < 0 || r < 0 || c >= WID || r >= HEI ) return false; if( puzzle[c][r].val && puzzle[c][r].val != word.at( a ) ) return false; c += dc; r += dr; } return true; } bool setWord( std::string word, int c, int r, int dc, int dr ) { if( !check( word, c, r, dc, dr ) ) return false; int sx = c, sy = r; for( size_t a = 0; a < word.length(); a++ ) { if( !puzzle[c][r].val ) puzzle[c][r].val = word.at( a ); else puzzle[c][r].cntOverlap++; c += dc; r += dr; } used.push_back( Word( word, sx, sy, c - dc, r - dr, dc, dr ) ); return true; } bool add2Puzzle( std::string word ) { int x = rand() % WID, y = rand() % HEI, z = rand() % 8; for( int d = z; d < z + 8; d++ ) { switch( d % 8 ) { case 0: if( setWord( word, x, y, 1, 0 ) ) return true; break; case 1: if( setWord( word, x, y, -1, -1 ) ) return true; break; case 2: if( setWord( word, x, y, 0, 1 ) ) return true; break; case 3: if( setWord( word, x, y, 1, -1 ) ) return true; break; case 4: if( setWord( word, x, y, -1, 0 ) ) return true; break; case 5: if( setWord( word, x, y, -1, 1 ) ) return true; break; case 6: if( setWord( word, x, y, 0, -1 ) ) return true; break; case 7: if( setWord( word, x, y, 1, 1 ) ) return true; break; } } return false; } void clearWord() { if( used.size() ) { Word lastW = used.back(); used.pop_back(); for( size_t a = 0; a < lastW.word.length(); a++ ) { if( puzzle[lastW.cols][lastW.rows].cntOverlap == 0 ) { puzzle[lastW.cols][lastW.rows].val = 0; } if( puzzle[lastW.cols][lastW.rows].cntOverlap > 0 ) { puzzle[lastW.cols][lastW.rows].cntOverlap--; } lastW.cols += lastW.dx; lastW.rows += lastW.dy; } } } void buildPuzzle() { addMsg(); int es = 0, cnt = 0; size_t idx = 0; do { for( std::vector<std::string>::iterator w = dictionary.begin(); w != dictionary.end(); w++ ) { if( std::find( used.begin(), used.end(), *w ) != used.end() ) continue; if( add2Puzzle( *w ) ) { es = getEmptySpaces(); if( !es && used.size() >= MIN_WORD_CNT ) return; } } clearWord(); std::random_shuffle( dictionary.begin(), dictionary.end() ); } while( ++cnt < 100 ); } std::vector<Word> used; std::vector<std::string> dictionary; Cell puzzle[WID][HEI]; }; int main( int argc, char* argv[] ) { unsigned s = unsigned( time( 0 ) ); srand( s ); words w; w.create( std::string( "unixdict.txt" ) ); w.printOut(); return 0; }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Wordseach { static class Program { readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}; class Grid { public char[,] Cells = new char[nRows, nCols]; public List<string> Solutions = new List<string>(); public int NumAttempts; } readonly static int nRows = 10; readonly static int nCols = 10; readonly static int gridSize = nRows * nCols; readonly static int minWords = 25; readonly static Random rand = new Random(); static void Main(string[] args) { PrintResult(CreateWordSearch(ReadWords("unixdict.txt"))); } private static List<string> ReadWords(string filename) { int maxLen = Math.Max(nRows, nCols); return System.IO.File.ReadAllLines(filename) .Select(s => s.Trim().ToLower()) .Where(s => Regex.IsMatch(s, "^[a-z]{3," + maxLen + "}$")) .ToList(); } private static Grid CreateWordSearch(List<string> words) { int numAttempts = 0; while (++numAttempts < 100) { words.Shuffle(); var grid = new Grid(); int messageLen = PlaceMessage(grid, "Rosetta Code"); int target = gridSize - messageLen; int cellsFilled = 0; foreach (var word in words) { cellsFilled += TryPlaceWord(grid, word); if (cellsFilled == target) { if (grid.Solutions.Count >= minWords) { grid.NumAttempts = numAttempts; return grid; } else break; } } } return null; } private static int TryPlaceWord(Grid grid, string word) { int randDir = rand.Next(dirs.GetLength(0)); int randPos = rand.Next(gridSize); for (int dir = 0; dir < dirs.GetLength(0); dir++) { dir = (dir + randDir) % dirs.GetLength(0); for (int pos = 0; pos < gridSize; pos++) { pos = (pos + randPos) % gridSize; int lettersPlaced = TryLocation(grid, word, dir, pos); if (lettersPlaced > 0) return lettersPlaced; } } return 0; } private static int TryLocation(Grid grid, string word, int dir, int pos) { int r = pos / nCols; int c = pos % nCols; int len = word.Length; if ((dirs[dir, 0] == 1 && (len + c) > nCols) || (dirs[dir, 0] == -1 && (len - 1) > c) || (dirs[dir, 1] == 1 && (len + r) > nRows) || (dirs[dir, 1] == -1 && (len - 1) > r)) return 0; int rr, cc, i, overlaps = 0; for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i]) { return 0; } cc += dirs[dir, 0]; rr += dirs[dir, 1]; } for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.Cells[rr, cc] == word[i]) overlaps++; else grid.Cells[rr, cc] = word[i]; if (i < len - 1) { cc += dirs[dir, 0]; rr += dirs[dir, 1]; } } int lettersPlaced = len - overlaps; if (lettersPlaced > 0) { grid.Solutions.Add($"{word,-10} ({c},{r})({cc},{rr})"); } return lettersPlaced; } private static int PlaceMessage(Grid grid, string msg) { msg = Regex.Replace(msg.ToUpper(), "[^A-Z]", ""); int messageLen = msg.Length; if (messageLen > 0 && messageLen < gridSize) { int gapSize = gridSize / messageLen; for (int i = 0; i < messageLen; i++) { int pos = i * gapSize + rand.Next(gapSize); grid.Cells[pos / nCols, pos % nCols] = msg[i]; } return messageLen; } return 0; } public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rand.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } private static void PrintResult(Grid grid) { if (grid == null || grid.NumAttempts == 0) { Console.WriteLine("No grid to display"); return; } int size = grid.Solutions.Count; Console.WriteLine("Attempts: " + grid.NumAttempts); Console.WriteLine("Number of words: " + size); Console.WriteLine("\n 0 1 2 3 4 5 6 7 8 9"); for (int r = 0; r < nRows; r++) { Console.Write("\n{0} ", r); for (int c = 0; c < nCols; c++) Console.Write(" {0} ", grid.Cells[r, c]); } Console.WriteLine("\n"); for (int i = 0; i < size - 1; i += 2) { Console.WriteLine("{0} {1}", grid.Solutions[i], grid.Solutions[i + 1]); } if (size % 2 == 1) Console.WriteLine(grid.Solutions[size - 1]); Console.ReadLine(); } } }
Keep all operations the same but rewrite the snippet in C#.
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); public: CWidget(CFactory& parent); ~CWidget(); }; CFactory::CFactory() : m_uiCount(0) {} CFactory::~CFactory() {} CWidget* CFactory::GetWidget() { return new CWidget(*this); } CWidget::CWidget(CFactory& parent) : m_parent(parent) { ++m_parent.m_uiCount; std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } CWidget::~CWidget() { --m_parent.m_uiCount; std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } int main() { CFactory factory; CWidget* pWidget1 = factory.GetWidget(); CWidget* pWidget2 = factory.GetWidget(); delete pWidget1; CWidget* pWidget3 = factory.GetWidget(); delete pWidget3; delete pWidget2; }
using System; using System.Reflection; public class MyClass { private int answer = 42; } public class Program { public static void Main() { var myInstance = new MyClass(); var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance); var answer = fieldInfo.GetValue(myInstance); Console.WriteLine(answer); } }
Keep all operations the same but rewrite the snippet in C++.
using System; using System.Reflection; public class MyClass { private int answer = 42; } public class Program { public static void Main() { var myInstance = new MyClass(); var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance); var answer = fieldInfo.GetValue(myInstance); Console.WriteLine(answer); } }
#include <iostream> class CWidget; class CFactory { friend class CWidget; private: unsigned int m_uiCount; public: CFactory(); ~CFactory(); CWidget* GetWidget(); }; class CWidget { private: CFactory& m_parent; private: CWidget(); CWidget(const CWidget&); CWidget& operator=(const CWidget&); public: CWidget(CFactory& parent); ~CWidget(); }; CFactory::CFactory() : m_uiCount(0) {} CFactory::~CFactory() {} CWidget* CFactory::GetWidget() { return new CWidget(*this); } CWidget::CWidget(CFactory& parent) : m_parent(parent) { ++m_parent.m_uiCount; std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } CWidget::~CWidget() { --m_parent.m_uiCount; std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl; } int main() { CFactory factory; CWidget* pWidget1 = factory.GetWidget(); CWidget* pWidget2 = factory.GetWidget(); delete pWidget1; CWidget* pWidget3 = factory.GetWidget(); delete pWidget3; delete pWidget2; }
Produce a functionally identical C++ code for the snippet given in C#.
using System; using System.IO; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; namespace Object_serialization { [Serializable] public class Being { public bool Alive { get; set; } } [Serializable] public class Animal: Being { public Animal() { } public Animal(long id, string name, bool alive = true) { Id = id; Name = name; Alive = alive; } public long Id { get; set; } public string Name { get; set; } public void Print() { Console.WriteLine("{0}, id={1} is {2}", Name, Id, Alive ? "alive" : "dead"); } } internal class Program { private static void Main() { string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"\\objects.dat"; var n = new List<Animal> { new Animal(1, "Fido"), new Animal(2, "Lupo"), new Animal(7, "Wanda"), new Animal(3, "Kiki", alive: false) }; foreach(Animal animal in n) animal.Print(); using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write)) new BinaryFormatter().Serialize(stream, n); n.Clear(); Console.WriteLine("---------------"); List<Animal> m; using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) m = (List<Animal>) new BinaryFormatter().Deserialize(stream); foreach(Animal animal in m) animal.Print(); } } }
#include <string> #include <fstream> #include <boost/serialization/string.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/base_object.hpp> #include <iostream> class Employee { public : Employee( ) { } Employee ( const std::string &dep , const std::string &namen ) : department( dep ) , name( namen ) { my_id = count++ ; } std::string getName( ) const { return name ; } std::string getDepartment( ) const { return department ; } int getId( ) const { return my_id ; } void setDepartment( const std::string &dep ) { department.assign( dep ) ; } virtual void print( ) { std::cout << "Name: " << name << '\n' ; std::cout << "Id: " << my_id << '\n' ; std::cout << "Department: " << department << '\n' ; } virtual ~Employee( ) { } static int count ; private : std::string name ; std::string department ; int my_id ; friend class boost::serialization::access ; template <class Archive> void serialize( Archive &ar, const unsigned int version ) { ar & my_id ; ar & name ; ar & department ; } } ; class Worker : public Employee { public : Worker( const std::string & dep, const std::string &namen , double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { } Worker( ) { } double getSalary( ) { return salary ; } void setSalary( double pay ) { if ( pay > 0 ) salary = pay ; } virtual void print( ) { Employee::print( ) ; std::cout << "wage per hour: " << salary << '\n' ; } private : double salary ; friend class boost::serialization::access ; template <class Archive> void serialize ( Archive & ar, const unsigned int version ) { ar & boost::serialization::base_object<Employee>( *this ) ; ar & salary ; } } ; int Employee::count = 0 ; int main( ) { std::ofstream storefile( "/home/ulrich/objects.dat" ) ; const Employee emp1( "maintenance" , "Fritz Schmalstieg" ) ; const Employee emp2( "maintenance" , "John Berry" ) ; const Employee emp3( "repair" , "Pawel Lichatschow" ) ; const Employee emp4( "IT" , "Marian Niculescu" ) ; const Worker worker1( "maintenance" , "Laurent Le Chef" , 20 ) ; const Worker worker2 ( "IT" , "Srinivan Taraman" , 55.35 ) ; boost::archive::text_oarchive oar ( storefile ) ; oar << emp1 ; oar << emp2 ; oar << emp3 ; oar << emp4 ; oar << worker1 ; oar << worker2 ; storefile.close( ) ; std::cout << "Reading out the data again\n" ; Employee e1 , e2 , e3 , e4 ; Worker w1, w2 ; std::ifstream sourcefile( "/home/ulrich/objects.dat" ) ; boost::archive::text_iarchive iar( sourcefile ) ; iar >> e1 >> e2 >> e3 >> e4 ; iar >> w1 >> w2 ; sourcefile.close( ) ; std::cout << "And here are the data after deserialization!( abridged):\n" ; e1.print( ) ; e3.print( ) ; w2.print( ) ; return 0 ; }
Rewrite the snippet below in C# so it works the same as the original C++ code.
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
using System; using System.Collections.Generic; namespace Eertree { class Node { public Node(int length) { this.Length = length; this.Edges = new Dictionary<char, int>(); } public Node(int length, Dictionary<char, int> edges, int suffix) { this.Length = length; this.Edges = edges; this.Suffix = suffix; } public int Length { get; set; } public Dictionary<char, int> Edges { get; set; } public int Suffix { get; set; } } class Program { const int EVEN_ROOT = 0; const int ODD_ROOT = 1; static List<Node> Eertree(string s) { List<Node> tree = new List<Node> { new Node(0, new Dictionary<char, int>(), ODD_ROOT), new Node(-1, new Dictionary<char, int>(), ODD_ROOT) }; int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.Length; i++) { char c = s[i]; for (n = suffix; ; n = tree[n].Suffix) { k = tree[n].Length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } if (tree[n].Edges.ContainsKey(c)) { suffix = tree[n].Edges[c]; continue; } suffix = tree.Count; tree.Add(new Node(k + 2)); tree[n].Edges[c] = suffix; if (tree[suffix].Length == 1) { tree[suffix].Suffix = 0; continue; } while (true) { n = tree[n].Suffix; int b = i - tree[n].Length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].Suffix = tree[n].Edges[c]; } return tree; } static List<string> SubPalindromes(List<Node> tree) { List<string> s = new List<string>(); SubPalindromes_children(0, "", tree, s); foreach (var c in tree[1].Edges.Keys) { int m = tree[1].Edges[c]; string ct = c.ToString(); s.Add(ct); SubPalindromes_children(m, ct, tree, s); } return s; } static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) { foreach (var c in tree[n].Edges.Keys) { int m = tree[n].Edges[c]; string p1 = c + p + c; s.Add(p1); SubPalindromes_children(m, p1, tree, s); } } static void Main(string[] args) { List<Node> tree = Eertree("eertree"); List<string> result = SubPalindromes(tree); string listStr = string.Join(", ", result); Console.WriteLine("[{0}]", listStr); } } }
Produce a language-to-language conversion: from C# to C++, same semantics.
using System; using System.Collections.Generic; namespace Eertree { class Node { public Node(int length) { this.Length = length; this.Edges = new Dictionary<char, int>(); } public Node(int length, Dictionary<char, int> edges, int suffix) { this.Length = length; this.Edges = edges; this.Suffix = suffix; } public int Length { get; set; } public Dictionary<char, int> Edges { get; set; } public int Suffix { get; set; } } class Program { const int EVEN_ROOT = 0; const int ODD_ROOT = 1; static List<Node> Eertree(string s) { List<Node> tree = new List<Node> { new Node(0, new Dictionary<char, int>(), ODD_ROOT), new Node(-1, new Dictionary<char, int>(), ODD_ROOT) }; int suffix = ODD_ROOT; int n, k; for (int i = 0; i < s.Length; i++) { char c = s[i]; for (n = suffix; ; n = tree[n].Suffix) { k = tree[n].Length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } if (tree[n].Edges.ContainsKey(c)) { suffix = tree[n].Edges[c]; continue; } suffix = tree.Count; tree.Add(new Node(k + 2)); tree[n].Edges[c] = suffix; if (tree[suffix].Length == 1) { tree[suffix].Suffix = 0; continue; } while (true) { n = tree[n].Suffix; int b = i - tree[n].Length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].Suffix = tree[n].Edges[c]; } return tree; } static List<string> SubPalindromes(List<Node> tree) { List<string> s = new List<string>(); SubPalindromes_children(0, "", tree, s); foreach (var c in tree[1].Edges.Keys) { int m = tree[1].Edges[c]; string ct = c.ToString(); s.Add(ct); SubPalindromes_children(m, ct, tree, s); } return s; } static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) { foreach (var c in tree[n].Edges.Keys) { int m = tree[n].Edges[c]; string p1 = c + p + c; s.Add(p1); SubPalindromes_children(m, p1, tree, s); } } static void Main(string[] args) { List<Node> tree = Eertree("eertree"); List<string> result = SubPalindromes(tree); string listStr = string.Join(", ", result); Console.WriteLine("[{0}]", listStr); } } }
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; constexpr int evenRoot = 0; constexpr int oddRoot = 1; std::vector<Node> eertree(const std::string& s) { std::vector<Node> tree = { Node(0, {}, oddRoot), Node(-1, {}, oddRoot) }; int suffix = oddRoot; int n, k; for (size_t i = 0; i < s.length(); ++i) { char c = s[i]; for (n = suffix; ; n = tree[n].suffix) { k = tree[n].length; int b = i - k - 1; if (b >= 0 && s[b] == c) { break; } } auto it = tree[n].edges.find(c); auto end = tree[n].edges.end(); if (it != end) { suffix = it->second; continue; } suffix = tree.size(); tree.push_back(Node(k + 2)); tree[n].edges[c] = suffix; if (tree[suffix].length == 1) { tree[suffix].suffix = 0; continue; } while (true) { n = tree[n].suffix; int b = i - tree[n].length - 1; if (b >= 0 && s[b] == c) { break; } } tree[suffix].suffix = tree[n].edges[c]; } return tree; } std::vector<std::string> subPalindromes(const std::vector<Node>& tree) { std::vector<std::string> s; std::function<void(int, std::string)> children; children = [&children, &tree, &s](int n, std::string p) { auto it = tree[n].edges.cbegin(); auto end = tree[n].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto m = it->second; std::string pl = c + p + c; s.push_back(pl); children(m, pl); } }; children(0, ""); auto it = tree[1].edges.cbegin(); auto end = tree[1].edges.cend(); for (; it != end; it = std::next(it)) { auto c = it->first; auto n = it->second; std::string ct(1, c); s.push_back(ct); children(n, ct); } return s; } int main() { using namespace std; auto tree = eertree("eertree"); auto pal = subPalindromes(tree); auto it = pal.cbegin(); auto end = pal.cend(); cout << "["; if (it != end) { cout << it->c_str(); it++; } while (it != end) { cout << ", " << it->c_str(); it++; } cout << "]" << endl; return 0; }
Translate the given C++ code snippet into C# without altering its behavior.
#include <stdio.h> #include <math.h> int p(int year) { return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7; } int is_long_year(int year) { return p(year) == 4 || p(year - 1) == 3; } void print_long_years(int from, int to) { for (int year = from; year <= to; ++year) { if (is_long_year(year)) { printf("%d ", year); } } } int main() { printf("Long (53 week) years between 1800 and 2100\n\n"); print_long_years(1800, 2100); printf("\n"); return 0; }
using static System.Console; using System.Collections.Generic; using System.Linq; using System.Globalization; public static class Program { public static void Main() { WriteLine("Long years in the 21st century:"); WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53))); } public static IEnumerable<int> To(this int start, int end) { for (int i = start; i < end; i++) yield return i; } }
Change the following C# code into C++ without altering its purpose.
using System; using System.Collections.Generic; using System.Linq; namespace ZumkellerNumbers { class Program { static List<int> GetDivisors(int n) { List<int> divs = new List<int> { 1, n }; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.Add(i); if (i != j) { divs.Add(j); } } } return divs; } static bool IsPartSum(List<int> divs, int sum) { if (sum == 0) { return true; } var le = divs.Count; if (le == 0) { return false; } var last = divs[le - 1]; List<int> newDivs = new List<int>(); for (int i = 0; i < le - 1; i++) { newDivs.Add(divs[i]); } if (last > sum) { return IsPartSum(newDivs, sum); } return IsPartSum(newDivs, sum) || IsPartSum(newDivs, sum - last); } static bool IsZumkeller(int n) { var divs = GetDivisors(n); var sum = divs.Sum(); if (sum % 2 == 1) { return false; } if (n % 2 == 1) { var abundance = sum - 2 * n; return abundance > 0 && abundance % 2 == 0; } return IsPartSum(divs, sum / 2); } static void Main() { Console.WriteLine("The first 220 Zumkeller numbers are:"); int i = 2; for (int count = 0; count < 220; i++) { if (IsZumkeller(i)) { Console.Write("{0,3} ", i); count++; if (count % 20 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (IsZumkeller(i)) { Console.Write("{0,5} ", i); count++; if (count % 10 == 0) { Console.WriteLine(); } } } Console.WriteLine("\nThe first 40 odd Zumkeller numbers which don't end in 5 are:"); i = 3; for (int count = 0; count < 40; i += 2) { if (i % 10 != 5 && IsZumkeller(i)) { Console.Write("{0,7} ", i); count++; if (count % 8 == 0) { Console.WriteLine(); } } } } } }
#include <iostream"> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> #include <numeric> using namespace std; const uint* binary(uint n, uint length); uint sum_subset_unrank_bin(const vector<uint>& d, uint r); vector<uint> factors(uint x); bool isPrime(uint number); bool isZum(uint n); ostream& operator<<(ostream& os, const vector<uint>& zumz) { for (uint i = 0; i < zumz.size(); i++) { if (i % 10 == 0) os << endl; os << setw(10) << zumz[i] << ' '; } return os; } int main() { cout << "First 220 Zumkeller numbers:" << endl; vector<uint> zumz; for (uint n = 2; zumz.size() < 220; n++) if (isZum(n)) zumz.push_back(n); cout << zumz << endl << endl; cout << "First 40 odd Zumkeller numbers:" << endl; vector<uint> zumz2; for (uint n = 2; zumz2.size() < 40; n++) if (n % 2 && isZum(n)) zumz2.push_back(n); cout << zumz2 << endl << endl; cout << "First 40 odd Zumkeller numbers not ending in 5:" << endl; vector<uint> zumz3; for (uint n = 2; zumz3.size() < 40; n++) if (n % 2 && (n % 10) != 5 && isZum(n)) zumz3.push_back(n); cout << zumz3 << endl << endl; return 0; } const uint* binary(uint n, uint length) { uint* bin = new uint[length]; fill(bin, bin + length, 0); for (uint i = 0; n > 0; i++) { uint rem = n % 2; n /= 2; if (rem) bin[length - 1 - i] = 1; } return bin; } uint sum_subset_unrank_bin(const vector<uint>& d, uint r) { vector<uint> subset; const uint* bits = binary(r, d.size() - 1); for (uint i = 0; i < d.size() - 1; i++) if (bits[i]) subset.push_back(d[i]); delete[] bits; return accumulate(subset.begin(), subset.end(), 0u); } vector<uint> factors(uint x) { vector<uint> result; for (uint i = 1; i * i <= x; i++) { if (x % i == 0) { result.push_back(i); if (x / i != i) result.push_back(x / i); } } sort(result.begin(), result.end()); return result; } bool isPrime(uint number) { if (number < 2) return false; if (number == 2) return true; if (number % 2 == 0) return false; for (uint i = 3; i * i <= number; i += 2) if (number % i == 0) return false; return true; } bool isZum(uint n) { if (isPrime(n)) return false; const auto d = factors(n); uint s = accumulate(d.begin(), d.end(), 0u); if (s % 2 || s < 2 * n) return false; if (n % 2 || d.size() >= 24) return true; if (!(s % 2) && d[d.size() - 1] <= s / 2) for (uint x = 2; (uint) log2(x) < (d.size() - 1); x++) if (sum_subset_unrank_bin(d, x) == s / 2) return true; return false; }
Rewrite the snippet below in C# so it works the same as the original C++ code.
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; map original{ {"name", "Rocket Skates"}, {"price", "12.75"}, {"color", "yellow"} }; map update{ {"price", "15.25"}, {"color", "red"}, {"year", "1974"} }; map merged(merge(original, update)); for (auto&& i : merged) std::cout << "key: " << i.first << ", value: " << i.second << '\n'; return 0; }
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var baseData = new Dictionary<string, object> { ["name"] = "Rocket Skates", ["price"] = 12.75, ["color"] = "yellow" }; var updateData = new Dictionary<string, object> { ["price"] = 15.25, ["color"] = "red", ["year"] = 1974 }; var mergedData = new Dictionary<string, object>(); foreach (var entry in baseData.Concat(updateData)) { mergedData[entry.Key] = entry.Value; } foreach (var entry in mergedData) { Console.WriteLine(entry); } } }
Transform the following C# implementation into C++, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var baseData = new Dictionary<string, object> { ["name"] = "Rocket Skates", ["price"] = 12.75, ["color"] = "yellow" }; var updateData = new Dictionary<string, object> { ["price"] = 15.25, ["color"] = "red", ["year"] = 1974 }; var mergedData = new Dictionary<string, object>(); foreach (var entry in baseData.Concat(updateData)) { mergedData[entry.Key] = entry.Value; } foreach (var entry in mergedData) { Console.WriteLine(entry); } } }
#include <iostream> #include <string> #include <map> template<typename map_type> map_type merge(const map_type& original, const map_type& update) { map_type result(update); result.insert(original.begin(), original.end()); return result; } int main() { typedef std::map<std::string, std::string> map; map original{ {"name", "Rocket Skates"}, {"price", "12.75"}, {"color", "yellow"} }; map update{ {"price", "15.25"}, {"color", "red"}, {"year", "1974"} }; map merged(merge(original, update)); for (auto&& i : merged) std::cout << "key: " << i.first << ", value: " << i.second << '\n'; return 0; }
Write a version of this C++ function in C# with identical behavior.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: "; auto x0 = 1L, x1 = 1L; std::cout << x0 << ", " << x1; for (auto i = 1u; i <= N - 1 - 1; i++) { auto x2 = b * x1 + x0; std::cout << ", " << x2; x0 = x1; x1 = x2; } std::cout << std::endl; } template<const ushort P> void metallic(ulong b) { using namespace boost::multiprecision; using bfloat = number<cpp_dec_float<P+1>>; bfloat x0(1), x1(1); auto prev = bfloat(1).str(P+1); for (auto i = 0u;;) { i++; bfloat x2(b * x1 + x0); auto thiz = bfloat(x2 / x1).str(P+1); if (prev == thiz) { std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl; break; } prev = thiz; x0 = x1; x1 = x2; } } int main() { for (auto b = 0L; b < 10L; b++) { lucas<15>(b); metallic<32>(b); } std::cout << "Golden ratio, where b = 1:" << std::endl; metallic<256>(1); return 0; }
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); } }
Ensure the translated C++ code behaves exactly like the original C# snippet.
using static System.Math; using static System.Console; using BI = System.Numerics.BigInteger; class Program { static BI IntSqRoot(BI v, BI res) { BI term = 0, d = 0, dl = 1; while (dl != d) { term = v / res; res = (res + term) >> 1; dl = d; d = term - res; } return term; } static string doOne(int b, int digs) { int s = b * b + 4; BI g = (BI)(Sqrt((double)s) * Pow(10, ++digs)), bs = IntSqRoot(s * BI.Parse('1' + new string('0', digs << 1)), g); bs += b * BI.Parse('1' + new string('0', digs)); bs >>= 1; bs += 4; string st = bs.ToString(); return string.Format("{0}.{1}", st[0], st.Substring(1, --digs)); } static string divIt(BI a, BI b, int digs) { int al = a.ToString().Length, bl = b.ToString().Length; a *= BI.Pow(10, ++digs << 1); b *= BI.Pow(10, digs); string s = (a / b + 5).ToString(); return s[0] + "." + s.Substring(1, --digs); } static string joined(BI[] x) { int[] wids = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; string res = ""; for (int i = 0; i < x.Length; i++) res += string.Format("{0," + (-wids[i]).ToString() + "} ", x[i]); return res; } static void Main(string[] args) { WriteLine("Metal B Sq.Rt Iters /---- 32 decimal place value ----\\ Matches Sq.Rt Calc"); int k; string lt, t = ""; BI n, nm1, on; for (int b = 0; b < 10; b++) { BI[] lst = new BI[15]; lst[0] = lst[1] = 1; for (int i = 2; i < 15; i++) lst[i] = b * lst[i - 1] + lst[i - 2]; n = lst[14]; nm1 = lst[13]; k = 0; for (int j = 13; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 32))) k = b == 0 ? 1 : j; on = n; n = b * n + nm1; nm1 = on; } WriteLine("{0,4} {1} {2,2} {3, 2} {4} {5}\n{6,19} {7}", "Pt Au Ag CuSn Cu Ni Al Fe Sn Pb" .Split(' ')[b], b, b * b + 4, k, t, t == doOne(b, 32), "", joined(lst)); } n = nm1 =1; k = 0; for (int j = 1; k == 0; j++) { lt = t; if (lt == (t = divIt(n, nm1, 256))) k = j; on = n; n += nm1; nm1 = on; } WriteLine("\nAu to 256 digits:"); WriteLine(t); WriteLine("Iteration count: {0} Matched Sq.Rt Calc: {1}", k, t == doOne(1, 256)); } }
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b << ":\nFirst " << N << " elements: "; auto x0 = 1L, x1 = 1L; std::cout << x0 << ", " << x1; for (auto i = 1u; i <= N - 1 - 1; i++) { auto x2 = b * x1 + x0; std::cout << ", " << x2; x0 = x1; x1 = x2; } std::cout << std::endl; } template<const ushort P> void metallic(ulong b) { using namespace boost::multiprecision; using bfloat = number<cpp_dec_float<P+1>>; bfloat x0(1), x1(1); auto prev = bfloat(1).str(P+1); for (auto i = 0u;;) { i++; bfloat x2(b * x1 + x0); auto thiz = bfloat(x2 / x1).str(P+1); if (prev == thiz) { std::cout << "Value after " << i << " iteration" << (i == 1 ? ": " : "s: ") << thiz << std::endl << std::endl; break; } prev = thiz; x0 = x1; x1 = x2; } } int main() { for (auto b = 0L; b < 10L; b++) { lucas<15>(b); metallic<32>(b); } std::cout << "Golden ratio, where b = 1:" << std::endl; metallic<256>(1); return 0; }
Produce a functionally identical C# code for the snippet given in C++.
#include <stdexcept> int main() { throw std::runtime_error("boom"); }
int a=0,b=1/a;
Can you help me rewrite this code in C++ instead of C#, keeping it the same logically?
interface IEatable { void Eat(); }
template<typename T> struct can_eat { private: template<typename U, void (U::*)()> struct SFINAE {}; template<typename U> static char Test(SFINAE<U, &U::eat>*); template<typename U> static int Test(...); public: static constexpr bool value = sizeof(Test<T>(0)) == sizeof(char); }; struct potato { void eat(); }; struct brick {}; template<typename T> class FoodBox { static_assert(can_eat<T>::value, "Only edible items are allowed in foodbox"); }; int main() { FoodBox<potato> lunch; }
Can you help me rewrite this code in C++ instead of C#, keeping it the same logically?
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace MarkovChainTextGenerator { class Program { static string Join(string a, string b) { return a + " " + b; } static string Markov(string filePath, int keySize, int outputSize) { if (keySize < 1) throw new ArgumentException("Key size can't be less than 1"); string body; using (StreamReader sr = new StreamReader(filePath)) { body = sr.ReadToEnd(); } var words = body.Split(); if (outputSize < keySize || words.Length < outputSize) { throw new ArgumentException("Output size is out of range"); } Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); for (int i = 0; i < words.Length - keySize; i++) { var key = words.Skip(i).Take(keySize).Aggregate(Join); string value; if (i + keySize < words.Length) { value = words[i + keySize]; } else { value = ""; } if (dict.ContainsKey(key)) { dict[key].Add(value); } else { dict.Add(key, new List<string>() { value }); } } Random rand = new Random(); List<string> output = new List<string>(); int n = 0; int rn = rand.Next(dict.Count); string prefix = dict.Keys.Skip(rn).Take(1).Single(); output.AddRange(prefix.Split()); while (true) { var suffix = dict[prefix]; if (suffix.Count == 1) { if (suffix[0] == "") { return output.Aggregate(Join); } output.Add(suffix[0]); } else { rn = rand.Next(suffix.Count); output.Add(suffix[rn]); } if (output.Count >= outputSize) { return output.Take(outputSize).Aggregate(Join); } n++; prefix = output.Skip(n).Take(keySize).Aggregate(Join); } } static void Main(string[] args) { Console.WriteLine(Markov("alice_oz.txt", 3, 200)); } } }
#include <ctime> #include <iostream> #include <algorithm> #include <fstream> #include <string> #include <vector> #include <map> class markov { public: void create( std::string& file, unsigned int keyLen, unsigned int words ) { std::ifstream f( file.c_str(), std::ios_base::in ); fileBuffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() ); f.close(); if( fileBuffer.length() < 1 ) return; createDictionary( keyLen ); createText( words - keyLen ); } private: void createText( int w ) { std::string key, first, second; size_t next; std::map<std::string, std::vector<std::string> >::iterator it = dictionary.begin(); std::advance( it, rand() % dictionary.size() ); key = ( *it ).first; std::cout << key; while( true ) { std::vector<std::string> d = dictionary[key]; if( d.size() < 1 ) break; second = d[rand() % d.size()]; if( second.length() < 1 ) break; std::cout << " " << second; if( --w < 0 ) break; next = key.find_first_of( 32, 0 ); first = key.substr( next + 1 ); key = first + " " + second; } std::cout << "\n"; } void createDictionary( unsigned int kl ) { std::string w1, key; size_t wc = 0, pos, next; next = fileBuffer.find_first_not_of( 32, 0 ); if( next == std::string::npos ) return; while( wc < kl ) { pos = fileBuffer.find_first_of( ' ', next ); w1 = fileBuffer.substr( next, pos - next ); key += w1 + " "; next = fileBuffer.find_first_not_of( 32, pos + 1 ); if( next == std::string::npos ) return; wc++; } key = key.substr( 0, key.size() - 1 ); while( true ) { next = fileBuffer.find_first_not_of( 32, pos + 1 ); if( next == std::string::npos ) return; pos = fileBuffer.find_first_of( 32, next ); w1 = fileBuffer.substr( next, pos - next ); if( w1.size() < 1 ) break; if( std::find( dictionary[key].begin(), dictionary[key].end(), w1 ) == dictionary[key].end() ) dictionary[key].push_back( w1 ); key = key.substr( key.find_first_of( 32 ) + 1 ) + " " + w1; } } std::string fileBuffer; std::map<std::string, std::vector<std::string> > dictionary; }; int main( int argc, char* argv[] ) { srand( unsigned( time( 0 ) ) ); markov m; m.create( std::string( "alice_oz.txt" ), 3, 200 ); return 0; }
Generate an equivalent C++ version of this C# code.
using static System.Linq.Enumerable; using static System.String; using static System.Console; using System.Collections.Generic; using System; using EdgeList = System.Collections.Generic.List<(int node, double weight)>; public static class Dijkstra { public static void Main() { Graph graph = new Graph(6); Func<char, int> id = c => c - 'a'; Func<int , char> name = i => (char)(i + 'a'); foreach (var (start, end, cost) in new [] { ('a', 'b', 7), ('a', 'c', 9), ('a', 'f', 14), ('b', 'c', 10), ('b', 'd', 15), ('c', 'd', 11), ('c', 'f', 2), ('d', 'e', 6), ('e', 'f', 9), }) { graph.AddEdge(id(start), id(end), cost); } var path = graph.FindPath(id('a')); for (int d = id('b'); d <= id('f'); d++) { WriteLine(Join(" -> ", Path(id('a'), d).Select(p => $"{name(p.node)}({p.distance})").Reverse())); } IEnumerable<(double distance, int node)> Path(int start, int destination) { yield return (path[destination].distance, destination); for (int i = destination; i != start; i = path[i].prev) { yield return (path[path[i].prev].distance, path[i].prev); } } } } sealed class Graph { private readonly List<EdgeList> adjacency; public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList(); public int Count => adjacency.Count; public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e); public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0; public bool AddEdge(int s, int e, double weight) { if (HasEdge(s, e)) return false; adjacency[s].Add((e, weight)); return true; } public (double distance, int prev)[] FindPath(int start) { var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray(); info[start].distance = 0; var visited = new System.Collections.BitArray(adjacency.Count); var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance)); heap.Push((start, 0)); while (heap.Count > 0) { var current = heap.Pop(); if (visited[current.node]) continue; var edges = adjacency[current.node]; for (int n = 0; n < edges.Count; n++) { int v = edges[n].node; if (visited[v]) continue; double alt = info[current.node].distance + edges[n].weight; if (alt < info[v].distance) { info[v] = (alt, current.node); heap.Push((v, alt)); } } visited[current.node] = true; } return info; } } sealed class Heap<T> { private readonly IComparer<T> comparer; private readonly List<T> list = new List<T> { default }; public Heap() : this(default(IComparer<T>)) { } public Heap(IComparer<T> comparer) { this.comparer = comparer ?? Comparer<T>.Default; } public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { } public int Count => list.Count - 1; public void Push(T element) { list.Add(element); SiftUp(list.Count - 1); } public T Pop() { T result = list[1]; list[1] = list[list.Count - 1]; list.RemoveAt(list.Count - 1); SiftDown(1); return result; } private static int Parent(int i) => i / 2; private static int Left(int i) => i * 2; private static int Right(int i) => i * 2 + 1; private void SiftUp(int i) { while (i > 1) { int parent = Parent(i); if (comparer.Compare(list[i], list[parent]) > 0) return; (list[parent], list[i]) = (list[i], list[parent]); i = parent; } } private void SiftDown(int i) { for (int left = Left(i); left < list.Count; left = Left(i)) { int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i; int right = Right(i); if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right; if (smallest == i) return; (list[i], list[smallest]) = (list[smallest], list[i]); i = smallest; } } }
#include <iostream> #include <vector> #include <string> #include <list> #include <limits> #include <set> #include <utility> #include <algorithm> #include <iterator> typedef int vertex_t; typedef double weight_t; const weight_t max_weight = std::numeric_limits<double>::infinity(); struct neighbor { vertex_t target; weight_t weight; neighbor(vertex_t arg_target, weight_t arg_weight) : target(arg_target), weight(arg_weight) { } }; typedef std::vector<std::vector<neighbor> > adjacency_list_t; void DijkstraComputePaths(vertex_t source, const adjacency_list_t &adjacency_list, std::vector<weight_t> &min_distance, std::vector<vertex_t> &previous) { int n = adjacency_list.size(); min_distance.clear(); min_distance.resize(n, max_weight); min_distance[source] = 0; previous.clear(); previous.resize(n, -1); std::set<std::pair<weight_t, vertex_t> > vertex_queue; vertex_queue.insert(std::make_pair(min_distance[source], source)); while (!vertex_queue.empty()) { weight_t dist = vertex_queue.begin()->first; vertex_t u = vertex_queue.begin()->second; vertex_queue.erase(vertex_queue.begin()); const std::vector<neighbor> &neighbors = adjacency_list[u]; for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin(); neighbor_iter != neighbors.end(); neighbor_iter++) { vertex_t v = neighbor_iter->target; weight_t weight = neighbor_iter->weight; weight_t distance_through_u = dist + weight; if (distance_through_u < min_distance[v]) { vertex_queue.erase(std::make_pair(min_distance[v], v)); min_distance[v] = distance_through_u; previous[v] = u; vertex_queue.insert(std::make_pair(min_distance[v], v)); } } } } std::list<vertex_t> DijkstraGetShortestPathTo( vertex_t vertex, const std::vector<vertex_t> &previous) { std::list<vertex_t> path; for ( ; vertex != -1; vertex = previous[vertex]) path.push_front(vertex); return path; } int main() { adjacency_list_t adjacency_list(6); adjacency_list[0].push_back(neighbor(1, 7)); adjacency_list[0].push_back(neighbor(2, 9)); adjacency_list[0].push_back(neighbor(5, 14)); adjacency_list[1].push_back(neighbor(0, 7)); adjacency_list[1].push_back(neighbor(2, 10)); adjacency_list[1].push_back(neighbor(3, 15)); adjacency_list[2].push_back(neighbor(0, 9)); adjacency_list[2].push_back(neighbor(1, 10)); adjacency_list[2].push_back(neighbor(3, 11)); adjacency_list[2].push_back(neighbor(5, 2)); adjacency_list[3].push_back(neighbor(1, 15)); adjacency_list[3].push_back(neighbor(2, 11)); adjacency_list[3].push_back(neighbor(4, 6)); adjacency_list[4].push_back(neighbor(3, 6)); adjacency_list[4].push_back(neighbor(5, 9)); adjacency_list[5].push_back(neighbor(0, 14)); adjacency_list[5].push_back(neighbor(2, 2)); adjacency_list[5].push_back(neighbor(4, 9)); std::vector<weight_t> min_distance; std::vector<vertex_t> previous; DijkstraComputePaths(0, adjacency_list, min_distance, previous); std::cout << "Distance from 0 to 4: " << min_distance[4] << std::endl; std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous); std::cout << "Path : "; std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, " ")); std::cout << std::endl; return 0; }
Rewrite the snippet below in C++ so it works the same as the original C# code.
using System; using System.Text; namespace GeometricAlgebra { struct Vector { private readonly double[] dims; public Vector(double[] da) { dims = da; } public static Vector operator -(Vector v) { return v * -1.0; } public static Vector operator +(Vector lhs, Vector rhs) { var result = new double[32]; Array.Copy(lhs.dims, 0, result, 0, lhs.Length); for (int i = 0; i < result.Length; i++) { result[i] = lhs[i] + rhs[i]; } return new Vector(result); } public static Vector operator *(Vector lhs, Vector rhs) { var result = new double[32]; for (int i = 0; i < lhs.Length; i++) { if (lhs[i] != 0.0) { for (int j = 0; j < lhs.Length; j++) { if (rhs[j] != 0.0) { var s = ReorderingSign(i, j) * lhs[i] * rhs[j]; var k = i ^ j; result[k] += s; } } } } return new Vector(result); } public static Vector operator *(Vector v, double scale) { var result = (double[])v.dims.Clone(); for (int i = 0; i < result.Length; i++) { result[i] *= scale; } return new Vector(result); } public double this[int key] { get { return dims[key]; } set { dims[key] = value; } } public int Length { get { return dims.Length; } } public Vector Dot(Vector rhs) { return (this * rhs + rhs * this) * 0.5; } private static int BitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F0F0F; i += (i >> 8); i += (i >> 16); return i & 0x0000003F; } private static double ReorderingSign(int i, int j) { int k = i >> 1; int sum = 0; while (k != 0) { sum += BitCount(k & j); k >>= 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } public override string ToString() { var it = dims.GetEnumerator(); StringBuilder sb = new StringBuilder("["); if (it.MoveNext()) { sb.Append(it.Current); } while (it.MoveNext()) { sb.Append(", "); sb.Append(it.Current); } sb.Append(']'); return sb.ToString(); } } class Program { static double[] DoubleArray(uint size) { double[] result = new double[size]; for (int i = 0; i < size; i++) { result[i] = 0.0; } return result; } static Vector E(int n) { if (n > 4) { throw new ArgumentException("n must be less than 5"); } var result = new Vector(DoubleArray(32)); result[1 << n] = 1.0; return result; } static readonly Random r = new Random(); static Vector RandomVector() { var result = new Vector(DoubleArray(32)); for (int i = 0; i < 5; i++) { var singleton = new double[] { r.NextDouble() }; result += new Vector(singleton) * E(i); } return result; } static Vector RandomMultiVector() { var result = new Vector(DoubleArray(32)); for (int i = 0; i < result.Length; i++) { result[i] = r.NextDouble(); } return result; } static void Main() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i < j) { if (E(i).Dot(E(j))[0] != 0.0) { Console.WriteLine("Unexpected non-null sclar product."); return; } } else if (i == j) { if ((E(i).Dot(E(j)))[0] == 0.0) { Console.WriteLine("Unexpected null sclar product."); } } } } var a = RandomMultiVector(); var b = RandomMultiVector(); var c = RandomMultiVector(); var x = RandomVector(); Console.WriteLine((a * b) * c); Console.WriteLine(a * (b * c)); Console.WriteLine(); Console.WriteLine(a * (b + c)); Console.WriteLine(a * b + a * c); Console.WriteLine(); Console.WriteLine((a + b) * c); Console.WriteLine(a * c + b * c); Console.WriteLine(); Console.WriteLine(x * x); } } }
#include <algorithm> #include <iostream> #include <random> #include <vector> double uniform01() { static std::default_random_engine generator; static std::uniform_real_distribution<double> distribution(0.0, 1.0); return distribution(generator); } int bitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (i + (i >> 4)) & 0x0F0F0F0F; i += (i >> 8); i += (i >> 16); return i & 0x0000003F; } double reorderingSign(int i, int j) { int k = i >> 1; int sum = 0; while (k != 0) { sum += bitCount(k & j); k = k >> 1; } return ((sum & 1) == 0) ? 1.0 : -1.0; } struct MyVector { public: MyVector(const std::vector<double> &da) : dims(da) { } double &operator[](size_t i) { return dims[i]; } const double &operator[](size_t i) const { return dims[i]; } MyVector operator+(const MyVector &rhs) const { std::vector<double> temp(dims); for (size_t i = 0; i < rhs.dims.size(); ++i) { temp[i] += rhs[i]; } return MyVector(temp); } MyVector operator*(const MyVector &rhs) const { std::vector<double> temp(dims.size(), 0.0); for (size_t i = 0; i < dims.size(); i++) { if (dims[i] != 0.0) { for (size_t j = 0; j < dims.size(); j++) { if (rhs[j] != 0.0) { auto s = reorderingSign(i, j) * dims[i] * rhs[j]; auto k = i ^ j; temp[k] += s; } } } } return MyVector(temp); } MyVector operator*(double scale) const { std::vector<double> temp(dims); std::for_each(temp.begin(), temp.end(), [scale](double a) { return a * scale; }); return MyVector(temp); } MyVector operator-() const { return *this * -1.0; } MyVector dot(const MyVector &rhs) const { return (*this * rhs + rhs * *this) * 0.5; } friend std::ostream &operator<<(std::ostream &, const MyVector &); private: std::vector<double> dims; }; std::ostream &operator<<(std::ostream &os, const MyVector &v) { auto it = v.dims.cbegin(); auto end = v.dims.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << ']'; } MyVector e(int n) { if (n > 4) { throw new std::runtime_error("n must be less than 5"); } auto result = MyVector(std::vector<double>(32, 0.0)); result[1 << n] = 1.0; return result; } MyVector randomVector() { auto result = MyVector(std::vector<double>(32, 0.0)); for (int i = 0; i < 5; i++) { result = result + MyVector(std::vector<double>(1, uniform01())) * e(i); } return result; } MyVector randomMultiVector() { auto result = MyVector(std::vector<double>(32, 0.0)); for (int i = 0; i < 32; i++) { result[i] = uniform01(); } return result; } int main() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i < j) { if (e(i).dot(e(j))[0] != 0.0) { std::cout << "Unexpected non-null scalar product."; return 1; } else if (i == j) { if (e(i).dot(e(j))[0] == 0.0) { std::cout << "Unexpected null scalar product."; } } } } } auto a = randomMultiVector(); auto b = randomMultiVector(); auto c = randomMultiVector(); auto x = randomVector(); std::cout << ((a * b) * c) << '\n'; std::cout << (a * (b * c)) << "\n\n"; std::cout << (a * (b + c)) << '\n'; std::cout << (a * b + a * c) << "\n\n"; std::cout << ((a + b) * c) << '\n'; std::cout << (a * c + b * c) << "\n\n"; std::cout << (x * x) << '\n'; return 0; }
Keep all operations the same but rewrite the snippet in C++.
using System; using System.Collections.Generic; namespace SuffixTree { class Node { public string sub; public List<int> ch = new List<int>(); public Node() { sub = ""; } public Node(string sub, params int[] children) { this.sub = sub; ch.AddRange(children); } } class SuffixTree { readonly List<Node> nodes = new List<Node>(); public SuffixTree(string str) { nodes.Add(new Node()); for (int i = 0; i < str.Length; i++) { AddSuffix(str.Substring(i)); } } public void Visualize() { if (nodes.Count == 0) { Console.WriteLine("<empty>"); return; } void f(int n, string pre) { var children = nodes[n].ch; if (children.Count == 0) { Console.WriteLine("- {0}", nodes[n].sub); return; } Console.WriteLine("+ {0}", nodes[n].sub); var it = children.GetEnumerator(); if (it.MoveNext()) { do { var cit = it; if (!cit.MoveNext()) break; Console.Write("{0}+-", pre); f(it.Current, pre + "| "); } while (it.MoveNext()); } Console.Write("{0}+-", pre); f(children[children.Count-1], pre+" "); } f(0, ""); } private void AddSuffix(string suf) { int n = 0; int i = 0; while (i < suf.Length) { char b = suf[i]; int x2 = 0; int n2; while (true) { var children = nodes[n].ch; if (x2 == children.Count) { n2 = nodes.Count; nodes.Add(new Node(suf.Substring(i))); nodes[n].ch.Add(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } var sub2 = nodes[n2].sub; int j = 0; while (j < sub2.Length) { if (suf[i + j] != sub2[j]) { var n3 = n2; n2 = nodes.Count; nodes.Add(new Node(sub2.Substring(0, j), n3)); nodes[n3].sub = sub2.Substring(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } } class Program { static void Main() { new SuffixTree("banana$").Visualize(); } } }
#include <functional> #include <iostream> #include <vector> struct Node { std::string sub = ""; std::vector<int> ch; Node() { } Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) { ch.insert(ch.end(), children); } }; struct SuffixTree { std::vector<Node> nodes; SuffixTree(const std::string& str) { nodes.push_back(Node{}); for (size_t i = 0; i < str.length(); i++) { addSuffix(str.substr(i)); } } void visualize() { if (nodes.size() == 0) { std::cout << "<empty>\n"; return; } std::function<void(int, const std::string&)> f; f = [&](int n, const std::string & pre) { auto children = nodes[n].ch; if (children.size() == 0) { std::cout << "- " << nodes[n].sub << '\n'; return; } std::cout << "+ " << nodes[n].sub << '\n'; auto it = std::begin(children); if (it != std::end(children)) do { if (std::next(it) == std::end(children)) break; std::cout << pre << "+-"; f(*it, pre + "| "); it = std::next(it); } while (true); std::cout << pre << "+-"; f(children[children.size() - 1], pre + " "); }; f(0, ""); } private: void addSuffix(const std::string & suf) { int n = 0; size_t i = 0; while (i < suf.length()) { char b = suf[i]; int x2 = 0; int n2; while (true) { auto children = nodes[n].ch; if (x2 == children.size()) { n2 = nodes.size(); nodes.push_back(Node(suf.substr(i), {})); nodes[n].ch.push_back(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } auto sub2 = nodes[n2].sub; size_t j = 0; while (j < sub2.size()) { if (suf[i + j] != sub2[j]) { auto n3 = n2; n2 = nodes.size(); nodes.push_back(Node(sub2.substr(0, j), { n3 })); nodes[n3].sub = sub2.substr(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } }; int main() { SuffixTree("banana$").visualize(); }
Convert the following code from C# to C++, ensuring the logic remains intact.
using System; using System.Collections.Generic; namespace SuffixTree { class Node { public string sub; public List<int> ch = new List<int>(); public Node() { sub = ""; } public Node(string sub, params int[] children) { this.sub = sub; ch.AddRange(children); } } class SuffixTree { readonly List<Node> nodes = new List<Node>(); public SuffixTree(string str) { nodes.Add(new Node()); for (int i = 0; i < str.Length; i++) { AddSuffix(str.Substring(i)); } } public void Visualize() { if (nodes.Count == 0) { Console.WriteLine("<empty>"); return; } void f(int n, string pre) { var children = nodes[n].ch; if (children.Count == 0) { Console.WriteLine("- {0}", nodes[n].sub); return; } Console.WriteLine("+ {0}", nodes[n].sub); var it = children.GetEnumerator(); if (it.MoveNext()) { do { var cit = it; if (!cit.MoveNext()) break; Console.Write("{0}+-", pre); f(it.Current, pre + "| "); } while (it.MoveNext()); } Console.Write("{0}+-", pre); f(children[children.Count-1], pre+" "); } f(0, ""); } private void AddSuffix(string suf) { int n = 0; int i = 0; while (i < suf.Length) { char b = suf[i]; int x2 = 0; int n2; while (true) { var children = nodes[n].ch; if (x2 == children.Count) { n2 = nodes.Count; nodes.Add(new Node(suf.Substring(i))); nodes[n].ch.Add(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } var sub2 = nodes[n2].sub; int j = 0; while (j < sub2.Length) { if (suf[i + j] != sub2[j]) { var n3 = n2; n2 = nodes.Count; nodes.Add(new Node(sub2.Substring(0, j), n3)); nodes[n3].sub = sub2.Substring(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } } class Program { static void Main() { new SuffixTree("banana$").Visualize(); } } }
#include <functional> #include <iostream> #include <vector> struct Node { std::string sub = ""; std::vector<int> ch; Node() { } Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) { ch.insert(ch.end(), children); } }; struct SuffixTree { std::vector<Node> nodes; SuffixTree(const std::string& str) { nodes.push_back(Node{}); for (size_t i = 0; i < str.length(); i++) { addSuffix(str.substr(i)); } } void visualize() { if (nodes.size() == 0) { std::cout << "<empty>\n"; return; } std::function<void(int, const std::string&)> f; f = [&](int n, const std::string & pre) { auto children = nodes[n].ch; if (children.size() == 0) { std::cout << "- " << nodes[n].sub << '\n'; return; } std::cout << "+ " << nodes[n].sub << '\n'; auto it = std::begin(children); if (it != std::end(children)) do { if (std::next(it) == std::end(children)) break; std::cout << pre << "+-"; f(*it, pre + "| "); it = std::next(it); } while (true); std::cout << pre << "+-"; f(children[children.size() - 1], pre + " "); }; f(0, ""); } private: void addSuffix(const std::string & suf) { int n = 0; size_t i = 0; while (i < suf.length()) { char b = suf[i]; int x2 = 0; int n2; while (true) { auto children = nodes[n].ch; if (x2 == children.size()) { n2 = nodes.size(); nodes.push_back(Node(suf.substr(i), {})); nodes[n].ch.push_back(n2); return; } n2 = children[x2]; if (nodes[n2].sub[0] == b) { break; } x2++; } auto sub2 = nodes[n2].sub; size_t j = 0; while (j < sub2.size()) { if (suf[i + j] != sub2[j]) { auto n3 = n2; n2 = nodes.size(); nodes.push_back(Node(sub2.substr(0, j), { n3 })); nodes[n3].sub = sub2.substr(j); nodes[n].ch[x2] = n2; break; } j++; } i += j; n = n2; } } }; int main() { SuffixTree("banana$").visualize(); }
Generate a C++ translation of this C# snippet without changing its computational steps.
using System; using System.Collections.Generic; namespace AssocArrays { class Program { static void Main(string[] args) { Dictionary<string,int> assocArray = new Dictionary<string,int>(); assocArray["Hello"] = 1; assocArray.Add("World", 2); assocArray["!"] = 3; foreach (KeyValuePair<string, int> kvp in assocArray) { Console.WriteLine(kvp.Key + " : " + kvp.Value); } foreach (string key in assocArray.Keys) { Console.WriteLine(key); } foreach (int val in assocArray.Values) { Console.WriteLine(val.ToString()); } } } }
#include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> dict { {"One", 1}, {"Two", 2}, {"Three", 7} }; dict["Three"] = 3; std::cout << "One: " << dict["One"] << std::endl; std::cout << "Key/Value pairs: " << std::endl; for(auto& kv: dict) { std::cout << " " << kv.first << ": " << kv.second << std::endl; } return 0; }
Port the following code from C# to C++ with equivalent syntax and logic.
using System; using System.Globalization; struct LimitedInt : IComparable, IComparable<LimitedInt>, IConvertible, IEquatable<LimitedInt>, IFormattable { const int MIN_VALUE = 1; const int MAX_VALUE = 10; public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE); public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE); static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE; readonly int _value; public int Value => this._value == 0 ? MIN_VALUE : this._value; public LimitedInt(int value) { if (!IsValidValue(value)) throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}."); this._value = value; } #region IComparable public int CompareTo(object obj) { if (obj is LimitedInt l) return this.Value.CompareTo(l); throw new ArgumentException("Object must be of type " + nameof(LimitedInt), nameof(obj)); } #endregion #region IComparable<LimitedInt> public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value); #endregion #region IConvertible public TypeCode GetTypeCode() => this.Value.GetTypeCode(); bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider); byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider); char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider); DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider); decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider); double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider); short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider); int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider); long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider); sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider); float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider); string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider); object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider); ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider); uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider); ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider); #endregion #region IEquatable<LimitedInt> public bool Equals(LimitedInt other) => this == other; #endregion #region IFormattable public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider); #endregion #region operators public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value; public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value; public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value; public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value; public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value; public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value; public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1); public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1); public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value); public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value); public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value); public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value); public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value); public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value); public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value); public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value); public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value; public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right); public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right); public static implicit operator int(LimitedInt value) => value.Value; public static explicit operator LimitedInt(int value) { if (!IsValidValue(value)) throw new OverflowException(); return new LimitedInt(value); } #endregion public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) => this.Value.TryFormat(destination, out charsWritten, format, provider); public override int GetHashCode() => this.Value.GetHashCode(); public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l); public override string ToString() => this.Value.ToString(); #region static methods public static bool TryParse(ReadOnlySpan<char> s, out int result) => int.TryParse(s, out result); public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider); public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider); public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result); public static int Parse(string s) => int.Parse(s); public static int Parse(string s, NumberStyles style) => int.Parse(s, style); public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider); public static bool TryParse(string s, ref int result) => int.TryParse(s, out result); #endregion }
#include <stdexcept> class tiny_int { public: tiny_int(int i): value(i) { if (value < 1) throw std::out_of_range("tiny_int: value smaller than 1"); if (value > 10) throw std::out_of_range("tiny_int: value larger than 10"); } operator int() const { return value; } tiny_int& operator+=(int i) { *this = value + i; return *this; } tiny_int& operator-=(int i) { *this = value - i; return *this; } tiny_int& operator*=(int i) { *this = value * i; return *this; } tiny_int& operator/=(int i) { *this = value / i; return *this; } tiny_int& operator<<=(int i) { *this = value << i; return *this; } tiny_int& operator>>=(int i) { *this = value >> i; return *this; } tiny_int& operator&=(int i) { *this = value & i; return *this; } tiny_int& operator|=(int i) { *this = value | i; return *this; } private: unsigned char value; };
Convert this C# snippet to C++ and keep its semantics consistent.
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
Rewrite this program in C# while keeping its functionality equivalent to the C++ version.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Generate an equivalent C# version of this C++ code.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -1; dy[0] = -2; dx[1] = -1; dy[1] = 2; dx[2] = 1; dy[2] = -2; dx[3] = 1; dy[3] = 2; dx[4] = -2; dy[4] = -1; dx[5] = -2; dy[5] = 1; dx[6] = 2; dy[6] = -1; dx[7] = 2; dy[7] = 1; } void solve( vector<string>& puzz, int max_wid ) { if( puzz.size() < 1 ) return; wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid; int len = wid * hei, c = 0; max = len; arr = new node[len]; memset( arr, 0, len * sizeof( node ) ); for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "*" ) { max--; arr[c++].val = -1; continue; } arr[c].val = atoi( ( *i ).c_str() ); c++; } solveIt(); c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) == "." ) { ostringstream o; o << arr[c].val; ( *i ) = o.str(); } c++; } delete [] arr; } private: bool search( int x, int y, int w ) { if( w > max ) return true; node* n = &arr[x + y * wid]; n->neighbors = getNeighbors( x, y ); for( int d = 0; d < 8; d++ ) { if( n->neighbors & ( 1 << d ) ) { int a = x + dx[d], b = y + dy[d]; if( arr[a + b * wid].val == 0 ) { arr[a + b * wid].val = w; if( search( a, b, w + 1 ) ) return true; arr[a + b * wid].val = 0; } } } return false; } unsigned char getNeighbors( int x, int y ) { unsigned char c = 0; int a, b; for( int xx = 0; xx < 8; xx++ ) { a = x + dx[xx], b = y + dy[xx]; if( a < 0 || b < 0 || a >= wid || b >= hei ) continue; if( arr[a + b * wid].val > -1 ) c |= ( 1 << xx ); } return c; } void solveIt() { int x, y, z; findStart( x, y, z ); if( z == 99999 ) { cout << "\nCan't find start point!\n"; return; } search( x, y, z + 1 ); } void findStart( int& x, int& y, int& z ) { z = 99999; for( int b = 0; b < hei; b++ ) for( int a = 0; a < wid; a++ ) if( arr[a + wid * b].val > 0 && arr[a + wid * b].val < z ) { x = a; y = b; z = arr[a + wid * b].val; } } int wid, hei, max, dx[8], dy[8]; node* arr; }; int main( int argc, char* argv[] ) { int wid; string p; p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; wid = 13; istringstream iss( p ); vector<string> puzz; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) ); nSolver s; s.solve( puzz, wid ); int c = 0; for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ ) { if( ( *i ) != "*" && ( *i ) != "." ) { if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; cout << ( *i ) << " "; } else cout << " "; if( ++c >= wid ) { cout << endl; c = 0; } } cout << endl << endl; return system( "pause" ); }
using System.Collections; using System.Collections.Generic; using static System.Console; using static System.Math; using static System.Linq.Enumerable; public class Solver { private static readonly (int dx, int dy)[] knightMoves = {(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1),(-2,-1),(-1,-2)}; private (int dx, int dy)[] moves; public static void Main() { var knightSolver = new Solver(knightMoves); Print(knightSolver.Solve(true, ".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000..")); Print(knightSolver.Solve(true, ".....0.0.....", ".....0.0.....", "....00000....", ".....000.....", "..0..0.0..0..", "00000...00000", "..00.....00..", "00000...00000", "..0..0.0..0..", ".....000.....", "....00000....", ".....0.0.....", ".....0.0....." )); } public Solver(params (int dx, int dy)[] moves) => this.moves = moves; public int[,] Solve(bool circular, params string[] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } public int[,] Solve(bool circular, int[,] puzzle) { var (board, given, count) = Parse(puzzle); return Solve(board, given, count, circular); } private int[,] Solve(int[,] board, BitArray given, int count, bool circular) { var (height, width) = (board.GetLength(0), board.GetLength(1)); bool solved = false; for (int x = 0; x < height && !solved; x++) { solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1)); if (solved) return board; } return null; } private bool Solve(int[,] board, BitArray given, bool circular, (int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n) { var (x, y) = current; if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false; if (board[x, y] < 0) return false; if (given[n - 1]) { if (board[x, y] != n) return false; } else if (board[x, y] > 0) return false; board[x, y] = n; if (n == last) { if (!circular || AreNeighbors(start, current)) return true; } for (int i = 0; i < moves.Length; i++) { var move = moves[i]; if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true; } if (!given[n - 1]) board[x, y] = 0; return false; bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1)); } private static (int[,] board, BitArray given, int count) Parse(string[] input) { (int height, int width) = (input.Length, input[0].Length); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) { string line = input[x]; for (int y = 0; y < width; y++) { board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1; if (board[x, y] >= 0) count++; } } BitArray given = Scan(board, count, height, width); return (board, given, count); } private static (int[,] board, BitArray given, int count) Parse(int[,] input) { (int height, int width) = (input.GetLength(0), input.GetLength(1)); int[,] board = new int[height, width]; int count = 0; for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if ((board[x, y] = input[x, y]) >= 0) count++; BitArray given = Scan(board, count, height, width); return (board, given, count); } private static BitArray Scan(int[,] board, int count, int height, int width) { var given = new BitArray(count + 1); for (int x = 0; x < height; x++) for (int y = 0; y < width; y++) if (board[x, y] > 0) given[board[x, y] - 1] = true; return given; } private static void Print(int[,] board) { if (board == null) { WriteLine("No solution"); } else { int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1; string e = new string('-', w); foreach (int x in Range(0, board.GetLength(0))) WriteLine(string.Join(" ", Range(0, board.GetLength(1)) .Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' ')))); } WriteLine(); } }
Keep all operations the same but rewrite the snippet in C#.
#include <iostream> #include <string> #include <vector> #include <unordered_map> using tab_t = std::vector<std::vector<std::string>>; tab_t tab1 { {"27", "Jonah"} , {"18", "Alan"} , {"28", "Glory"} , {"18", "Popeye"} , {"28", "Alan"} }; tab_t tab2 { {"Jonah", "Whales"} , {"Jonah", "Spiders"} , {"Alan", "Ghosts"} , {"Alan", "Zombies"} , {"Glory", "Buffy"} }; std::ostream& operator<<(std::ostream& o, const tab_t& t) { for(size_t i = 0; i < t.size(); ++i) { o << i << ":"; for(const auto& e : t[i]) o << '\t' << e; o << std::endl; } return o; } tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) { std::unordered_multimap<std::string, size_t> hashmap; for(size_t i = 0; i < a.size(); ++i) { hashmap.insert(std::make_pair(a[i][columna], i)); } tab_t result; for(size_t i = 0; i < b.size(); ++i) { auto range = hashmap.equal_range(b[i][columnb]); for(auto it = range.first; it != range.second; ++it) { tab_t::value_type row; row.insert(row.end() , a[it->second].begin() , a[it->second].end()); row.insert(row.end() , b[i].begin() , b[i].end()); result.push_back(std::move(row)); } } return result; } int main(int argc, char const *argv[]) { using namespace std; int ret = 0; cout << "Table A: " << endl << tab1 << endl; cout << "Table B: " << endl << tab2 << endl; auto tab3 = Join(tab1, 1, tab2, 0); cout << "Joined tables: " << endl << tab3 << endl; return ret; }
using System; using System.Collections.Generic; using System.Linq; namespace HashJoin { public class AgeName { public AgeName(byte age, string name) { Age = age; Name = name; } public byte Age { get; private set; } public string Name { get; private set; } } public class NameNemesis { public NameNemesis(string name, string nemesis) { Name = name; Nemesis = nemesis; } public string Name { get; private set; } public string Nemesis { get; private set; } } public class DataContext { public DataContext() { AgeName = new List<AgeName>(); NameNemesis = new List<NameNemesis>(); } public List<AgeName> AgeName { get; set; } public List<NameNemesis> NameNemesis { get; set; } } public class AgeNameNemesis { public AgeNameNemesis(byte age, string name, string nemesis) { Age = age; Name = name; Nemesis = nemesis; } public byte Age { get; private set; } public string Name { get; private set; } public string Nemesis { get; private set; } } class Program { public static void Main() { var data = GetData(); var result = ExecuteHashJoin(data); WriteResultToConsole(result); } private static void WriteResultToConsole(List<AgeNameNemesis> result) { result.ForEach(ageNameNemesis => Console.WriteLine("Age: {0}, Name: {1}, Nemesis: {2}", ageNameNemesis.Age, ageNameNemesis.Name, ageNameNemesis.Nemesis)); } private static List<AgeNameNemesis> ExecuteHashJoin(DataContext data) { return (data.AgeName.Join(data.NameNemesis, ageName => ageName.Name, nameNemesis => nameNemesis.Name, (ageName, nameNemesis) => new AgeNameNemesis(ageName.Age, ageName.Name, nameNemesis.Nemesis))) .ToList(); } private static DataContext GetData() { var context = new DataContext(); context.AgeName.AddRange(new [] { new AgeName(27, "Jonah"), new AgeName(18, "Alan"), new AgeName(28, "Glory"), new AgeName(18, "Popeye"), new AgeName(28, "Alan") }); context.NameNemesis.AddRange(new[] { new NameNemesis("Jonah", "Whales"), new NameNemesis("Jonah", "Spiders"), new NameNemesis("Alan", "Ghosts"), new NameNemesis("Alan", "Zombies"), new NameNemesis("Glory", "Buffy") }); return context; } } }
Produce a functionally identical C++ code for the snippet given in C#.
using System; using static System.Console; using System.Collections; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>(); var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First(); lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++) res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt)) Write("{0,4} {1}", item, ++c % 20 == 0 ? "\n" : ""); Write("\n\nCounted {0} odd squarefree semiprimes under {1}", c, lmt); } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
#include <iomanip> #include <iostream> bool odd_square_free_semiprime(int n) { if ((n & 1) == 0) return false; int count = 0; for (int i = 3; i * i <= n; i += 2) { for (; n % i == 0; n /= i) { if (++count > 1) return false; } } return count == 1; } int main() { const int n = 1000; std::cout << "Odd square-free semiprimes < " << n << ":\n"; int count = 0; for (int i = 1; i < n; i += 2) { if (odd_square_free_semiprime(i)) { ++count; std::cout << std::setw(4) << i; if (count % 20 == 0) std::cout << '\n'; } } std::cout << "\nCount: " << count << '\n'; return 0; }
Produce a functionally identical C++ code for the snippet given in C#.
using System; using static System.Console; using System.Collections; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { int lmt = 1000, amt, c = 0, sr = (int)Math.Sqrt(lmt), lm2; var res = new List<int>(); var pr = PG.Primes(lmt / 3 + 5).ToArray(); lm2 = pr.OrderBy(i => Math.Abs(sr - i)).First(); lm2 = Array.IndexOf(pr, lm2); for (var p = 0; p < lm2; p++) { amt = 0; for (var q = p + 1; amt < lmt; q++) res.Add(amt = pr[p] * pr[q]); } res.Sort(); foreach(var item in res.TakeWhile(x => x < lmt)) Write("{0,4} {1}", item, ++c % 20 == 0 ? "\n" : ""); Write("\n\nCounted {0} odd squarefree semiprimes under {1}", c, lmt); } } class PG { public static IEnumerable<int> Primes(int lim) { var flags = new bool[lim + 1]; int j = 3; for (int d = 8, sq = 9; sq <= lim; j += 2, sq += d += 8) if (!flags[j]) { yield return j; for (int k = sq, i = j << 1; k <= lim; k += i) flags[k] = true; } for (; j <= lim; j += 2) if (!flags[j]) yield return j; } }
#include <iomanip> #include <iostream> bool odd_square_free_semiprime(int n) { if ((n & 1) == 0) return false; int count = 0; for (int i = 3; i * i <= n; i += 2) { for (; n % i == 0; n /= i) { if (++count > 1) return false; } } return count == 1; } int main() { const int n = 1000; std::cout << "Odd square-free semiprimes < " << n << ":\n"; int count = 0; for (int i = 1; i < n; i += 2) { if (odd_square_free_semiprime(i)) { ++count; std::cout << std::setw(4) << i; if (count % 20 == 0) std::cout << '\n'; } } std::cout << "\nCount: " << count << '\n'; return 0; }
Generate an equivalent C++ version of this C# code.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int degree = polynomial.size() - 1; int d = degree; for (int i : polynomial) { if (d < degree) { if (i >= 0) { formatted += " + "; } else { formatted += " - "; } } formatted += std::to_string(abs(i)); if (d > 1) { formatted += "x^" + std::to_string(d); } else if (d == 1) { formatted += "x"; } d--; } return formatted; } std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor) { std::vector<int> quotient; quotient = dividend; int normalizer = divisor[0]; for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++) { quotient[i] /= normalizer; int coef = quotient[i]; if (coef != 0) { for (int j = 1; j < divisor.size(); j++) { quotient[i + j] += -divisor[j] * coef; } } } return quotient; } int main(int argc, char **argv) { std::vector<int> dividend{ 1, -12, 0, -42}; std::vector<int> divisor{ 1, -3}; std::cout << frmtPolynomial(dividend) << "\n"; std::cout << frmtPolynomial(divisor) << "\n"; std::vector<int> quotient = syntheticDiv(dividend, divisor); std::cout << frmtPolynomial(quotient, true) << "\n"; }
Keep all operations the same but rewrite the snippet in C++.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int degree = polynomial.size() - 1; int d = degree; for (int i : polynomial) { if (d < degree) { if (i >= 0) { formatted += " + "; } else { formatted += " - "; } } formatted += std::to_string(abs(i)); if (d > 1) { formatted += "x^" + std::to_string(d); } else if (d == 1) { formatted += "x"; } d--; } return formatted; } std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor) { std::vector<int> quotient; quotient = dividend; int normalizer = divisor[0]; for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++) { quotient[i] /= normalizer; int coef = quotient[i]; if (coef != 0) { for (int j = 1; j < divisor.size(); j++) { quotient[i + j] += -divisor[j] * coef; } } } return quotient; } int main(int argc, char **argv) { std::vector<int> dividend{ 1, -12, 0, -42}; std::vector<int> divisor{ 1, -3}; std::cout << frmtPolynomial(dividend) << "\n"; std::cout << frmtPolynomial(divisor) << "\n"; std::vector<int> quotient = syntheticDiv(dividend, divisor); std::cout << frmtPolynomial(quotient, true) << "\n"; }
Produce a language-to-language conversion: from C# to C++, same semantics.
using System; using System.Collections.Generic; using System.Linq; namespace SyntheticDivision { class Program { static (List<int>,List<int>) extendedSyntheticDivision(List<int> dividend, List<int> divisor) { List<int> output = dividend.ToList(); int normalizer = divisor[0]; for (int i = 0; i < dividend.Count() - (divisor.Count() - 1); i++) { output[i] /= normalizer; int coef = output[i]; if (coef != 0) { for (int j = 1; j < divisor.Count(); j++) output[i + j] += -divisor[j] * coef; } } int separator = output.Count() - (divisor.Count() - 1); return ( output.GetRange(0, separator), output.GetRange(separator, output.Count() - separator) ); } static void Main(string[] args) { List<int> N = new List<int>{ 1, -12, 0, -42 }; List<int> D = new List<int> { 1, -3 }; var (quotient, remainder) = extendedSyntheticDivision(N, D); Console.WriteLine("[ {0} ] / [ {1} ] = [ {2} ], remainder [ {3} ]" , string.Join(",", N), string.Join(",", D), string.Join(",", quotient), string.Join(",", remainder) ); } } }
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int degree = polynomial.size() - 1; int d = degree; for (int i : polynomial) { if (d < degree) { if (i >= 0) { formatted += " + "; } else { formatted += " - "; } } formatted += std::to_string(abs(i)); if (d > 1) { formatted += "x^" + std::to_string(d); } else if (d == 1) { formatted += "x"; } d--; } return formatted; } std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor) { std::vector<int> quotient; quotient = dividend; int normalizer = divisor[0]; for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++) { quotient[i] /= normalizer; int coef = quotient[i]; if (coef != 0) { for (int j = 1; j < divisor.size(); j++) { quotient[i + j] += -divisor[j] * coef; } } } return quotient; } int main(int argc, char **argv) { std::vector<int> dividend{ 1, -12, 0, -42}; std::vector<int> divisor{ 1, -3}; std::cout << frmtPolynomial(dividend) << "\n"; std::cout << frmtPolynomial(divisor) << "\n"; std::vector<int> quotient = syntheticDiv(dividend, divisor); std::cout << frmtPolynomial(quotient, true) << "\n"; }
Generate an equivalent C++ version of this C# code.
using System; using System.Dynamic; class Example : DynamicObject { public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { result = null; Console.WriteLine("This is {0}.", binder.Name); return true; } } class Program { static void Main(string[] args) { dynamic ex = new Example(); ex.Foo(); ex.Bar(); } }
class animal { public: virtual void bark() { throw "implement me: do not know how to bark"; } }; class elephant : public animal { }; int main() { elephant e; e.bark(); }
Write a version of this C++ function in C# with identical behavior.
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <vector> typedef std::vector<std::vector<int>> matrix; matrix dList(int n, int start) { start--; std::vector<int> a(n); std::iota(a.begin(), a.end(), 0); a[start] = a[0]; a[0] = start; std::sort(a.begin() + 1, a.end()); auto first = a[1]; matrix r; std::function<void(int)> recurse; recurse = [&](int last) { if (last == first) { for (size_t j = 1; j < a.size(); j++) { auto v = a[j]; if (j == v) { return; } } std::vector<int> b; std::transform(a.cbegin(), a.cend(), std::back_inserter(b), [](int v) { return v + 1; }); r.push_back(b); return; } for (int i = last; i >= 1; i--) { std::swap(a[i], a[last]); recurse(last - 1); std::swap(a[i], a[last]); } }; recurse(n - 1); return r; } void printSquare(const matrix &latin, int n) { for (auto &row : latin) { auto it = row.cbegin(); auto end = row.cend(); std::cout << '['; if (it != end) { std::cout << *it; it = std::next(it); } while (it != end) { std::cout << ", " << *it; it = std::next(it); } std::cout << "]\n"; } std::cout << '\n'; } unsigned long reducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { std::cout << "[]\n"; } return 0; } else if (n == 1) { if (echo) { std::cout << "[1]\n"; } return 1; } matrix rlatin; for (int i = 0; i < n; i++) { rlatin.push_back({}); for (int j = 0; j < n; j++) { rlatin[i].push_back(j); } } for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } unsigned long count = 0; std::function<void(int)> recurse; recurse = [&](int i) { auto rows = dList(n, i); for (size_t r = 0; r < rows.size(); r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.size() - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { printSquare(rlatin, n); } } outer: {} } }; recurse(2); return count; } unsigned long factorial(unsigned long n) { if (n <= 0) return 1; unsigned long prod = 1; for (unsigned long i = 2; i <= n; i++) { prod *= i; } return prod; } int main() { std::cout << "The four reduced lating squares of order 4 are:\n"; reducedLatinSquares(4, true); std::cout << "The size of the set of reduced latin squares for the following orders\n"; std::cout << "and hence the total number of latin squares of these orders are:\n\n"; for (int n = 1; n < 7; n++) { auto size = reducedLatinSquares(n, false); auto f = factorial(n - 1); f *= f * n * size; std::cout << "Order " << n << ": Size " << size << " x " << n << "! x " << (n - 1) << "! => Total " << f << '\n'; } return 0; }
using System; using System.Collections.Generic; using System.Linq; namespace LatinSquares { using matrix = List<List<int>>; class Program { static void Swap<T>(ref T a, ref T b) { var t = a; a = b; b = t; } static matrix DList(int n, int start) { start--; var a = Enumerable.Range(0, n).ToArray(); a[start] = a[0]; a[0] = start; Array.Sort(a, 1, a.Length - 1); var first = a[1]; matrix r = new matrix(); void recurse(int last) { if (last == first) { for (int j = 1; j < a.Length; j++) { var v = a[j]; if (j == v) { return; } } var b = a.Select(v => v + 1).ToArray(); r.Add(b.ToList()); return; } for (int i = last; i >= 1; i--) { Swap(ref a[i], ref a[last]); recurse(last - 1); Swap(ref a[i], ref a[last]); } } recurse(n - 1); return r; } static ulong ReducedLatinSquares(int n, bool echo) { if (n <= 0) { if (echo) { Console.WriteLine("[]\n"); } return 0; } else if (n == 1) { if (echo) { Console.WriteLine("[1]\n"); } return 1; } matrix rlatin = new matrix(); for (int i = 0; i < n; i++) { rlatin.Add(new List<int>()); for (int j = 0; j < n; j++) { rlatin[i].Add(0); } } for (int j = 0; j < n; j++) { rlatin[0][j] = j + 1; } ulong count = 0; void recurse(int i) { var rows = DList(n, i); for (int r = 0; r < rows.Count; r++) { rlatin[i - 1] = rows[r]; for (int k = 0; k < i - 1; k++) { for (int j = 1; j < n; j++) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.Count - 1) { goto outer; } if (i > 2) { return; } } } } if (i < n) { recurse(i + 1); } else { count++; if (echo) { PrintSquare(rlatin, n); } } outer: { } } } recurse(2); return count; } static void PrintSquare(matrix latin, int n) { foreach (var row in latin) { var it = row.GetEnumerator(); Console.Write("["); if (it.MoveNext()) { Console.Write(it.Current); } while (it.MoveNext()) { Console.Write(", {0}", it.Current); } Console.WriteLine("]"); } Console.WriteLine(); } static ulong Factorial(ulong n) { if (n <= 0) { return 1; } ulong prod = 1; for (ulong i = 2; i < n + 1; i++) { prod *= i; } return prod; } static void Main() { Console.WriteLine("The four reduced latin squares of order 4 are:\n"); ReducedLatinSquares(4, true); Console.WriteLine("The size of the set of reduced latin squares for the following orders"); Console.WriteLine("and hence the total number of latin squares of these orders are:\n"); for (int n = 1; n < 7; n++) { ulong nu = (ulong)n; var size = ReducedLatinSquares(n, false); var f = Factorial(nu - 1); f *= f * nu * size; Console.WriteLine("Order {0}: Size {1} x {2}! x {3}! => Total {4}", n, size, n, n - 1, f); } } } }
Translate the given C# code snippet into C++ without altering its behavior.
class Segment { public Segment(PointF p1, PointF p2) { P1 = p1; P2 = p2; } public readonly PointF P1; public readonly PointF P2; public float Length() { return (float)Math.Sqrt(LengthSquared()); } public float LengthSquared() { return (P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y); } }
#include <iostream> #include <vector> #include <utility> #include <cmath> #include <random> #include <chrono> #include <algorithm> #include <iterator> typedef std::pair<double, double> point_t; typedef std::pair<point_t, point_t> points_t; double distance_between(const point_t& a, const point_t& b) { return std::sqrt(std::pow(b.first - a.first, 2) + std::pow(b.second - a.second, 2)); } std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) { if (points.size() < 2) { return { -1, { { 0, 0 }, { 0, 0 } } }; } auto minDistance = std::abs(distance_between(points.at(0), points.at(1))); points_t minPoints = { points.at(0), points.at(1) }; for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) { for (auto j = i + 1; j < std::end(points); ++j) { auto newDistance = std::abs(distance_between(*i, *j)); if (newDistance < minDistance) { minDistance = newDistance; minPoints.first = *i; minPoints.second = *j; } } } return { minDistance, minPoints }; } std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP, const std::vector<point_t>& yP) { if (xP.size() <= 3) { return find_closest_brute(xP); } auto N = xP.size(); auto xL = std::vector<point_t>(); auto xR = std::vector<point_t>(); std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL)); std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR)); auto xM = xP.at((N-1) / 2).first; auto yL = std::vector<point_t>(); auto yR = std::vector<point_t>(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) { return p.first <= xM; }); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) { return p.first > xM; }); auto p1 = find_closest_optimized(xL, yL); auto p2 = find_closest_optimized(xR, yR); auto minPair = (p1.first <= p2.first) ? p1 : p2; auto yS = std::vector<point_t>(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) { return std::abs(xM - p.first) < minPair.first; }); auto result = minPair; for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) { for (auto k = i + 1; k != std::end(yS) && ((k->second - i->second) < minPair.first); ++k) { auto newDistance = std::abs(distance_between(*k, *i)); if (newDistance < result.first) { result = { newDistance, { *k, *i } }; } } } return result; } void print_point(const point_t& point) { std::cout << "(" << point.first << ", " << point.second << ")"; } int main(int argc, char * argv[]) { std::default_random_engine re(std::chrono::system_clock::to_time_t( std::chrono::system_clock::now())); std::uniform_real_distribution<double> urd(-500.0, 500.0); std::vector<point_t> points(100); std::generate(std::begin(points), std::end(points), [&urd, &re]() { return point_t { 1000 + urd(re), 1000 + urd(re) }; }); auto answer = find_closest_brute(points); std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { return a.first < b.first; }); auto xP = points; std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { return a.second < b.second; }); auto yP = points; std::cout << "Min distance (brute): " << answer.first << " "; print_point(answer.second.first); std::cout << ", "; print_point(answer.second.second); answer = find_closest_optimized(xP, yP); std::cout << "\nMin distance (optimized): " << answer.first << " "; print_point(answer.second.first); std::cout << ", "; print_point(answer.second.second); return 0; }
Convert the following code from C# to C++, ensuring the logic remains intact.
class Animal { } class Dog : Animal { } class Lab : Dog { } class Collie : Dog { } class Cat : Animal { }
class Animal { }; class Dog: public Animal { }; class Lab: public Dog { }; class Collie: public Dog { }; class Cat: public Animal { };
Port the provided C# code into C++ while preserving the original functionality.
public MainWindow() { InitializeComponent(); RenderOptions.SetBitmapScalingMode(imgMain, BitmapScalingMode.HighQuality); imgMain.Source = new WriteableBitmap(480, 480, 96, 96, PixelFormats.Bgr32, null); DrawHue(100); } void DrawHue(int saturation) { var bmp = (WriteableBitmap)imgMain.Source; int centerX = (int)bmp.Width / 2; int centerY = (int)bmp.Height / 2; int radius = Math.Min(centerX, centerY); int radius2 = radius - 40; bmp.Lock(); unsafe{ var buf = bmp.BackBuffer; IntPtr pixLineStart; for(int y=0; y < bmp.Height; y++){ pixLineStart = buf + bmp.BackBufferStride * y; double dy = (y - centerY); for(int x=0; x < bmp.Width; x++){ double dx = (x - centerX); double dist = Math.Sqrt(dx * dx + dy * dy); if (radius2 <= dist && dist <= radius) { double theta = Math.Atan2(dy, dx); double hue = (theta + Math.PI) / (2.0 * Math.PI); *((int*)(pixLineStart + x * 4)) = HSB_to_RGB((int)(hue * 360), saturation, 100); } } } } bmp.AddDirtyRect(new Int32Rect(0, 0, 480, 480)); bmp.Unlock(); } static int HSB_to_RGB(int h, int s, int v) { var rgb = new int[3]; var baseColor = (h + 60) % 360 / 120; var shift = (h + 60) % 360 - (120 * baseColor + 60 ); var secondaryColor = (baseColor + (shift >= 0 ? 1 : -1) + 3) % 3; rgb[baseColor] = 255; rgb[secondaryColor] = (int) ((Math.Abs(shift) / 60.0f) * 255.0f); for (var i = 0; i < 3; i++) rgb[i] += (int) ((255 - rgb[i]) * ((100 - s) / 100.0f)); for (var i = 0; i < 3; i++) rgb[i] -= (int) (rgb[i] * (100-v) / 100.0f); return RGB2int(rgb[0], rgb[1], rgb[2]); } public static int RGB2int(int r, int g, int b) => r << 16 | g << 8 | b;
#include "colorwheelwidget.h" #include <QPainter> #include <QPaintEvent> #include <cmath> namespace { QColor hsvToRgb(int h, double s, double v) { double hp = h/60.0; double c = s * v; double x = c * (1 - std::abs(std::fmod(hp, 2) - 1)); double m = v - c; double r = 0, g = 0, b = 0; if (hp <= 1) { r = c; g = x; } else if (hp <= 2) { r = x; g = c; } else if (hp <= 3) { g = c; b = x; } else if (hp <= 4) { g = x; b = c; } else if (hp <= 5) { r = x; b = c; } else { r = c; b = x; } r += m; g += m; b += m; return QColor(r * 255, g * 255, b * 255); } } ColorWheelWidget::ColorWheelWidget(QWidget *parent) : QWidget(parent) { setWindowTitle(tr("Color Wheel")); resize(400, 400); } void ColorWheelWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); const QColor backgroundColor(0, 0, 0); const QColor white(255, 255, 255); painter.fillRect(event->rect(), backgroundColor); const int margin = 10; const double diameter = std::min(width(), height()) - 2*margin; QPointF center(width()/2.0, height()/2.0); QRectF rect(center.x() - diameter/2.0, center.y() - diameter/2.0, diameter, diameter); for (int angle = 0; angle < 360; ++angle) { QColor color(hsvToRgb(angle, 1.0, 1.0)); QRadialGradient gradient(center, diameter/2.0); gradient.setColorAt(0, white); gradient.setColorAt(1, color); QBrush brush(gradient); QPen pen(brush, 1.0); painter.setPen(pen); painter.setBrush(brush); painter.drawPie(rect, angle * 16, 16); } }
Produce a language-to-language conversion: from C# to C++, same semantics.
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { System.Console.WriteLine("Point"); } } public class Circle : Point { private int r; public Circle(Point p) : this(p,0) { } public Circle(Point p, int r) : base(p) { this.r = r; } public Circle() : this(0) { } public Circle(int x) : this(x,0) { } public Circle(int x, int y) : this(x,y,0) { } public Circle(int x, int y, int r) : base(x,y) { this.r = r; } public int R { get { return r; } set { r = value; } } public override void print() { System.Console.WriteLine("Circle"); } public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
#include <cstdio> #include <cstdlib> class Point { protected: int x, y; public: Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {} Point(const Point &p) : x(p.x), y(p.y) {} virtual ~Point() {} const Point& operator=(const Point &p) { if (this != &p) { x = p.x; y = p.y; } return *this; } int getX() { return x; } int getY() { return y; } void setX(int x0) { x = x0; } void setY(int y0) { y = y0; } virtual void print() { printf("Point\n"); } }; class Circle: public Point { private: int r; public: Circle(Point p, int r0 = 0) : Point(p), r(r0) {} Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {} virtual ~Circle() {} const Circle& operator=(const Circle &c) { if (this != &c) { x = c.x; y = c.y; r = c.r; } return *this; } int getR() { return r; } void setR(int r0) { r = r0; } virtual void print() { printf("Circle\n"); } }; int main() { Point *p = new Point(); Point *c = new Circle(); p->print(); c->print(); delete p; delete c; return EXIT_SUCCESS; }
Port the provided C# code into C++ while preserving the original functionality.
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { System.Console.WriteLine("Point"); } } public class Circle : Point { private int r; public Circle(Point p) : this(p,0) { } public Circle(Point p, int r) : base(p) { this.r = r; } public Circle() : this(0) { } public Circle(int x) : this(x,0) { } public Circle(int x, int y) : this(x,y,0) { } public Circle(int x, int y, int r) : base(x,y) { this.r = r; } public int R { get { return r; } set { r = value; } } public override void print() { System.Console.WriteLine("Circle"); } public static void main(String args[]) { Point p = new Point(); Point c = new Circle(); p.print(); c.print(); } }
#include <cstdio> #include <cstdlib> class Point { protected: int x, y; public: Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {} Point(const Point &p) : x(p.x), y(p.y) {} virtual ~Point() {} const Point& operator=(const Point &p) { if (this != &p) { x = p.x; y = p.y; } return *this; } int getX() { return x; } int getY() { return y; } void setX(int x0) { x = x0; } void setY(int y0) { y = y0; } virtual void print() { printf("Point\n"); } }; class Circle: public Point { private: int r; public: Circle(Point p, int r0 = 0) : Point(p), r(r0) {} Circle(int x0 = 0, int y0 = 0, int r0 = 0) : Point(x0, y0), r(r0) {} virtual ~Circle() {} const Circle& operator=(const Circle &c) { if (this != &c) { x = c.x; y = c.y; r = c.r; } return *this; } int getR() { return r; } void setR(int r0) { r = r0; } virtual void print() { printf("Circle\n"); } }; int main() { Point *p = new Point(); Point *c = new Circle(); p->print(); c->print(); delete p; delete c; return EXIT_SUCCESS; }
Generate an equivalent C# version of this C++ code.
#include <functional> #include <iostream> #include <ostream> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto it = v.cbegin(); auto end = v.cend(); os << "["; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << "]"; } std::vector<int> kosaraju(std::vector<std::vector<int>>& g) { auto size = g.size(); std::vector<bool> vis(size); std::vector<int> l(size); auto x = size; std::vector<std::vector<int>> t(size); std::function<void(int)> visit; visit = [&](int u) { if (!vis[u]) { vis[u] = true; for (auto v : g[u]) { visit(v); t[v].push_back(u); } l[--x] = u; } }; for (int i = 0; i < g.size(); ++i) { visit(i); } std::vector<int> c(size); std::function<void(int, int)> assign; assign = [&](int u, int root) { if (vis[u]) { vis[u] = false; c[u] = root; for (auto v : t[u]) { assign(v, root); } } }; for (auto u : l) { assign(u, u); } return c; } std::vector<std::vector<int>> g = { {1}, {2}, {0}, {1, 2, 4}, {3, 5}, {2, 6}, {5}, {4, 6, 7}, }; int main() { using namespace std; cout << kosaraju(g) << endl; return 0; }
using System; using System.Collections.Generic; class Node { public enum Colors { Black, White, Gray } public Colors color { get; set; } public int N { get; } public Node(int n) { N = n; color = Colors.White; } } class Graph { public HashSet<Node> V { get; } public Dictionary<Node, HashSet<Node>> Adj { get; } public void Kosaraju() { var L = new HashSet<Node>(); Action<Node> Visit = null; Visit = (u) => { if (u.color == Node.Colors.White) { u.color = Node.Colors.Gray; foreach (var v in Adj[u]) Visit(v); L.Add(u); } }; Action<Node, Node> Assign = null; Assign = (u, root) => { if (u.color != Node.Colors.Black) { if (u == root) Console.Write("SCC: "); Console.Write(u.N + " "); u.color = Node.Colors.Black; foreach (var v in Adj[u]) Assign(v, root); if (u == root) Console.WriteLine(); } }; foreach (var u in V) Visit(u); foreach (var u in L) Assign(u, u); } }
Translate this program into C# but keep the logic exactly as in C++.
#include <functional> #include <iostream> #include <ostream> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto it = v.cbegin(); auto end = v.cend(); os << "["; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", " << *it; it = std::next(it); } return os << "]"; } std::vector<int> kosaraju(std::vector<std::vector<int>>& g) { auto size = g.size(); std::vector<bool> vis(size); std::vector<int> l(size); auto x = size; std::vector<std::vector<int>> t(size); std::function<void(int)> visit; visit = [&](int u) { if (!vis[u]) { vis[u] = true; for (auto v : g[u]) { visit(v); t[v].push_back(u); } l[--x] = u; } }; for (int i = 0; i < g.size(); ++i) { visit(i); } std::vector<int> c(size); std::function<void(int, int)> assign; assign = [&](int u, int root) { if (vis[u]) { vis[u] = false; c[u] = root; for (auto v : t[u]) { assign(v, root); } } }; for (auto u : l) { assign(u, u); } return c; } std::vector<std::vector<int>> g = { {1}, {2}, {0}, {1, 2, 4}, {3, 5}, {2, 6}, {5}, {4, 6, 7}, }; int main() { using namespace std; cout << kosaraju(g) << endl; return 0; }
using System; using System.Collections.Generic; class Node { public enum Colors { Black, White, Gray } public Colors color { get; set; } public int N { get; } public Node(int n) { N = n; color = Colors.White; } } class Graph { public HashSet<Node> V { get; } public Dictionary<Node, HashSet<Node>> Adj { get; } public void Kosaraju() { var L = new HashSet<Node>(); Action<Node> Visit = null; Visit = (u) => { if (u.color == Node.Colors.White) { u.color = Node.Colors.Gray; foreach (var v in Adj[u]) Visit(v); L.Add(u); } }; Action<Node, Node> Assign = null; Assign = (u, root) => { if (u.color != Node.Colors.Black) { if (u == root) Console.Write("SCC: "); Console.Write(u.N + " "); u.color = Node.Colors.Black; foreach (var v in Adj[u]) Assign(v, root); if (u == root) Console.WriteLine(); } }; foreach (var u in V) Visit(u); foreach (var u in L) Assign(u, u); } }
Port the provided C# code into C++ while preserving the original functionality.
using System; using System.Collections.Generic; class Program { static List<int> PrimesUpTo(int limit, bool verbose = false) { var sw = System.Diagnostics.Stopwatch.StartNew(); var members = new SortedSet<int>{ 1 }; int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), nl, ac = 2, rc = 1; List<int> primes = new List<int>(), tl = new List<int>(); while (prime < rtlim) { nl = Math.Min(prime * stp, limit); if (stp < limit) { tl.Clear(); foreach (var w in members) for (n = w + stp; n <= nl; n += stp) tl.Add(n); members.UnionWith(tl); ac += tl.Count; } stp = nl; nxtpr = 5; tl.Clear(); foreach (var w in members) { if (nxtpr == 5 && w > prime) nxtpr = w; if ((n = prime * w) > nl) break; else tl.Add(n); } foreach (var itm in tl) members.Remove(itm); rc += tl.Count; primes.Add(prime); prime = prime == 2 ? 3 : nxtpr; } members.Remove(1); primes.AddRange(members); sw.Stop(); if (verbose) Console.WriteLine("Up to {0}, added:{1}, removed:{2}, primes counted:{3}, time:{4} ms", limit, ac, rc, primes.Count, sw.Elapsed.TotalMilliseconds); return primes; } static void Main(string[] args) { Console.WriteLine("[{0}]", string.Join(", ", PrimesUpTo(150, true))); PrimesUpTo(1000000, true); } }
#include <cstring> #include <string> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <ctime> void Extend (uint32_t w[], uint32_t &w_end, uint32_t &length, uint32_t n, bool d[], uint32_t &w_end_max) { uint32_t i, j, x; i = 0; j = w_end; x = length + 1; while (x <= n) { w[++j] = x; d[x] = false; x = length + w[++i]; } length = n; w_end = j; if (w_end > w_end_max) w_end_max = w_end; } void Delete (uint32_t w[], uint32_t length, uint32_t p, bool d[], uint32_t &imaxf) { uint32_t i, x; i = 0; x = p; while (x <= length) { d[x] = true; x = p*w[++i]; } imaxf = i-1; } void Compress(uint32_t w[], bool d[], uint32_t to, uint32_t &w_end) { uint32_t i, j; j = 0; for (i=1; i <= to; i++) { if (!d[w[i]]) { w[++j] = w[i]; } } if (to == w_end) { w_end = j; } else { for (uint32_t k=j+1; k <= to; k++) w[k] = 0; } } void Sift(uint32_t N, bool printPrimes, uint32_t &nrPrimes, uint32_t &vBound) { uint32_t *w = new uint32_t[N/4+5]; bool *d = new bool[N+1]; uint32_t w_end, length; uint32_t w_end_max, p, imaxf; w_end = 0; w[0] = 1; w_end_max = 0; length = 2; nrPrimes = 1; if (printPrimes) printf("%d", 2); p = 3; while (p*p <= N) { nrPrimes++; if (printPrimes) printf(" %d", p); if (length < N) { Extend (w, w_end, length, std::min(p*length,N), d, w_end_max); } Delete(w, length, p, d, imaxf); Compress(w, d, (length < N ? w_end : imaxf), w_end); p = w[1]; if (p == 0) break; } if (length < N) { Extend (w, w_end, length, N, d, w_end_max); } for (uint32_t i=1; i <= w_end; i++) { if (w[i] == 0 || d[w[i]]) continue; if (printPrimes) printf(" %d", w[i]); nrPrimes++; } vBound = w_end_max+1; } int main (int argc, char *argw[]) { bool error = false; bool printPrimes = false; uint32_t N, nrPrimes, vBound; if (argc == 3) { if (strcmp(argw[2], "-p") == 0) { printPrimes = true; argc--; } else { error = true; } } if (argc == 2) { N = atoi(argw[1]); if (N < 2 || N > 1000000000) error = true; } else { error = true; } if (error) { printf("call with: %s N -p where 2 <= N <= 1000000000 and -p to print the primes is optional \n", argw[0]); exit(1); } int start_s = clock(); Sift(N, printPrimes, nrPrimes, vBound); int stop_s=clock(); printf("\n%d primes up to %lu found in %.3f ms using array w[%d]\n", nrPrimes, (unsigned long)N, (stop_s-start_s)*1E3/double(CLOCKS_PER_SEC), vBound); }
Translate the given Python code snippet into C++ without altering its behavior.
import math from collections import Counter def entropy(s): p, lns = Counter(s), float(len(s)) return -sum( count/lns * math.log(count/lns, 2) for count in p.values()) with open(__file__) as f: b=f.read() print(entropy(b))
#include <iostream> #include <fstream> #include <cmath> using namespace std; string readFile (string path) { string contents; string line; ifstream inFile(path); while (getline (inFile, line)) { contents.append(line); contents.append("\n"); } inFile.close(); return contents; } double entropy (string X) { const int MAXCHAR = 127; int N = X.length(); int count[MAXCHAR]; double count_i; char ch; double sum = 0.0; for (int i = 0; i < MAXCHAR; i++) count[i] = 0; for (int pos = 0; pos < N; pos++) { ch = X[pos]; count[(int)ch]++; } for (int n_i = 0; n_i < MAXCHAR; n_i++) { count_i = count[n_i]; if (count_i > 0) sum -= count_i / N * log2(count_i / N); } return sum; } int main () { cout<<entropy(readFile("entropy.cpp")); return 0; }
Preserve the algorithm and functionality while converting the code from Python to C++.
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
#include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace Rcpp ; CharacterVector getNameInfo(std::string fqdn) { struct addrinfo hints, *res, *res0; int error; char host[NI_MAXHOST]; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); if (error) { return(NA_STRING); } int i = 0 ; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { i++ ; } } CharacterVector results(i) ; i = 0; for (res = res0; res; res = res->ai_next) { error = getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof host, NULL, 0, NI_NUMERICHOST); if (!error) { results[i++] = host ; } } freeaddrinfo(res0); return(results) ; }
Translate the given Python code snippet into C++ without altering its behavior.
import turtle as tt import inspect stack = [] def peano(iterations=1): global stack ivan = tt.Turtle(shape = "classic", visible = True) screen = tt.Screen() screen.title("Desenhin do Peano") screen.bgcolor(" screen.delay(0) screen.setup(width=0.95, height=0.9) walk = 1 def screenlength(k): if k != 0: length = screenlength(k-1) return 2*length + 1 else: return 0 kkkj = screenlength(iterations) screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1) ivan.color(" def step1(k): global stack stack.append(len(inspect.stack())) if k != 0: ivan.left(90) step2(k - 1) ivan.forward(walk) ivan.right(90) step1(k - 1) ivan.forward(walk) step1(k - 1) ivan.right(90) ivan.forward(walk) step2(k - 1) ivan.left(90) def step2(k): global stack stack.append(len(inspect.stack())) if k != 0: ivan.right(90) step1(k - 1) ivan.forward(walk) ivan.left(90) step2(k - 1) ivan.forward(walk) step2(k - 1) ivan.left(90) ivan.forward(walk) step1(k - 1) ivan.right(90) ivan.left(90) step2(iterations) tt.done() if __name__ == "__main__": peano(4) import pylab as P P.plot(stack) P.show()
#include <cmath> #include <fstream> #include <iostream> #include <string> class peano_curve { public: void write(std::ostream& out, int size, int length, int order); private: static std::string rewrite(const std::string& s); void line(std::ostream& out); void execute(std::ostream& out, const std::string& s); double x_; double y_; int angle_; int length_; }; void peano_curve::write(std::ostream& out, int size, int length, int order) { length_ = length; x_ = length; y_ = length; angle_ = 90; out << "<svg xmlns='http: << size << "' height='" << size << "'>\n"; out << "<rect width='100%' height='100%' fill='white'/>\n"; out << "<path stroke-width='1' stroke='black' fill='none' d='"; std::string s = "L"; for (int i = 0; i < order; ++i) s = rewrite(s); execute(out, s); out << "'/>\n</svg>\n"; } std::string peano_curve::rewrite(const std::string& s) { std::string t; for (char c : s) { switch (c) { case 'L': t += "LFRFL-F-RFLFR+F+LFRFL"; break; case 'R': t += "RFLFR+F+LFRFL-F-RFLFR"; break; default: t += c; break; } } return t; } void peano_curve::line(std::ostream& out) { double theta = (3.14159265359 * angle_)/180.0; x_ += length_ * std::cos(theta); y_ += length_ * std::sin(theta); out << " L" << x_ << ',' << y_; } void peano_curve::execute(std::ostream& out, const std::string& s) { out << 'M' << x_ << ',' << y_; for (char c : s) { switch (c) { case 'F': line(out); break; case '+': angle_ = (angle_ + 90) % 360; break; case '-': angle_ = (angle_ - 90) % 360; break; } } } int main() { std::ofstream out("peano_curve.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return 1; } peano_curve pc; pc.write(out, 656, 8, 4); return 0; }
Produce a language-to-language conversion: from Python to C++, same semantics.
from random import randint def dice5(): return randint(1, 5) def dice7(): r = dice5() + dice5() * 5 - 6 return (r % 7) + 1 if r < 21 else dice7()
template<typename F> class fivetoseven { public: fivetoseven(F f): d5(f), rem(0), max(1) {} int operator()(); private: F d5; int rem, max; }; template<typename F> int fivetoseven<F>::operator()() { while (rem/7 == max/7) { while (max < 7) { int rand5 = d5()-1; max *= 5; rem = 5*rem + rand5; } int groups = max / 7; if (rem >= 7*groups) { rem -= 7*groups; max -= 7*groups; } } int result = rem % 7; rem /= 7; max /= 7; return result+1; } int d5() { return 5.0*std::rand()/(RAND_MAX + 1.0) + 1; } fivetoseven<int(*)()> d7(d5); int main() { srand(time(0)); test_distribution(d5, 1000000, 0.001); test_distribution(d7, 1000000, 0.001); }
Generate an equivalent C++ version of this Python code.
from __future__ import print_function from itertools import permutations from enum import Enum A, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H') connections = ((A, C), (A, D), (A, E), (B, D), (B, E), (B, F), (G, C), (G, D), (G, E), (H, D), (H, E), (H, F), (C, D), (D, E), (E, F)) def ok(conn, perm): this, that = (c.value - 1 for c in conn) return abs(perm[this] - perm[that]) != 1 def solve(): return [perm for perm in permutations(range(1, 9)) if all(ok(conn, perm) for conn in connections)] if __name__ == '__main__': solutions = solve() print("A, B, C, D, E, F, G, H =", ', '.join(str(i) for i in solutions[0]))
#include <array> #include <iostream> #include <vector> std::vector<std::pair<int, int>> connections = { {0, 2}, {0, 3}, {0, 4}, {1, 3}, {1, 4}, {1, 5}, {6, 2}, {6, 3}, {6, 4}, {7, 3}, {7, 4}, {7, 5}, {2, 3}, {3, 4}, {4, 5}, }; std::array<int, 8> pegs; int num = 0; void printSolution() { std::cout << "----- " << num++ << " -----\n"; std::cout << " " << pegs[0] << ' ' << pegs[1] << '\n'; std::cout << pegs[2] << ' ' << pegs[3] << ' ' << pegs[4] << ' ' << pegs[5] << '\n'; std::cout << " " << pegs[6] << ' ' << pegs[7] << '\n'; std::cout << '\n'; } bool valid() { for (size_t i = 0; i < connections.size(); i++) { if (abs(pegs[connections[i].first] - pegs[connections[i].second]) == 1) { return false; } } return true; } void solution(int le, int ri) { if (le == ri) { if (valid()) { printSolution(); } } else { for (size_t i = le; i <= ri; i++) { std::swap(pegs[le], pegs[i]); solution(le + 1, ri); std::swap(pegs[le], pegs[i]); } } } int main() { pegs = { 1, 2, 3, 4, 5, 6, 7, 8 }; solution(0, pegs.size() - 1); return 0; }
Produce a functionally identical C++ code for the snippet given in Python.
islice(count(7), 0, None, 2)
#include <iostream> #include <cstdint> #include <queue> #include <utility> #include <vector> #include <limits> template<typename integer> class prime_generator { public: integer next_prime(); integer count() const { return count_; } private: struct queue_item { queue_item(integer prime, integer multiple, unsigned int wheel_index) : prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {} integer prime_; integer multiple_; unsigned int wheel_index_; }; struct cmp { bool operator()(const queue_item& a, const queue_item& b) const { return a.multiple_ > b.multiple_; } }; static integer wheel_next(unsigned int& index) { integer offset = wheel_[index]; ++index; if (index == std::size(wheel_)) index = 0; return offset; } typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue; integer next_ = 11; integer count_ = 0; queue queue_; unsigned int wheel_index_ = 0; static const unsigned int wheel_[]; static const integer primes_[]; }; template<typename integer> const unsigned int prime_generator<integer>::wheel_[] = { 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10 }; template<typename integer> const integer prime_generator<integer>::primes_[] = { 2, 3, 5, 7 }; template<typename integer> integer prime_generator<integer>::next_prime() { if (count_ < std::size(primes_)) return primes_[count_++]; integer n = next_; integer prev = 0; while (!queue_.empty()) { queue_item item = queue_.top(); if (prev != 0 && prev != item.multiple_) n += wheel_next(wheel_index_); if (item.multiple_ > n) break; else if (item.multiple_ == n) { queue_.pop(); queue_item new_item(item); new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_); queue_.push(new_item); } else throw std::overflow_error("prime_generator: overflow!"); prev = item.multiple_; } if (std::numeric_limits<integer>::max()/n > n) queue_.emplace(n, n * n, wheel_index_); next_ = n + wheel_next(wheel_index_); ++count_; return n; } int main() { typedef uint32_t integer; prime_generator<integer> pgen; std::cout << "First 20 primes:\n"; for (int i = 0; i < 20; ++i) { integer p = pgen.next_prime(); if (i != 0) std::cout << ", "; std::cout << p; } std::cout << "\nPrimes between 100 and 150:\n"; for (int n = 0; ; ) { integer p = pgen.next_prime(); if (p > 150) break; if (p >= 100) { if (n != 0) std::cout << ", "; std::cout << p; ++n; } } int count = 0; for (;;) { integer p = pgen.next_prime(); if (p > 8000) break; if (p >= 7700) ++count; } std::cout << "\nNumber of primes between 7700 and 8000: " << count << '\n'; for (integer n = 10000; n <= 10000000; n *= 10) { integer prime; while (pgen.count() != n) prime = pgen.next_prime(); std::cout << n << "th prime: " << prime << '\n'; } return 0; }
Translate this program into C++ but keep the logic exactly as in Python.
islice(count(7), 0, None, 2)
#include <iostream> #include <cstdint> #include <queue> #include <utility> #include <vector> #include <limits> template<typename integer> class prime_generator { public: integer next_prime(); integer count() const { return count_; } private: struct queue_item { queue_item(integer prime, integer multiple, unsigned int wheel_index) : prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {} integer prime_; integer multiple_; unsigned int wheel_index_; }; struct cmp { bool operator()(const queue_item& a, const queue_item& b) const { return a.multiple_ > b.multiple_; } }; static integer wheel_next(unsigned int& index) { integer offset = wheel_[index]; ++index; if (index == std::size(wheel_)) index = 0; return offset; } typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue; integer next_ = 11; integer count_ = 0; queue queue_; unsigned int wheel_index_ = 0; static const unsigned int wheel_[]; static const integer primes_[]; }; template<typename integer> const unsigned int prime_generator<integer>::wheel_[] = { 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10 }; template<typename integer> const integer prime_generator<integer>::primes_[] = { 2, 3, 5, 7 }; template<typename integer> integer prime_generator<integer>::next_prime() { if (count_ < std::size(primes_)) return primes_[count_++]; integer n = next_; integer prev = 0; while (!queue_.empty()) { queue_item item = queue_.top(); if (prev != 0 && prev != item.multiple_) n += wheel_next(wheel_index_); if (item.multiple_ > n) break; else if (item.multiple_ == n) { queue_.pop(); queue_item new_item(item); new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_); queue_.push(new_item); } else throw std::overflow_error("prime_generator: overflow!"); prev = item.multiple_; } if (std::numeric_limits<integer>::max()/n > n) queue_.emplace(n, n * n, wheel_index_); next_ = n + wheel_next(wheel_index_); ++count_; return n; } int main() { typedef uint32_t integer; prime_generator<integer> pgen; std::cout << "First 20 primes:\n"; for (int i = 0; i < 20; ++i) { integer p = pgen.next_prime(); if (i != 0) std::cout << ", "; std::cout << p; } std::cout << "\nPrimes between 100 and 150:\n"; for (int n = 0; ; ) { integer p = pgen.next_prime(); if (p > 150) break; if (p >= 100) { if (n != 0) std::cout << ", "; std::cout << p; ++n; } } int count = 0; for (;;) { integer p = pgen.next_prime(); if (p > 8000) break; if (p >= 7700) ++count; } std::cout << "\nNumber of primes between 7700 and 8000: " << count << '\n'; for (integer n = 10000; n <= 10000000; n *= 10) { integer prime; while (pgen.count() != n) prime = pgen.next_prime(); std::cout << n << "th prime: " << prime << '\n'; } return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
from random import choice rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'} previous = ['rock', 'paper', 'scissors'] while True: human = input('\nchoose your weapon: ') computer = rules[choice(previous)] if human in ('quit', 'exit'): break elif human in rules: previous.append(human) print('the computer played', computer, end='; ') if rules[computer] == human: print('yay you win!') elif rules[human] == computer: print('the computer beat you... :(') else: print("it's a tie!") else: print("that's not a valid choice")
#include <windows.h> #include <iostream> #include <string> using namespace std; enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C }; enum indexes { PLAYER, COMPUTER, DRAW }; class stats { public: stats() : _draw( 0 ) { ZeroMemory( _moves, sizeof( _moves ) ); ZeroMemory( _win, sizeof( _win ) ); } void draw() { _draw++; } void win( int p ) { _win[p]++; } void move( int p, int m ) { _moves[p][m]++; } int getMove( int p, int m ) { return _moves[p][m]; } string format( int a ) { char t[32]; wsprintf( t, "%.3d", a ); string d( t ); return d; } void print() { string d = format( _draw ), pw = format( _win[PLAYER] ), cw = format( _win[COMPUTER] ), pr = format( _moves[PLAYER][ROCK] ), cr = format( _moves[COMPUTER][ROCK] ), pp = format( _moves[PLAYER][PAPER] ), cp = format( _moves[COMPUTER][PAPER] ), ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ), pl = format( _moves[PLAYER][LIZARD] ), cl = format( _moves[COMPUTER][LIZARD] ), pk = format( _moves[PLAYER][SPOCK] ), ck = format( _moves[COMPUTER][SPOCK] ); system( "cls" ); cout << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |" << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << "| PLAYER | " << pw << " | | " << pr << " | " << pp << " | " << ps << " | " << pl << " | " << pk << " |" << endl; cout << "+----------+-------+ " << d << " +--------+---------+----------+--------+---------+" << endl; cout << "| COMPUTER | " << cw << " | | " << cr << " | " << cp << " | " << cs << " | " << cl << " | " << ck << " |" << endl; cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl; cout << endl << endl; system( "pause" ); } private: int _moves[2][MX_C], _win[2], _draw; }; class rps { private: int makeMove() { int total = 0, r, s; for( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) ); r = rand() % total; for( int i = ROCK; i < SCISSORS; i++ ) { s = statistics.getMove( PLAYER, i ); if( r < s ) return ( i + 1 ); r -= s; } return ROCK; } void printMove( int p, int m ) { if( p == COMPUTER ) cout << "My move: "; else cout << "Your move: "; switch( m ) { case ROCK: cout << "ROCK\n"; break; case PAPER: cout << "PAPER\n"; break; case SCISSORS: cout << "SCISSORS\n"; break; case LIZARD: cout << "LIZARD\n"; break; case SPOCK: cout << "SPOCK\n"; } } public: rps() { checker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1; checker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0; checker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1; checker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0; checker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2; } void play() { int p, r, m; while( true ) { cout << "What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? "; cin >> p; if( !p || p < 0 ) break; if( p > 0 && p < 6 ) { p--; cout << endl; printMove( PLAYER, p ); statistics.move( PLAYER, p ); m = makeMove(); statistics.move( COMPUTER, m ); printMove( COMPUTER, m ); r = checker[p][m]; switch( r ) { case DRAW: cout << endl << "DRAW!" << endl << endl; statistics.draw(); break; case COMPUTER: cout << endl << "I WIN!" << endl << endl; statistics.win( COMPUTER ); break; case PLAYER: cout << endl << "YOU WIN!" << endl << endl; statistics.win( PLAYER ); } system( "pause" ); } system( "cls" ); } statistics.print(); } private: stats statistics; int checker[MX_C][MX_C]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); rps game; game.play(); return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
width = int(raw_input("Width of myarray: ")) height = int(raw_input("Height of Array: ")) myarray = [[0] * width for i in range(height)] myarray[0][0] = 3.5 print (myarray[0][0])
#include <iostream> int main() { int dim1, dim2; std::cin >> dim1 >> dim2; double* array_data = new double[dim1*dim2]; double** array = new double*[dim1]; for (int i = 0; i < dim1; ++i) array[i] = array_data + dim2*i; array[0][0] = 3.5; std::cout << array[0][0] << std::endl; delete[] array; delete[] array_data; return 0; }
Translate this program into C++ but keep the logic exactly as in Python.
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Ensure the translated C++ code behaves exactly like the original Python snippet.
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Change the following Python code into C++ without altering its purpose.
from string import uppercase from operator import itemgetter def vigenere_decrypt(target_freqs, input): nchars = len(uppercase) ordA = ord('A') sorted_targets = sorted(target_freqs) def frequency(input): result = [[c, 0.0] for c in uppercase] for c in input: result[c - ordA][1] += 1 return result def correlation(input): result = 0.0 freq = frequency(input) freq.sort(key=itemgetter(1)) for i, f in enumerate(freq): result += f[1] * sorted_targets[i] return result cleaned = [ord(c) for c in input.upper() if c.isupper()] best_len = 0 best_corr = -100.0 for i in xrange(2, len(cleaned) // 20): pieces = [[] for _ in xrange(i)] for j, c in enumerate(cleaned): pieces[j % i].append(c) corr = -0.5 * i + sum(correlation(p) for p in pieces) if corr > best_corr: best_len = i best_corr = corr if best_len == 0: return ("Text is too short to analyze", "") pieces = [[] for _ in xrange(best_len)] for i, c in enumerate(cleaned): pieces[i % best_len].append(c) freqs = [frequency(p) for p in pieces] key = "" for fr in freqs: fr.sort(key=itemgetter(1), reverse=True) m = 0 max_corr = 0.0 for j in xrange(nchars): corr = 0.0 c = ordA + j for frc in fr: d = (ord(frc[0]) - c + nchars) % nchars corr += frc[1] * target_freqs[d] if corr > max_corr: m = j max_corr = corr key += chr(m + ordA) r = (chr((c - ord(key[i % best_len]) + nchars) % nchars + ordA) for i, c in enumerate(cleaned)) return (key, "".join(r)) def main(): encoded = english_frequences = [ 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074] (key, decoded) = vigenere_decrypt(english_frequences, encoded) print "Key:", key print "\nText:", decoded main()
#include <iostream> #include <string> #include <vector> #include <map> #include <algorithm> #include <array> using namespace std; typedef array<pair<char, double>, 26> FreqArray; class VigenereAnalyser { private: array<double, 26> targets; array<double, 26> sortedTargets; FreqArray freq; FreqArray& frequency(const string& input) { for (char c = 'A'; c <= 'Z'; ++c) freq[c - 'A'] = make_pair(c, 0); for (size_t i = 0; i < input.size(); ++i) freq[input[i] - 'A'].second++; return freq; } double correlation(const string& input) { double result = 0.0; frequency(input); sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool { return u.second < v.second; }); for (size_t i = 0; i < 26; ++i) result += freq[i].second * sortedTargets[i]; return result; } public: VigenereAnalyser(const array<double, 26>& targetFreqs) { targets = targetFreqs; sortedTargets = targets; sort(sortedTargets.begin(), sortedTargets.end()); } pair<string, string> analyze(string input) { string cleaned; for (size_t i = 0; i < input.size(); ++i) { if (input[i] >= 'A' && input[i] <= 'Z') cleaned += input[i]; else if (input[i] >= 'a' && input[i] <= 'z') cleaned += input[i] + 'A' - 'a'; } size_t bestLength = 0; double bestCorr = -100.0; for (size_t i = 2; i < cleaned.size() / 20; ++i) { vector<string> pieces(i); for (size_t j = 0; j < cleaned.size(); ++j) pieces[j % i] += cleaned[j]; double corr = -0.5*i; for (size_t j = 0; j < i; ++j) corr += correlation(pieces[j]); if (corr > bestCorr) { bestLength = i; bestCorr = corr; } } if (bestLength == 0) return make_pair("Text is too short to analyze", ""); vector<string> pieces(bestLength); for (size_t i = 0; i < cleaned.size(); ++i) pieces[i % bestLength] += cleaned[i]; vector<FreqArray> freqs; for (size_t i = 0; i < bestLength; ++i) freqs.push_back(frequency(pieces[i])); string key = ""; for (size_t i = 0; i < bestLength; ++i) { sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool { return u.second > v.second; }); size_t m = 0; double mCorr = 0.0; for (size_t j = 0; j < 26; ++j) { double corr = 0.0; char c = 'A' + j; for (size_t k = 0; k < 26; ++k) { int d = (freqs[i][k].first - c + 26) % 26; corr += freqs[i][k].second * targets[d]; } if (corr > mCorr) { m = j; mCorr = corr; } } key += m + 'A'; } string result = ""; for (size_t i = 0; i < cleaned.size(); ++i) result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A'; return make_pair(result, key); } }; int main() { string input = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; array<double, 26> english = { 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074}; VigenereAnalyser va(english); pair<string, string> output = va.analyze(input); cout << "Key: " << output.second << endl << endl; cout << "Text: " << output.first << endl; }
Generate a C++ translation of this Python snippet without changing its computational steps.
def calcPi(): q, r, t, k, n, l = 1, 0, 1, 1, 3, 3 while True: if 4*q+r-t < n*t: yield n nr = 10*(r-n*t) n = ((10*(3*q+r))//t)-10*n q *= 10 r = nr else: nr = (2*q+r)*l nn = (q*(7*k)+2+(r*l))//(t*l) q *= k t *= l l += 2 k += 1 n = nn r = nr import sys pi_digits = calcPi() i = 0 for d in pi_digits: sys.stdout.write(str(d)) i += 1 if i == 40: print(""); i = 0
#include <iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; class Gospers { cpp_int q, r, t, i, n; public: Gospers() : q{1}, r{0}, t{1}, i{1} { ++*this; } Gospers& operator++() { n = (q*(27*i-12)+5*r) / (5*t); while(n != (q*(675*i-216)+125*r)/(125*t)) { r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r); q = i*(2*i-1)*q; t = 3*(3*i+1)*(3*i+2)*t; i++; n = (q*(27*i-12)+5*r) / (5*t); } q = 10*q; r = 10*r-10*n*t; return *this; } int operator*() { return (int)n; } }; int main() { Gospers g; std::cout << *g << "."; for(;;) { std::cout << *++g; } }
Convert this Python block to C++, preserving its control flow and logic.
def q(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return q.seq[n] except IndexError: ans = q(n - q(n - 1)) + q(n - q(n - 2)) q.seq.append(ans) return ans q.seq = [None, 1, 1] if __name__ == '__main__': first10 = [q(i) for i in range(1,11)] assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)" print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10)) assert q(1000) == 502, "Q(1000) value error" print("Q(1000) =", q(1000))
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }
Preserve the algorithm and functionality while converting the code from Python to C++.
def q(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return q.seq[n] except IndexError: ans = q(n - q(n - 1)) + q(n - q(n - 2)) q.seq.append(ans) return ans q.seq = [None, 1, 1] if __name__ == '__main__': first10 = [q(i) for i in range(1,11)] assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)" print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10)) assert q(1000) == 502, "Q(1000) value error" print("Q(1000) =", q(1000))
#include <iostream> int main() { const int size = 100000; int hofstadters[size] = { 1, 1 }; for (int i = 3 ; i < size; i++) hofstadters[ i - 1 ] = hofstadters[ i - 1 - hofstadters[ i - 1 - 1 ]] + hofstadters[ i - 1 - hofstadters[ i - 2 - 1 ]]; std::cout << "The first 10 numbers are: "; for (int i = 0; i < 10; i++) std::cout << hofstadters[ i ] << ' '; std::cout << std::endl << "The 1000'th term is " << hofstadters[ 999 ] << " !" << std::endl; int less_than_preceding = 0; for (int i = 0; i < size - 1; i++) if (hofstadters[ i + 1 ] < hofstadters[ i ]) less_than_preceding++; std::cout << "In array of size: " << size << ", "; std::cout << less_than_preceding << " times a number was preceded by a greater number!" << std::endl; return 0; }
Produce a functionally identical C++ code for the snippet given in Python.
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1)) >>> [ Y(fac)(i) for i in range(10) ] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] >>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)) >>> [ Y(fib)(i) for i in range(10) ] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#include <iostream> #include <functional> template <typename F> struct RecursiveFunc { std::function<F(RecursiveFunc)> o; }; template <typename A, typename B> std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) { RecursiveFunc<std::function<B(A)>> r = { std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) { return f(std::function<B(A)>([w](A x) { return w.o(w)(x); })); }) }; return r.o(r); } typedef std::function<int(int)> Func; typedef std::function<Func(Func)> FuncFunc; FuncFunc almost_fac = [](Func f) { return Func([f](int n) { if (n <= 1) return 1; return n * f(n - 1); }); }; FuncFunc almost_fib = [](Func f) { return Func([f](int n) { if (n <= 2) return 1; return f(n - 1) + f(n - 2); }); }; int main() { auto fib = Y(almost_fib); auto fac = Y(almost_fac); std::cout << "fib(10) = " << fib(10) << std::endl; std::cout << "fac(10) = " << fac(10) << std::endl; return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1)) >>> [ Y(fac)(i) for i in range(10) ] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] >>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)) >>> [ Y(fib)(i) for i in range(10) ] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#include <iostream> #include <functional> template <typename F> struct RecursiveFunc { std::function<F(RecursiveFunc)> o; }; template <typename A, typename B> std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) { RecursiveFunc<std::function<B(A)>> r = { std::function<std::function<B(A)>(RecursiveFunc<std::function<B(A)>>)>([f](RecursiveFunc<std::function<B(A)>> w) { return f(std::function<B(A)>([w](A x) { return w.o(w)(x); })); }) }; return r.o(r); } typedef std::function<int(int)> Func; typedef std::function<Func(Func)> FuncFunc; FuncFunc almost_fac = [](Func f) { return Func([f](int n) { if (n <= 1) return 1; return n * f(n - 1); }); }; FuncFunc almost_fib = [](Func f) { return Func([f](int n) { if (n <= 2) return 1; return f(n - 1) + f(n - 2); }); }; int main() { auto fib = Y(almost_fib); auto fac = Y(almost_fac); std::cout << "fib(10) = " << fib(10) << std::endl; std::cout << "fac(10) = " << fac(10) << std::endl; return 0; }
Port the provided Python code into C++ while preserving the original functionality.
def addsub(x, y): return x + y, x - y
#include <algorithm> #include <array> #include <cstdint> #include <iostream> #include <tuple> std::tuple<int, int> minmax(const int * numbers, const std::size_t num) { const auto maximum = std::max_element(numbers, numbers + num); const auto minimum = std::min_element(numbers, numbers + num); return std::make_tuple(*minimum, *maximum) ; } int main( ) { const auto numbers = std::array<int, 8>{{17, 88, 9, 33, 4, 987, -10, 2}}; int min{}; int max{}; std::tie(min, max) = minmax(numbers.data(), numbers.size()); std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ; }
Produce a language-to-language conversion: from Python to C++, same semantics.
def van_eck(): n, seen, val = 0, {}, 0 while True: yield val last = {val: n} val = n - seen.get(val, n) seen.update(last) n += 1 if __name__ == '__main__': print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10))) print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
def van_eck(): n, seen, val = 0, {}, 0 while True: yield val last = {val: n} val = n - seen.get(val, n) seen.update(last) n += 1 if __name__ == '__main__': print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10))) print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
#include <iostream> #include <map> class van_eck_generator { public: int next() { int result = last_term; auto iter = last_pos.find(last_term); int next_term = (iter != last_pos.end()) ? index - iter->second : 0; last_pos[last_term] = index; last_term = next_term; ++index; return result; } private: int index = 0; int last_term = 0; std::map<int, int> last_pos; }; int main() { van_eck_generator gen; int i = 0; std::cout << "First 10 terms of the Van Eck sequence:\n"; for (; i < 10; ++i) std::cout << gen.next() << ' '; for (; i < 990; ++i) gen.next(); std::cout << "\nTerms 991 to 1000 of the sequence:\n"; for (; i < 1000; ++i) std::cout << gen.next() << ' '; std::cout << '\n'; return 0; }