Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Please provide an equivalent version of this C++ code in C#.
#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); } } }
Write the same code in C++ as shown below in C#.
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; } }
#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; }
Please provide an equivalent version of this C++ code in C#.
#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; }
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(); } } } } } }
Rewrite the snippet below in C++ so it works the same as the original C# code.
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; }
Generate a C# translation of this C++ snippet without changing its computational steps.
#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); } } }
Generate a C++ translation of this C# snippet without changing its computational steps.
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; }
Ensure the translated C# code behaves exactly like the original C++ snippet.
#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)); } }
Rewrite this program in C++ while keeping its functionality equivalent to the C# version.
int a=0,b=1/a;
#include <stdexcept> int main() { throw std::runtime_error("boom"); }
Port the following code from C++ to C# with equivalent syntax and logic.
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; }
interface IEatable { void Eat(); }
Write the same code in C# as shown below in C++.
#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; }
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)); } } }
Rewrite this program in C# while keeping its functionality equivalent to the C++ version.
#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; }
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; } } }
Rewrite this program in C# while keeping its functionality equivalent to the C++ version.
#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; }
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); } } }
Preserve the algorithm and functionality while converting the code from C++ to C#.
#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(); }
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(); } } }
Convert this C++ block to C#, preserving its control flow and logic.
#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(); }
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(); } } }
Change the programming language of this snippet from C++ to C# without modifying what it does.
#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; }
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()); } } } }
Convert this C++ snippet to C# and keep its semantics consistent.
#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; };
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 }
Generate a C# translation of this C++ snippet without changing its computational steps.
#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 a C++ translation of this C# snippet without changing its computational steps.
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" ); }
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)[] 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" ); }
Transform the following C# implementation into C++, maintaining the same output and logic.
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; } } }
#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; }
Please provide an equivalent version of this C++ code in C#.
#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; }
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; } }
Change the following C++ code into C# without altering its purpose.
#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; }
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; } }
Can you help me rewrite this code in C# instead of C++, keeping it the same logically?
#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"; }
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) ); } } }
Translate the given C++ code snippet into C# without altering its behavior.
#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"; }
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) ); } } }
Write the same algorithm in C# as shown in this C++ implementation.
#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"; }
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) ); } } }
Change the following C++ code into C# without altering its purpose.
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(); }
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(); } }
Write the same algorithm in C++ as shown in this C# implementation.
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); } } } }
#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; }
Change the following C++ code into C# without altering its purpose.
#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; }
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); } }
Port the following code from C++ to C# with equivalent syntax and logic.
class Animal { }; class Dog: public Animal { }; class Lab: public Dog { }; class Collie: public Dog { }; class Cat: public Animal { };
class Animal { } class Dog : Animal { } class Lab : Dog { } class Collie : Dog { } class Cat : Animal { }
Convert the following code from C++ to C#, ensuring the logic remains intact.
#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); } }
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;
Write the same algorithm in C# as shown in this C++ implementation.
#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; }
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(); } }
Change the programming language of this snippet from C++ to C# without modifying what it does.
#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; }
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(); } }
Convert this C# block to C++, preserving its control flow and logic.
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); } }
#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; }
Produce a language-to-language conversion: from C# to C++, same semantics.
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); } }
#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; }
Can you help me rewrite this code in C# instead of C++, keeping it the same logically?
#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); }
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); } }
Keep all operations the same but rewrite the snippet in Python.
#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; }
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))
Produce a language-to-language conversion: from C++ to Python, same semantics.
#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) ; }
>>> 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
Produce a language-to-language conversion: from C++ to Python, same semantics.
#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; }
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()
Generate a Python translation of this C++ snippet without changing its computational steps.
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); }
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()
Port the following code from C++ to Python with equivalent syntax and logic.
#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; }
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]))
Produce a functionally identical Python code for the snippet given in C++.
#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; }
islice(count(7), 0, None, 2)
Convert this C++ block to Python, preserving its control flow and logic.
#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; }
islice(count(7), 0, None, 2)
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#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; }
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")
Write a version of this C++ function in Python with identical behavior.
#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; }
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])
Preserve the algorithm and functionality while converting the code from C++ to Python.
#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; }
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)
Write the same code in Python as shown below in C++.
#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; }
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)
Produce a functionally identical Python code for the snippet given in C++.
#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; }
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()
Please provide an equivalent version of this C++ code in Python.
#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; } }
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
Generate a Python translation of this C++ snippet without changing its computational steps.
#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; }
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))
Write the same algorithm in Python as shown in this C++ implementation.
#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; }
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))
Write the same code in Python as shown below in C++.
#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; }
>>> 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]
Translate the given C++ code snippet into Python without altering its behavior.
#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; }
>>> 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]
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#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" ; }
def addsub(x, y): return x + y, x - y
Convert this C++ snippet to Python and keep its semantics consistent.
#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; }
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:])
Write a version of this C++ function in Python with identical behavior.
#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; }
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:])
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#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; }
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:])
Write a version of this C++ function in Python with identical behavior.
#include <iostream> #include <string> #include <cstring> #include <fstream> #include <sys/stat.h> #include <ftplib.h> #include <ftp++.hpp> int stat(const char *pathname, struct stat *buf); char *strerror(int errnum); char *basename(char *path); namespace stl { using std::cout; using std::cerr; using std::string; using std::ifstream; using std::remove; }; using namespace stl; using Mode = ftp::Connection::Mode; Mode PASV = Mode::PASSIVE; Mode PORT = Mode::PORT; using TransferMode = ftp::Connection::TransferMode; TransferMode BINARY = TransferMode::BINARY; TransferMode TEXT = TransferMode::TEXT; struct session { const string server; const string port; const string user; const string pass; Mode mode; TransferMode txmode; string dir; }; ftp::Connection connect_ftp( const session& sess); size_t get_ftp( ftp::Connection& conn, string const& path); string readFile( const string& filename); string login_ftp(ftp::Connection& conn, const session& sess); string dir_listing( ftp::Connection& conn, const string& path); string readFile( const string& filename) { struct stat stat_buf; string contents; errno = 0; if (stat(filename.c_str() , &stat_buf) != -1) { size_t len = stat_buf.st_size; string bytes(len+1, '\0'); ifstream ifs(filename); ifs.read(&bytes[0], len); if (! ifs.fail() ) contents.swap(bytes); ifs.close(); } else { cerr << "stat error: " << strerror(errno); } return contents; } ftp::Connection connect_ftp( const session& sess) try { string constr = sess.server + ":" + sess.port; cerr << "connecting to " << constr << " ...\n"; ftp::Connection conn{ constr.c_str() }; cerr << "connected to " << constr << "\n"; conn.setConnectionMode(sess.mode); return conn; } catch (ftp::ConnectException e) { cerr << "FTP error: could not connect to server" << "\n"; } string login_ftp(ftp::Connection& conn, const session& sess) { conn.login(sess.user.c_str() , sess.pass.c_str() ); return conn.getLastResponse(); } string dir_listing( ftp::Connection& conn, const string& path) try { const char* dirdata = "/dev/shm/dirdata"; conn.getList(dirdata, path.c_str() ); string dir_string = readFile(dirdata); cerr << conn.getLastResponse() << "\n"; errno = 0; if ( remove(dirdata) != 0 ) { cerr << "error: " << strerror(errno) << "\n"; } return dir_string; } catch (...) { cerr << "error: getting dir contents: \n" << strerror(errno) << "\n"; } size_t get_ftp( ftp::Connection& conn, const string& r_path) { size_t received = 0; const char* path = r_path.c_str(); unsigned remotefile_size = conn.size(path , BINARY); const char* localfile = basename(path); conn.get(localfile, path, BINARY); cerr << conn.getLastResponse() << "\n"; struct stat stat_buf; errno = 0; if (stat(localfile, &stat_buf) != -1) received = stat_buf.st_size; else cerr << strerror(errno); return received; } const session sonic { "mirrors.sonic.net", "21" , "anonymous", "xxxx@nohost.org", PASV, BINARY, "/pub/OpenBSD" }; int main(int argc, char* argv[], char * env[] ) { const session remote = sonic; try { ftp::Connection conn = connect_ftp(remote); cerr << login_ftp(conn, remote); cout << "System type: " << conn.getSystemType() << "\n"; cerr << conn.getLastResponse() << "\n"; conn.cd(remote.dir.c_str()); cerr << conn.getLastResponse() << "\n"; string pwdstr = conn.getDirectory(); cout << "PWD: " << pwdstr << "\n"; cerr << conn.getLastResponse() << "\n"; string dirlist = dir_listing(conn, pwdstr.c_str() ); cout << dirlist << "\n"; string filename = "ftplist"; auto pos = dirlist.find(filename); auto notfound = string::npos; if (pos != notfound) { size_t received = get_ftp(conn, filename.c_str() ); if (received == 0) cerr << "got 0 bytes\n"; else cerr << "got " << filename << " (" << received << " bytes)\n"; } else { cerr << "file " << filename << "not found on server. \n"; } } catch (ftp::ConnectException e) { cerr << "FTP error: could not connect to server" << "\n"; } catch (ftp::Exception e) { cerr << "FTP error: " << e << "\n"; } catch (...) { cerr << "error: " << strerror(errno) << "\n"; } return 0; }
from ftplib import FTP ftp = FTP('kernel.org') ftp.login() ftp.cwd('/pub/linux/kernel') ftp.set_pasv(True) print ftp.retrlines('LIST') print ftp.retrbinary('RETR README', open('README', 'wb').write) ftp.quit()
Write a version of this C++ function in Python with identical behavior.
#include <iostream> #include <string> #include <cstring> #include <fstream> #include <sys/stat.h> #include <ftplib.h> #include <ftp++.hpp> int stat(const char *pathname, struct stat *buf); char *strerror(int errnum); char *basename(char *path); namespace stl { using std::cout; using std::cerr; using std::string; using std::ifstream; using std::remove; }; using namespace stl; using Mode = ftp::Connection::Mode; Mode PASV = Mode::PASSIVE; Mode PORT = Mode::PORT; using TransferMode = ftp::Connection::TransferMode; TransferMode BINARY = TransferMode::BINARY; TransferMode TEXT = TransferMode::TEXT; struct session { const string server; const string port; const string user; const string pass; Mode mode; TransferMode txmode; string dir; }; ftp::Connection connect_ftp( const session& sess); size_t get_ftp( ftp::Connection& conn, string const& path); string readFile( const string& filename); string login_ftp(ftp::Connection& conn, const session& sess); string dir_listing( ftp::Connection& conn, const string& path); string readFile( const string& filename) { struct stat stat_buf; string contents; errno = 0; if (stat(filename.c_str() , &stat_buf) != -1) { size_t len = stat_buf.st_size; string bytes(len+1, '\0'); ifstream ifs(filename); ifs.read(&bytes[0], len); if (! ifs.fail() ) contents.swap(bytes); ifs.close(); } else { cerr << "stat error: " << strerror(errno); } return contents; } ftp::Connection connect_ftp( const session& sess) try { string constr = sess.server + ":" + sess.port; cerr << "connecting to " << constr << " ...\n"; ftp::Connection conn{ constr.c_str() }; cerr << "connected to " << constr << "\n"; conn.setConnectionMode(sess.mode); return conn; } catch (ftp::ConnectException e) { cerr << "FTP error: could not connect to server" << "\n"; } string login_ftp(ftp::Connection& conn, const session& sess) { conn.login(sess.user.c_str() , sess.pass.c_str() ); return conn.getLastResponse(); } string dir_listing( ftp::Connection& conn, const string& path) try { const char* dirdata = "/dev/shm/dirdata"; conn.getList(dirdata, path.c_str() ); string dir_string = readFile(dirdata); cerr << conn.getLastResponse() << "\n"; errno = 0; if ( remove(dirdata) != 0 ) { cerr << "error: " << strerror(errno) << "\n"; } return dir_string; } catch (...) { cerr << "error: getting dir contents: \n" << strerror(errno) << "\n"; } size_t get_ftp( ftp::Connection& conn, const string& r_path) { size_t received = 0; const char* path = r_path.c_str(); unsigned remotefile_size = conn.size(path , BINARY); const char* localfile = basename(path); conn.get(localfile, path, BINARY); cerr << conn.getLastResponse() << "\n"; struct stat stat_buf; errno = 0; if (stat(localfile, &stat_buf) != -1) received = stat_buf.st_size; else cerr << strerror(errno); return received; } const session sonic { "mirrors.sonic.net", "21" , "anonymous", "xxxx@nohost.org", PASV, BINARY, "/pub/OpenBSD" }; int main(int argc, char* argv[], char * env[] ) { const session remote = sonic; try { ftp::Connection conn = connect_ftp(remote); cerr << login_ftp(conn, remote); cout << "System type: " << conn.getSystemType() << "\n"; cerr << conn.getLastResponse() << "\n"; conn.cd(remote.dir.c_str()); cerr << conn.getLastResponse() << "\n"; string pwdstr = conn.getDirectory(); cout << "PWD: " << pwdstr << "\n"; cerr << conn.getLastResponse() << "\n"; string dirlist = dir_listing(conn, pwdstr.c_str() ); cout << dirlist << "\n"; string filename = "ftplist"; auto pos = dirlist.find(filename); auto notfound = string::npos; if (pos != notfound) { size_t received = get_ftp(conn, filename.c_str() ); if (received == 0) cerr << "got 0 bytes\n"; else cerr << "got " << filename << " (" << received << " bytes)\n"; } else { cerr << "file " << filename << "not found on server. \n"; } } catch (ftp::ConnectException e) { cerr << "FTP error: could not connect to server" << "\n"; } catch (ftp::Exception e) { cerr << "FTP error: " << e << "\n"; } catch (...) { cerr << "error: " << strerror(errno) << "\n"; } return 0; }
from ftplib import FTP ftp = FTP('kernel.org') ftp.login() ftp.cwd('/pub/linux/kernel') ftp.set_pasv(True) print ftp.retrlines('LIST') print ftp.retrbinary('RETR README', open('README', 'wb').write) ftp.quit()
Please provide an equivalent version of this C++ code in Python.
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); stk.push(f(a, b)); } void parse(char c) { if(c >= '0' && c <= '9') { stk.push(c - '0'); digits.insert(c - '0'); } else if(c == '+') op([](double a, double b) {return a+b;}); else if(c == '-') op([](double a, double b) {return a-b;}); else if(c == '*') op([](double a, double b) {return a*b;}); else if(c == '/') op([](double a, double b) {return a/b;}); } void parse(string s) { for(int i = 0; i < s.size(); ++i) parse(s[i]); } double getResult() { if(stk.size() != 1) throw "Improperly written expression"; return stk.top(); } }; int main() { random_device seed; mt19937 engine(seed()); uniform_int_distribution<> distribution(1, 9); auto rnd = bind(distribution, engine); multiset<int> digits; cout << "Make 24 with the digits: "; for(int i = 0; i < 4; ++i) { int n = rnd(); cout << " " << n; digits.insert(n); } cout << endl; RPNParse parser; try { string input; getline(cin, input); parser.parse(input); if(digits != parser.digits) cout << "Error: Not using the given digits" << endl; else { double r = parser.getResult(); cout << "Result: " << r << endl; if(r > 23.999 && r < 24.001) cout << "Good job!" << endl; else cout << "Try again." << endl; } } catch(char* e) { cout << "Error: " << e << endl; } return 0; }
from __future__ import division, print_function import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer.lower() == 'q': break if answer == '!': digits = choose4() print ("New digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") if __name__ == '__main__': main()
Write a version of this C++ function in Python with identical behavior.
#include <random> #include <iostream> #include <stack> #include <set> #include <string> #include <functional> using namespace std; class RPNParse { public: stack<double> stk; multiset<int> digits; void op(function<double(double,double)> f) { if(stk.size() < 2) throw "Improperly written expression"; int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); stk.push(f(a, b)); } void parse(char c) { if(c >= '0' && c <= '9') { stk.push(c - '0'); digits.insert(c - '0'); } else if(c == '+') op([](double a, double b) {return a+b;}); else if(c == '-') op([](double a, double b) {return a-b;}); else if(c == '*') op([](double a, double b) {return a*b;}); else if(c == '/') op([](double a, double b) {return a/b;}); } void parse(string s) { for(int i = 0; i < s.size(); ++i) parse(s[i]); } double getResult() { if(stk.size() != 1) throw "Improperly written expression"; return stk.top(); } }; int main() { random_device seed; mt19937 engine(seed()); uniform_int_distribution<> distribution(1, 9); auto rnd = bind(distribution, engine); multiset<int> digits; cout << "Make 24 with the digits: "; for(int i = 0; i < 4; ++i) { int n = rnd(); cout << " " << n; digits.insert(n); } cout << endl; RPNParse parser; try { string input; getline(cin, input); parser.parse(input); if(digits != parser.digits) cout << "Error: Not using the given digits" << endl; else { double r = parser.getResult(); cout << "Result: " << r << endl; if(r > 23.999 && r < 24.001) cout << "Good job!" << endl; else cout << "Try again." << endl; } } catch(char* e) { cout << "Error: " << e << endl; } return 0; }
from __future__ import division, print_function import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer.lower() == 'q': break if answer == '!': digits = choose4() print ("New digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") if __name__ == '__main__': main()
Translate this program into Python but keep the logic exactly as in C++.
for(int i = 1;i <= 10; i++){ cout << i; if(i % 5 == 0){ cout << endl; continue; } cout << ", "; }
for i in range(1, 11): if i % 5 == 0: print(i) continue print(i, end=', ')
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> class QPaintEvent ; class MyWidget : public QWidget { public : MyWidget( ) ; protected : void paintEvent( QPaintEvent * ) ; private : int width ; int height ; const int colornumber ; } ; #endif
from livewires import * horiz=640; vert=480 begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black) NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"] stepik=horiz/len(NameColors) for index,each in enumerate(NameColors): ExcStrng="set_colour(Colour."+each+")" exec ExcStrng box(index*stepik,0,(index+1)*stepik,vert,filled=1) while keys_pressed() != ['x']: pass end_graphics()
Translate the given C++ code snippet into Python without altering its behavior.
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> class QPaintEvent ; class MyWidget : public QWidget { public : MyWidget( ) ; protected : void paintEvent( QPaintEvent * ) ; private : int width ; int height ; const int colornumber ; } ; #endif
from livewires import * horiz=640; vert=480 begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black) NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"] stepik=horiz/len(NameColors) for index,each in enumerate(NameColors): ExcStrng="set_colour(Colour."+each+")" exec ExcStrng box(index*stepik,0,(index+1)*stepik,vert,filled=1) while keys_pressed() != ['x']: pass end_graphics()
Write the same algorithm in Python as shown in this C++ implementation.
#include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <limits> #include <numeric> #include <sstream> #include <vector> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, scalar_type value) : rows_(rows), columns_(columns), elements_(rows * columns, value) {} matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<scalar_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[i]); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const scalar_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } scalar_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } private: size_t rows_; size_t columns_; std::vector<scalar_type> elements_; }; template <typename scalar_type> void print(std::wostream& out, const matrix<scalar_type>& a) { const wchar_t* box_top_left = L"\x23a1"; const wchar_t* box_top_right = L"\x23a4"; const wchar_t* box_left = L"\x23a2"; const wchar_t* box_right = L"\x23a5"; const wchar_t* box_bottom_left = L"\x23a3"; const wchar_t* box_bottom_right = L"\x23a6"; const int precision = 5; size_t rows = a.rows(), columns = a.columns(); std::vector<size_t> width(columns); for (size_t column = 0; column < columns; ++column) { size_t max_width = 0; for (size_t row = 0; row < rows; ++row) { std::ostringstream str; str << std::fixed << std::setprecision(precision) << a(row, column); max_width = std::max(max_width, str.str().length()); } width[column] = max_width; } out << std::fixed << std::setprecision(precision); for (size_t row = 0; row < rows; ++row) { const bool top(row == 0), bottom(row + 1 == rows); out << (top ? box_top_left : (bottom ? box_bottom_left : box_left)); for (size_t column = 0; column < columns; ++column) { if (column > 0) out << L' '; out << std::setw(width[column]) << a(row, column); } out << (top ? box_top_right : (bottom ? box_bottom_right : box_right)); out << L'\n'; } } template <typename scalar_type> auto lu_decompose(const matrix<scalar_type>& input) { assert(input.rows() == input.columns()); size_t n = input.rows(); std::vector<size_t> perm(n); std::iota(perm.begin(), perm.end(), 0); matrix<scalar_type> lower(n, n); matrix<scalar_type> upper(n, n); matrix<scalar_type> input1(input); for (size_t j = 0; j < n; ++j) { size_t max_index = j; scalar_type max_value = 0; for (size_t i = j; i < n; ++i) { scalar_type value = std::abs(input1(perm[i], j)); if (value > max_value) { max_index = i; max_value = value; } } if (max_value <= std::numeric_limits<scalar_type>::epsilon()) throw std::runtime_error("matrix is singular"); if (j != max_index) std::swap(perm[j], perm[max_index]); size_t jj = perm[j]; for (size_t i = j + 1; i < n; ++i) { size_t ii = perm[i]; input1(ii, j) /= input1(jj, j); for (size_t k = j + 1; k < n; ++k) input1(ii, k) -= input1(ii, j) * input1(jj, k); } } for (size_t j = 0; j < n; ++j) { lower(j, j) = 1; for (size_t i = j + 1; i < n; ++i) lower(i, j) = input1(perm[i], j); for (size_t i = 0; i <= j; ++i) upper(i, j) = input1(perm[i], j); } matrix<scalar_type> pivot(n, n); for (size_t i = 0; i < n; ++i) pivot(i, perm[i]) = 1; return std::make_tuple(lower, upper, pivot); } template <typename scalar_type> void show_lu_decomposition(const matrix<scalar_type>& input) { try { std::wcout << L"A\n"; print(std::wcout, input); auto result(lu_decompose(input)); std::wcout << L"\nL\n"; print(std::wcout, std::get<0>(result)); std::wcout << L"\nU\n"; print(std::wcout, std::get<1>(result)); std::wcout << L"\nP\n"; print(std::wcout, std::get<2>(result)); } catch (const std::exception& ex) { std::cerr << ex.what() << '\n'; } } int main() { std::wcout.imbue(std::locale("")); std::wcout << L"Example 1:\n"; matrix<double> matrix1(3, 3, {{1, 3, 5}, {2, 4, 7}, {1, 1, 0}}); show_lu_decomposition(matrix1); std::wcout << '\n'; std::wcout << L"Example 2:\n"; matrix<double> matrix2(4, 4, {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}}); show_lu_decomposition(matrix2); std::wcout << '\n'; std::wcout << L"Example 3:\n"; matrix<double> matrix3(3, 3, {{-5, -6, -3}, {-1, 0, -2}, {-3, -4, -7}}); show_lu_decomposition(matrix3); std::wcout << '\n'; std::wcout << L"Example 4:\n"; matrix<double> matrix4(3, 3, {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}); show_lu_decomposition(matrix4); return 0; }
from pprint import pprint def matrixMul(A, B): TB = zip(*B) return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A] def pivotize(m): n = len(m) ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)] for j in xrange(n): row = max(xrange(j, n), key=lambda i: abs(m[i][j])) if j != row: ID[j], ID[row] = ID[row], ID[j] return ID def lu(A): n = len(A) L = [[0.0] * n for i in xrange(n)] U = [[0.0] * n for i in xrange(n)] P = pivotize(A) A2 = matrixMul(P, A) for j in xrange(n): L[j][j] = 1.0 for i in xrange(j+1): s1 = sum(U[k][j] * L[i][k] for k in xrange(i)) U[i][j] = A2[i][j] - s1 for i in xrange(j, n): s2 = sum(U[k][j] * L[i][k] for k in xrange(j)) L[i][j] = (A2[i][j] - s2) / U[j][j] return (L, U, P) a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]] for part in lu(a): pprint(part, width=19) print print b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]] for part in lu(b): pprint(part) print
Ensure the translated Python code behaves exactly like the original C++ snippet.
#include <algorithm> #include <iostream> #include <vector> #include <string> class pair { public: pair( int s, std::string z ) { p = std::make_pair( s, z ); } bool operator < ( const pair& o ) const { return i() < o.i(); } int i() const { return p.first; } std::string s() const { return p.second; } private: std::pair<int, std::string> p; }; void gFizzBuzz( int c, std::vector<pair>& v ) { bool output; for( int x = 1; x <= c; x++ ) { output = false; for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) { if( !( x % ( *i ).i() ) ) { std::cout << ( *i ).s(); output = true; } } if( !output ) std::cout << x; std::cout << "\n"; } } int main( int argc, char* argv[] ) { std::vector<pair> v; v.push_back( pair( 7, "Baxx" ) ); v.push_back( pair( 3, "Fizz" ) ); v.push_back( pair( 5, "Buzz" ) ); std::sort( v.begin(), v.end() ); gFizzBuzz( 20, v ); return 0; }
def genfizzbuzz(factorwords, numbers): factorwords.sort(key=lambda factor_and_word: factor_and_word[0]) lines = [] for num in numbers: words = ''.join(word for factor, word in factorwords if (num % factor) == 0) lines.append(words if words else str(num)) return '\n'.join(lines) if __name__ == '__main__': print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look at ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ; std::getline( std::cin , input ) ; int linenumber = std::stoi( input ) ; int lines_read = 0 ; std::string line ; if ( infile.is_open( ) ) { while ( infile ) { getline( infile , line ) ; lines_read++ ; if ( lines_read == linenumber ) { std::cout << line << std::endl ; break ; } } infile.close( ) ; if ( lines_read < linenumber ) std::cout << "No " << linenumber << " lines in " << file << " !\n" ; return 0 ; } else { std::cerr << "Could not find file " << file << " !\n" ; return 1 ; } }
with open('xxx.txt') as f: for i, line in enumerate(f): if i == 6: break else: print('Not 7 lines in file') line = None
Write a version of this C++ function in Python with identical behavior.
#include <string> #include <fstream> #include <iostream> int main( ) { std::cout << "Which file do you want to look at ?\n" ; std::string input ; std::getline( std::cin , input ) ; std::ifstream infile( input.c_str( ) , std::ios::in ) ; std::string file( input ) ; std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ; std::getline( std::cin , input ) ; int linenumber = std::stoi( input ) ; int lines_read = 0 ; std::string line ; if ( infile.is_open( ) ) { while ( infile ) { getline( infile , line ) ; lines_read++ ; if ( lines_read == linenumber ) { std::cout << line << std::endl ; break ; } } infile.close( ) ; if ( lines_read < linenumber ) std::cout << "No " << linenumber << " lines in " << file << " !\n" ; return 0 ; } else { std::cerr << "Could not find file " << file << " !\n" ; return 1 ; } }
with open('xxx.txt') as f: for i, line in enumerate(f): if i == 6: break else: print('Not 7 lines in file') line = None
Write the same algorithm in Python as shown in this C++ implementation.
#include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <vector> bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) { const size_t n1 = str.length(); const size_t n2 = suffix.length(); if (n1 < n2) return false; return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(), [](char c1, char c2) { return std::tolower(static_cast<unsigned char>(c1)) == std::tolower(static_cast<unsigned char>(c2)); }); } bool filenameHasExtension(const std::string& filename, const std::vector<std::string>& extensions) { return std::any_of(extensions.begin(), extensions.end(), [&filename](const std::string& extension) { return endsWithIgnoreCase(filename, "." + extension); }); } void test(const std::string& filename, const std::vector<std::string>& extensions) { std::cout << std::setw(20) << std::left << filename << ": " << std::boolalpha << filenameHasExtension(filename, extensions) << '\n'; } int main() { const std::vector<std::string> extensions{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}; test("MyData.a##", extensions); test("MyData.tar.Gz", extensions); test("MyData.gzip", extensions); test("MyData.7z.backup", extensions); test("MyData...", extensions); test("MyData", extensions); test("MyData_v1.0.tar.bz2", extensions); test("MyData_v1.0.bz2", extensions); return 0; }
def isExt(fileName, extensions): return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
Write the same algorithm in Python as shown in this C++ implementation.
#include <algorithm> #include <cctype> #include <iomanip> #include <iostream> #include <string> #include <vector> bool endsWithIgnoreCase(const std::string& str, const std::string& suffix) { const size_t n1 = str.length(); const size_t n2 = suffix.length(); if (n1 < n2) return false; return std::equal(str.begin() + (n1 - n2), str.end(), suffix.begin(), [](char c1, char c2) { return std::tolower(static_cast<unsigned char>(c1)) == std::tolower(static_cast<unsigned char>(c2)); }); } bool filenameHasExtension(const std::string& filename, const std::vector<std::string>& extensions) { return std::any_of(extensions.begin(), extensions.end(), [&filename](const std::string& extension) { return endsWithIgnoreCase(filename, "." + extension); }); } void test(const std::string& filename, const std::vector<std::string>& extensions) { std::cout << std::setw(20) << std::left << filename << ": " << std::boolalpha << filenameHasExtension(filename, extensions) << '\n'; } int main() { const std::vector<std::string> extensions{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"}; test("MyData.a##", extensions); test("MyData.tar.Gz", extensions); test("MyData.gzip", extensions); test("MyData.7z.backup", extensions); test("MyData...", extensions); test("MyData", extensions); test("MyData_v1.0.tar.bz2", extensions); test("MyData_v1.0.bz2", extensions); return 0; }
def isExt(fileName, extensions): return True in map(fileName.lower().endswith, ("." + e.lower() for e in extensions))
Generate an equivalent Python version of this C++ code.
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::string operation) { bool printOperation(false); for(const Digit& number : d) { if(printOperation) std::cout << operation; else printOperation = true; std::cout << number; } std::cout << std::endl; } void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") { std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl; } int main() { std::mt19937_64 randomGenerator; std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit}; for(int trial{10}; trial; --trial) { for(Digit& digit : d) { digit = digitDistro(randomGenerator); std::cout << digit << " "; } std::cout << std::endl; std::sort(d.begin(), d.end()); if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal) printTrivialOperation(" + "); if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal) printTrivialOperation(" * "); do { if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - "); if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + "); if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + "); if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )"); if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + "); if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )"); if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )"); if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - "); if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )"); if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )"); if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - "); if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - "); if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + "); if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )"); if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + "); if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / "); if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - "); if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / "); if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )"); if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / "); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )"); if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )"); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", ""); } while(std::next_permutation(d.begin(), d.end())); } return 0; }
from __future__ import division, print_function from itertools import permutations, combinations, product, \ chain from pprint import pprint as pp from fractions import Fraction as F import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input from itertools import izip_longest as zip_longest else: from itertools import zip_longest def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def ask4(): 'get four random digits >0 from the player' digits = '' while len(digits) != 4 or not all(d in '123456789' for d in digits): digits = input('Enter the digits to solve for: ') digits = ''.join(digits.strip().split()) return list(digits) def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def solve(digits): digilen = len(digits) exprlen = 2 * digilen - 1 digiperm = sorted(set(permutations(digits))) opcomb = list(product('+-*/', repeat=digilen-1)) brackets = ( [()] + [(x,y) for x in range(0, exprlen, 2) for y in range(x+4, exprlen+2, 2) if (x,y) != (0,exprlen+1)] + [(0, 3+1, 4+2, 7+3)] ) for d in digiperm: for ops in opcomb: if '/' in ops: d2 = [('F(%s)' % i) for i in d] else: d2 = d ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue=''))) for b in brackets: exp = ex[::] for insertpoint, bracket in zip(b, '()'*(len(b)//2)): exp.insert(insertpoint, bracket) txt = ''.join(exp) try: num = eval(txt) except ZeroDivisionError: continue if num == 24: if '/' in ops: exp = [ (term if not term.startswith('F(') else term[2]) for term in exp ] ans = ' '.join(exp).rstrip() print ("Solution found:",ans) return ans print ("No solution found for:", ' '.join(digits)) return '!' def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer == '?': solve(digits) answer = '!' if answer.lower() == 'q': break if answer == '!': digits = choose4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if answer == '!!': digits = ask4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: if '/' in answer: answer = ''.join( (('F(%s)' % char) if char in '123456789' else char) for char in answer ) ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") main()
Port the following code from C++ to Python with equivalent syntax and logic.
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::string operation) { bool printOperation(false); for(const Digit& number : d) { if(printOperation) std::cout << operation; else printOperation = true; std::cout << number; } std::cout << std::endl; } void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") { std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl; } int main() { std::mt19937_64 randomGenerator; std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit}; for(int trial{10}; trial; --trial) { for(Digit& digit : d) { digit = digitDistro(randomGenerator); std::cout << digit << " "; } std::cout << std::endl; std::sort(d.begin(), d.end()); if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal) printTrivialOperation(" + "); if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal) printTrivialOperation(" * "); do { if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - "); if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + "); if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + "); if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )"); if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + "); if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )"); if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )"); if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - "); if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )"); if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )"); if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - "); if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - "); if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + "); if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )"); if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + "); if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / "); if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )"); if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - "); if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / "); if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / "); if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )"); if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / "); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )"); if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )"); if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", ""); } while(std::next_permutation(d.begin(), d.end())); } return 0; }
from __future__ import division, print_function from itertools import permutations, combinations, product, \ chain from pprint import pprint as pp from fractions import Fraction as F import random, ast, re import sys if sys.version_info[0] < 3: input = raw_input from itertools import izip_longest as zip_longest else: from itertools import zip_longest def choose4(): 'four random digits >0 as characters' return [str(random.randint(1,9)) for i in range(4)] def ask4(): 'get four random digits >0 from the player' digits = '' while len(digits) != 4 or not all(d in '123456789' for d in digits): digits = input('Enter the digits to solve for: ') digits = ''.join(digits.strip().split()) return list(digits) def welcome(digits): print (__doc__) print ("Your four digits: " + ' '.join(digits)) def check(answer, digits): allowed = set('() +-*/\t'+''.join(digits)) ok = all(ch in allowed for ch in answer) and \ all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \ and not re.search('\d\d', answer) if ok: try: ast.parse(answer) except: ok = False return ok def solve(digits): digilen = len(digits) exprlen = 2 * digilen - 1 digiperm = sorted(set(permutations(digits))) opcomb = list(product('+-*/', repeat=digilen-1)) brackets = ( [()] + [(x,y) for x in range(0, exprlen, 2) for y in range(x+4, exprlen+2, 2) if (x,y) != (0,exprlen+1)] + [(0, 3+1, 4+2, 7+3)] ) for d in digiperm: for ops in opcomb: if '/' in ops: d2 = [('F(%s)' % i) for i in d] else: d2 = d ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue=''))) for b in brackets: exp = ex[::] for insertpoint, bracket in zip(b, '()'*(len(b)//2)): exp.insert(insertpoint, bracket) txt = ''.join(exp) try: num = eval(txt) except ZeroDivisionError: continue if num == 24: if '/' in ops: exp = [ (term if not term.startswith('F(') else term[2]) for term in exp ] ans = ' '.join(exp).rstrip() print ("Solution found:",ans) return ans print ("No solution found for:", ' '.join(digits)) return '!' def main(): digits = choose4() welcome(digits) trial = 0 answer = '' chk = ans = False while not (chk and ans == 24): trial +=1 answer = input("Expression %i: " % trial) chk = check(answer, digits) if answer == '?': solve(digits) answer = '!' if answer.lower() == 'q': break if answer == '!': digits = choose4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if answer == '!!': digits = ask4() trial = 0 print ("\nNew digits:", ' '.join(digits)) continue if not chk: print ("The input '%s' was wonky!" % answer) else: if '/' in answer: answer = ''.join( (('F(%s)' % char) if char in '123456789' else char) for char in answer ) ans = eval(answer) print (" = ", ans) if ans == 24: print ("Thats right!") print ("Thank you and goodbye") main()
Convert the following code from C++ to Python, ensuring the logic remains intact.
#include <iostream> #include <chrono> #include <atomic> #include <mutex> #include <random> #include <thread> std::mutex cout_lock; class Latch { std::atomic<int> semafor; public: Latch(int limit) : semafor(limit) {} void wait() { semafor.fetch_sub(1); while(semafor.load() > 0) std::this_thread::yield(); } }; struct Worker { static void do_work(int how_long, Latch& barrier, std::string name) { std::this_thread::sleep_for(std::chrono::milliseconds(how_long)); { std::lock_guard<std::mutex> lock(cout_lock); std::cout << "Worker " << name << " finished work\n"; } barrier.wait(); { std::lock_guard<std::mutex> lock(cout_lock); std::cout << "Worker " << name << " finished assembly\n"; } } }; int main() { Latch latch(5); std::mt19937 rng(std::random_device{}()); std::uniform_int_distribution<> dist(300, 3000); std::thread threads[] { std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"), std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"}, std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"}, }; for(auto& t: threads) t.join(); std::cout << "Assembly is finished"; }
import threading import time import random def worker(workernum, barrier): sleeptime = random.random() print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum)) barrier.wait() sleeptime = random.random() print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime)) time.sleep(sleeptime) print('Exiting worker'+str(workernum)) barrier = threading.Barrier(3) w1 = threading.Thread(target=worker, args=((1,barrier))) w2 = threading.Thread(target=worker, args=((2,barrier))) w3 = threading.Thread(target=worker, args=((3,barrier))) w1.start() w2.start() w3.start()
Keep all operations the same but rewrite the snippet in Python.
#include <iomanip> #include <iostream> #include <vector> std::ostream &operator<<(std::ostream &os, const std::vector<uint8_t> &v) { auto it = v.cbegin(); auto end = v.cend(); os << "[ "; if (it != end) { os << std::setfill('0') << std::setw(2) << (uint32_t)*it; it = std::next(it); } while (it != end) { os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it; it = std::next(it); } return os << " ]"; } std::vector<uint8_t> to_seq(uint64_t x) { int i; for (i = 9; i > 0; i--) { if (x & 127ULL << i * 7) { break; } } std::vector<uint8_t> out; for (int j = 0; j <= i; j++) { out.push_back(((x >> ((i - j) * 7)) & 127) | 128); } out[i] ^= 128; return out; } uint64_t from_seq(const std::vector<uint8_t> &seq) { uint64_t r = 0; for (auto b : seq) { r = (r << 7) | (b & 127); } return r; } int main() { std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL }; for (auto x : src) { auto s = to_seq(x); std::cout << std::hex; std::cout << "seq from " << x << ' ' << s << " back: " << from_seq(s) << '\n'; std::cout << std::dec; } return 0; }
def tobits(n, _group=8, _sep='_', _pad=False): 'Express n as binary bits with separator' bits = '{0:b}'.format(n)[::-1] if _pad: bits = '{0:0{1}b}'.format(n, ((_group+len(bits)-1)//_group)*_group)[::-1] answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] answer = '0'*(len(_sep)-1) + answer else: answer = _sep.join(bits[i:i+_group] for i in range(0, len(bits), _group))[::-1] return answer def tovlq(n): return tobits(n, _group=7, _sep='1_', _pad=True) def toint(vlq): return int(''.join(vlq.split('_1')), 2) def vlqsend(vlq): for i, byte in enumerate(vlq.split('_')[::-1]): print('Sent byte {0:3}: {1:
Write the same algorithm in Python as shown in this C++ implementation.
#include <iostream> #include <string> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) using namespace std; class recorder { public: void start() { paused = rec = false; action = "IDLE"; while( true ) { cout << endl << "==" << action << "==" << endl << endl; cout << "1) Record" << endl << "2) Play" << endl << "3) Pause" << endl << "4) Stop" << endl << "5) Quit" << endl; char c; cin >> c; if( c > '0' && c < '6' ) { switch( c ) { case '1': record(); break; case '2': play(); break; case '3': pause(); break; case '4': stop(); break; case '5': stop(); return; } } } } private: void record() { if( mciExecute( "open new type waveaudio alias my_sound") ) { mciExecute( "record my_sound" ); action = "RECORDING"; rec = true; } } void play() { if( paused ) mciExecute( "play my_sound" ); else if( mciExecute( "open tmp.wav alias my_sound" ) ) mciExecute( "play my_sound" ); action = "PLAYING"; paused = false; } void pause() { if( rec ) return; mciExecute( "pause my_sound" ); paused = true; action = "PAUSED"; } void stop() { if( rec ) { mciExecute( "stop my_sound" ); mciExecute( "save my_sound tmp.wav" ); mciExecute( "close my_sound" ); action = "IDLE"; rec = false; } else { mciExecute( "stop my_sound" ); mciExecute( "close my_sound" ); action = "IDLE"; } } bool mciExecute( string cmd ) { if( mciSendString( cmd.c_str(), NULL, 0, NULL ) ) { cout << "Can't do this: " << cmd << endl; return false; } return true; } bool paused, rec; string action; }; int main( int argc, char* argv[] ) { recorder r; r.start(); return 0; }
import pyaudio chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 p = pyaudio.PyAudio() stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) data = stream.read(chunk) print [ord(i) for i in data]
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <vector> #include <openssl/sha.h> class sha256_exception : public std::exception { public: const char* what() const noexcept override { return "SHA-256 error"; } }; class sha256 { public: sha256() { reset(); } sha256(const sha256&) = delete; sha256& operator=(const sha256&) = delete; void reset() { if (SHA256_Init(&context_) == 0) throw sha256_exception(); } void update(const void* data, size_t length) { if (SHA256_Update(&context_, data, length) == 0) throw sha256_exception(); } std::vector<unsigned char> digest() { std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH); if (SHA256_Final(digest.data(), &context_) == 0) throw sha256_exception(); return digest; } private: SHA256_CTX context_; }; std::string digest_to_string(const std::vector<unsigned char>& digest) { std::ostringstream out; out << std::hex << std::setfill('0'); for (size_t i = 0; i < digest.size(); ++i) out << std::setw(2) << static_cast<int>(digest[i]); return out.str(); } std::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) { std::vector<std::vector<unsigned char>> hashes; std::vector<char> buffer(block_size); sha256 md; while (in) { in.read(buffer.data(), block_size); size_t bytes = in.gcount(); if (bytes == 0) break; md.reset(); md.update(buffer.data(), bytes); hashes.push_back(md.digest()); } if (hashes.empty()) return {}; size_t length = hashes.size(); while (length > 1) { size_t j = 0; for (size_t i = 0; i < length; i += 2, ++j) { auto& digest1 = hashes[i]; auto& digest_out = hashes[j]; if (i + 1 < length) { auto& digest2 = hashes[i + 1]; md.reset(); md.update(digest1.data(), digest1.size()); md.update(digest2.data(), digest2.size()); digest_out = md.digest(); } else { digest_out = digest1; } } length = j; } return hashes[0]; } int main(int argc, char** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " filename\n"; return EXIT_FAILURE; } std::ifstream in(argv[1], std::ios::binary); if (!in) { std::cerr << "Cannot open file " << argv[1] << ".\n"; return EXIT_FAILURE; } try { std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\n'; } catch (const std::exception& ex) { std::cerr << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
import argh import hashlib import sys @argh.arg('filename', nargs='?', default=None) def main(filename, block_size=1024*1024): if filename: fin = open(filename, 'rb') else: fin = sys.stdin stack = [] block = fin.read(block_size) while block: node = (0, hashlib.sha256(block).digest()) stack.append(node) while len(stack) >= 2 and stack[-2][0] == stack[-1][0]: a = stack[-2] b = stack[-1] l = a[0] stack[-2:] = [(l+1, hashlib.sha256(a[1] + b[1]).digest())] block = fin.read(block_size) while len(stack) > 1: a = stack[-2] b = stack[-1] al = a[0] bl = b[0] stack[-2:] = [(max(al, bl)+1, hashlib.sha256(a[1] + b[1]).digest())] print(stack[0][1].hex()) argh.dispatch_command(main)
Rewrite this program in Python while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <string> #include <cctype> void str_toupper(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::toupper); } void str_tolower(std::string &str) { std::transform(str.begin(), str.end(), str.begin(), (int(*)(int)) std::tolower); }
s = "alphaBETA" print s.upper() print s.lower() print s.swapcase() print "fOo bAR".capitalize() print "fOo bAR".title() import string print string.capwords("fOo bAR")
Generate a Python translation of this C++ snippet without changing its computational steps.
#ifndef TASK_H #define TASK_H #include <QWidget> class QLabel ; class QLineEdit ; class QVBoxLayout ; class QHBoxLayout ; class EntryWidget : public QWidget { Q_OBJECT public : EntryWidget( QWidget *parent = 0 ) ; private : QHBoxLayout *upperpart , *lowerpart ; QVBoxLayout *entryLayout ; QLineEdit *stringinput ; QLineEdit *numberinput ; QLabel *stringlabel ; QLabel *numberlabel ; } ; #endif
from javax.swing import JOptionPane def to_int(n, default=0): try: return int(n) except ValueError: return default number = to_int(JOptionPane.showInputDialog ("Enter an Integer")) println(number) a_string = JOptionPane.showInputDialog ("Enter a String") println(a_string)
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <fstream> #include <iostream> #include <vector> constexpr double sqrt3_2 = 0.86602540378444; struct point { double x; double y; }; std::vector<point> sierpinski_arrowhead_next(const std::vector<point>& points) { size_t size = points.size(); std::vector<point> output(3*(size - 1) + 1); double x0, y0, x1, y1; size_t j = 0; for (size_t i = 0; i + 1 < size; ++i, j += 3) { x0 = points[i].x; y0 = points[i].y; x1 = points[i + 1].x; y1 = points[i + 1].y; double dx = x1 - x0; output[j] = {x0, y0}; if (y0 == y1) { double d = dx * sqrt3_2/2; if (d < 0) d = -d; output[j + 1] = {x0 + dx/4, y0 - d}; output[j + 2] = {x1 - dx/4, y0 - d}; } else if (y1 < y0) { output[j + 1] = {x1, y0}; output[j + 2] = {x1 + dx/2, (y0 + y1)/2}; } else { output[j + 1] = {x0 - dx/2, (y0 + y1)/2}; output[j + 2] = {x0, y1}; } } output[j] = {x1, y1}; return output; } void write_sierpinski_arrowhead(std::ostream& out, int size, int iterations) { 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='"; const double margin = 20.0; const double side = size - 2.0 * margin; const double x = margin; const double y = 0.5 * size + 0.5 * sqrt3_2 * side; std::vector<point> points{{x, y}, {x + side, y}}; for (int i = 0; i < iterations; ++i) points = sierpinski_arrowhead_next(points); for (size_t i = 0, n = points.size(); i < n; ++i) out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n'; out << "'/>\n</svg>\n"; } int main() { std::ofstream out("sierpinski_arrowhead.svg"); if (!out) { std::cerr << "Cannot open output file\n"; return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); return EXIT_SUCCESS; }
t = { 'x': 20, 'y': 30, 'a': 60 } def setup(): size(450, 400) background(0, 0, 200) stroke(-1) sc(7, 400, -60) def sc(o, l, a, s = t, X = 'x', Y = 'y', A = 'a', HALF = .5): if o: o -= 1 l *= HALF sc(o, l, -a)[A] += a sc(o, l, a)[A] += a sc(o, l, -a) else: x, y = s[X], s[Y] s[X] += cos(radians(s[A])) * l s[Y] += sin(radians(s[A])) * l line(x, y, s[X], s[Y]) return s
Can you help me rewrite this code in Python instead of C++, keeping it the same logically?
#include <iostream> #include <fstream> #include <string> #include <vector> #include <iomanip> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> using std::cout; using std::endl; const int NumFlags = 24; int main() { std::fstream file("readings.txt"); int badCount = 0; std::string badDate; int badCountMax = 0; while(true) { std::string line; getline(file, line); if(!file.good()) break; std::vector<std::string> tokens; boost::algorithm::split(tokens, line, boost::is_space()); if(tokens.size() != NumFlags * 2 + 1) { cout << "Bad input file." << endl; return 0; } double total = 0.0; int accepted = 0; for(size_t i = 1; i < tokens.size(); i += 2) { double val = boost::lexical_cast<double>(tokens[i]); int flag = boost::lexical_cast<int>(tokens[i+1]); if(flag > 0) { total += val; ++accepted; badCount = 0; } else { ++badCount; if(badCount > badCountMax) { badCountMax = badCount; badDate = tokens[0]; } } } cout << tokens[0]; cout << " Reject: " << std::setw(2) << (NumFlags - accepted); cout << " Accept: " << std::setw(2) << accepted; cout << " Average: " << std::setprecision(5) << total / accepted << endl; } cout << endl; cout << "Maximum number of consecutive bad readings is " << badCountMax << endl; cout << "Ends on date " << badDate << endl; }
import fileinput import sys nodata = 0; nodata_max=-1; nodata_maxline=[]; tot_file = 0 num_file = 0 infiles = sys.argv[1:] for line in fileinput.input(): tot_line=0; num_line=0; field = line.split() date = field[0] data = [float(f) for f in field[1::2]] flags = [int(f) for f in field[2::2]] for datum, flag in zip(data, flags): if flag<1: nodata += 1 else: if nodata_max==nodata and nodata>0: nodata_maxline.append(date) if nodata_max<nodata and nodata>0: nodata_max=nodata nodata_maxline=[date] nodata=0; tot_line += datum num_line += 1 tot_file += tot_line num_file += num_line print "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f" % ( date, len(data) -num_line, num_line, tot_line, tot_line/num_line if (num_line>0) else 0) print "" print "File(s) = %s" % (", ".join(infiles),) print "Total = %10.3f" % (tot_file,) print "Readings = %6i" % (num_file,) print "Average = %10.3f" % (tot_file / num_file,) print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % ( nodata_max, ", ".join(nodata_maxline))
Convert this C++ block to Python, preserving its control flow and logic.
#include <string> #include <iostream> #include "Poco/MD5Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::MD5Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ; MD5Engine md5 ; DigestOutputStream outstr( md5 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = md5.digest( ) ; std::cout << myphrase << " as a MD5 digest :\n" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
>>> import hashlib >>> >>> tests = ( (b"", 'd41d8cd98f00b204e9800998ecf8427e'), (b"a", '0cc175b9c0f1b6a831c399e269772661'), (b"abc", '900150983cd24fb0d6963f7d28e17f72'), (b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'), (b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'), (b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'), (b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') ) >>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden >>>
Change the following C++ code into Python without altering its purpose.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } void classify_aliquot_sequence(integer n) { constexpr int limit = 16; integer terms[limit]; terms[0] = n; std::string classification("non-terminating"); int length = 1; for (int i = 1; i < limit; ++i) { ++length; terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1]; if (terms[i] == n) { classification = (i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable")); break; } int j = 1; for (; j < i; ++j) { if (terms[i] == terms[i - j]) break; } if (j < i) { classification = (j == 1 ? "aspiring" : "cyclic"); break; } if (terms[i] == 0) { classification = "terminating"; break; } } std::cout << n << ": " << classification << ", sequence: " << terms[0]; for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i) std::cout << ' ' << terms[i]; std::cout << '\n'; } int main() { for (integer i = 1; i <= 10; ++i) classify_aliquot_sequence(i); for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}) classify_aliquot_sequence(i); classify_aliquot_sequence(15355717786080); classify_aliquot_sequence(153557177860800); return 0; }
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length %i' % slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to %i' % new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s if __name__ == '__main__': for n in range(1, 11): print('%s: %r' % aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s: %r' % aliquot(n))
Please provide an equivalent version of this C++ code in Python.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; integer divisor_sum(integer n) { integer total = 1, power = 2; for (; n % 2 == 0; power *= 2, n /= 2) total += power; for (integer p = 3; p * p <= n; p += 2) { integer sum = 1; for (power = p; n % p == 0; power *= p, n /= p) sum += power; total *= sum; } if (n > 1) total *= n + 1; return total; } void classify_aliquot_sequence(integer n) { constexpr int limit = 16; integer terms[limit]; terms[0] = n; std::string classification("non-terminating"); int length = 1; for (int i = 1; i < limit; ++i) { ++length; terms[i] = divisor_sum(terms[i - 1]) - terms[i - 1]; if (terms[i] == n) { classification = (i == 1 ? "perfect" : (i == 2 ? "amicable" : "sociable")); break; } int j = 1; for (; j < i; ++j) { if (terms[i] == terms[i - j]) break; } if (j < i) { classification = (j == 1 ? "aspiring" : "cyclic"); break; } if (terms[i] == 0) { classification = "terminating"; break; } } std::cout << n << ": " << classification << ", sequence: " << terms[0]; for (int i = 1; i < length && terms[i] != terms[i - 1]; ++i) std::cout << ' ' << terms[i]; std::cout << '\n'; } int main() { for (integer i = 1; i <= 10; ++i) classify_aliquot_sequence(i); for (integer i : {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}) classify_aliquot_sequence(i); classify_aliquot_sequence(15355717786080); classify_aliquot_sequence(153557177860800); return 0; }
from proper_divisors import proper_divs from functools import lru_cache @lru_cache() def pdsum(n): return sum(proper_divs(n)) def aliquot(n, maxlen=16, maxterm=2**47): if n == 0: return 'terminating', [0] s, slen, new = [n], 1, n while slen <= maxlen and new < maxterm: new = pdsum(s[-1]) if new in s: if s[0] == new: if slen == 1: return 'perfect', s elif slen == 2: return 'amicable', s else: return 'sociable of length %i' % slen, s elif s[-1] == new: return 'aspiring', s else: return 'cyclic back to %i' % new, s elif new == 0: return 'terminating', s + [0] else: s.append(new) slen += 1 else: return 'non-terminating', s if __name__ == '__main__': for n in range(1, 11): print('%s: %r' % aliquot(n)) print() for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]: print('%s: %r' % aliquot(n))
Produce a language-to-language conversion: from C++ to Python, same semantics.
#include <string> #include <iostream> #include <boost/date_time/local_time/local_time.hpp> #include <sstream> #include <boost/date_time/gregorian/gregorian.hpp> #include <vector> #include <boost/algorithm/string.hpp> #include <cstdlib> #include <locale> int main( ) { std::string datestring ("March 7 2009 7:30pm EST" ) ; std::vector<std::string> elements ; boost::split( elements , datestring , boost::is_any_of( " " ) ) ; std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " + elements[ 2 ] ; std::string timepart = elements[ 3 ] ; std::string timezone = elements[ 4 ] ; const char meridians[ ] = { 'a' , 'p' } ; std::string::size_type found = timepart.find_first_of( meridians, 0 ) ; std::string twelve_hour ( timepart.substr( found , 1 ) ) ; timepart = timepart.substr( 0 , found ) ; elements.clear( ) ; boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ; long hour = std::atol( (elements.begin( ))->c_str( ) ) ; if ( twelve_hour == "p" ) hour += 12 ; long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; boost::local_time::tz_database tz_db ; tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ; boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ; boost::gregorian::date_input_facet *f = new boost::gregorian::date_input_facet( "%B %d %Y" ) ; std::stringstream ss ; ss << datepart ; ss.imbue( std::locale( std::locale::classic( ) , f ) ) ; boost::gregorian::date d ; ss >> d ; boost::posix_time::time_duration td ( hour , minute , 0 ) ; boost::local_time::local_date_time lt ( d , td , dyc , boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ; std::cout << "local time: " << lt << '\n' ; ss.str( "" ) ; ss << lt ; boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ; boost::local_time::local_date_time ltlater = lt + td2 ; boost::gregorian::date_facet *f2 = new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ; std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ; std::cout << "12 hours after " << ss.str( ) << " it is " << ltlater << " !\n" ; boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ; std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ; std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ; return 0 ; }
import datetime def mt(): datime1="March 7 2009 7:30pm EST" formatting = "%B %d %Y %I:%M%p " datime2 = datime1[:-3] tdelta = datetime.timedelta(hours=12) s3 = datetime.datetime.strptime(datime2, formatting) datime2 = s3+tdelta print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:] mt()
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <string> #include <iostream> #include <boost/date_time/local_time/local_time.hpp> #include <sstream> #include <boost/date_time/gregorian/gregorian.hpp> #include <vector> #include <boost/algorithm/string.hpp> #include <cstdlib> #include <locale> int main( ) { std::string datestring ("March 7 2009 7:30pm EST" ) ; std::vector<std::string> elements ; boost::split( elements , datestring , boost::is_any_of( " " ) ) ; std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " + elements[ 2 ] ; std::string timepart = elements[ 3 ] ; std::string timezone = elements[ 4 ] ; const char meridians[ ] = { 'a' , 'p' } ; std::string::size_type found = timepart.find_first_of( meridians, 0 ) ; std::string twelve_hour ( timepart.substr( found , 1 ) ) ; timepart = timepart.substr( 0 , found ) ; elements.clear( ) ; boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ; long hour = std::atol( (elements.begin( ))->c_str( ) ) ; if ( twelve_hour == "p" ) hour += 12 ; long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; boost::local_time::tz_database tz_db ; tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ; boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ; boost::gregorian::date_input_facet *f = new boost::gregorian::date_input_facet( "%B %d %Y" ) ; std::stringstream ss ; ss << datepart ; ss.imbue( std::locale( std::locale::classic( ) , f ) ) ; boost::gregorian::date d ; ss >> d ; boost::posix_time::time_duration td ( hour , minute , 0 ) ; boost::local_time::local_date_time lt ( d , td , dyc , boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ; std::cout << "local time: " << lt << '\n' ; ss.str( "" ) ; ss << lt ; boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ; boost::local_time::local_date_time ltlater = lt + td2 ; boost::gregorian::date_facet *f2 = new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ; std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ; std::cout << "12 hours after " << ss.str( ) << " it is " << ltlater << " !\n" ; boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ; std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ; std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ; return 0 ; }
import datetime def mt(): datime1="March 7 2009 7:30pm EST" formatting = "%B %d %Y %I:%M%p " datime2 = datime1[:-3] tdelta = datetime.timedelta(hours=12) s3 = datetime.datetime.strptime(datime2, formatting) datime2 = s3+tdelta print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:] mt()
Generate a Python translation of this C++ snippet without changing its computational steps.
#include <chrono> #include <iostream> #include <thread> #include <vector> int main(int argc, char* argv[]) { std::vector<std::thread> threads; for (int i = 1; i < argc; ++i) { threads.emplace_back([i, &argv]() { int arg = std::stoi(argv[i]); std::this_thread::sleep_for(std::chrono::seconds(arg)); std::cout << argv[i] << std::endl; }); } for (auto& thread : threads) { thread.join(); } }
from time import sleep from threading import Timer def sleepsort(values): sleepsort.result = [] def add1(x): sleepsort.result.append(x) mx = values[0] for v in values: if mx < v: mx = v Timer(v, add1, [v]).start() sleep(mx+1) return sleepsort.result if __name__ == '__main__': x = [3,2,4,7,3,6,9,1] if sleepsort(x) == sorted(x): print('sleep sort worked for:',x) else: print('sleep sort FAILED for:',x)
Translate this program into Python but keep the logic exactly as in C++.
#include<cstdlib> #include<ctime> #include<iostream> using namespace std; int main() { int arr[10][10]; srand(time(NULL)); for(auto& row: arr) for(auto& col: row) col = rand() % 20 + 1; ([&](){ for(auto& row : arr) for(auto& col: row) { cout << col << endl; if(col == 20)return; } })(); return 0; }
from random import randint def do_scan(mat): for row in mat: for item in row: print item, if item == 20: print return print print mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)] do_scan(mat)
Produce a functionally identical Python code for the snippet given in C++.
#include <cmath> #include <iostream> #include <numeric> #include <tuple> #include <vector> using namespace std; auto CountTriplets(unsigned long long maxPerimeter) { unsigned long long totalCount = 0; unsigned long long primitveCount = 0; auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1; for(unsigned long long m = 2; m < max_M; ++m) { for(unsigned long long n = 1 + m % 2; n < m; n+=2) { if(gcd(m,n) != 1) { continue; } auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto perimeter = a + b + c; if(perimeter <= maxPerimeter) { primitveCount++; totalCount+= maxPerimeter / perimeter; } } } return tuple(totalCount, primitveCount); } int main() { vector<unsigned long long> inputs{100, 1000, 10'000, 100'000, 1000'000, 10'000'000, 100'000'000, 1000'000'000, 10'000'000'000}; for(auto maxPerimeter : inputs) { auto [total, primitive] = CountTriplets(maxPerimeter); cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ; } }
from fractions import gcd def pt1(maxperimeter=100): trips = [] for a in range(1, maxperimeter): aa = a*a for b in range(a, maxperimeter-a+1): bb = b*b for c in range(b, maxperimeter-b-a+1): cc = c*c if a+b+c > maxperimeter or cc > aa + bb: break if aa + bb == cc: trips.append((a,b,c, gcd(a, b) == 1)) return trips def pytrip(trip=(3,4,5),perim=100, prim=1): a0, b0, c0 = a, b, c = sorted(trip) t, firstprim = set(), prim>0 while a + b + c <= perim: t.add((a, b, c, firstprim>0)) a, b, c, firstprim = a+a0, b+b0, c+c0, False t2 = set() for a, b, c, firstprim in t: a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7 if a5 - b5 + c7 <= perim: t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim) if a5 + b5 + c7 <= perim: t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim) if -a5 + b5 + c7 <= perim: t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim) return t | t2 def pt2(maxperimeter=100): trips = pytrip((3,4,5), maxperimeter, 1) return trips def printit(maxperimeter=100, pt=pt1): trips = pt(maxperimeter) print(" Up to a perimeter of %i there are %i triples, of which %i are primitive" % (maxperimeter, len(trips), len([prim for a,b,c,prim in trips if prim]))) for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)): print(algo.__doc__) for maxperimeter in range(mn, mx+1, mn): printit(maxperimeter, algo)
Preserve the algorithm and functionality while converting the code from C++ to Python.
#include <cmath> #include <iostream> #include <numeric> #include <tuple> #include <vector> using namespace std; auto CountTriplets(unsigned long long maxPerimeter) { unsigned long long totalCount = 0; unsigned long long primitveCount = 0; auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1; for(unsigned long long m = 2; m < max_M; ++m) { for(unsigned long long n = 1 + m % 2; n < m; n+=2) { if(gcd(m,n) != 1) { continue; } auto a = m * m - n * n; auto b = 2 * m * n; auto c = m * m + n * n; auto perimeter = a + b + c; if(perimeter <= maxPerimeter) { primitveCount++; totalCount+= maxPerimeter / perimeter; } } } return tuple(totalCount, primitveCount); } int main() { vector<unsigned long long> inputs{100, 1000, 10'000, 100'000, 1000'000, 10'000'000, 100'000'000, 1000'000'000, 10'000'000'000}; for(auto maxPerimeter : inputs) { auto [total, primitive] = CountTriplets(maxPerimeter); cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ; } }
from fractions import gcd def pt1(maxperimeter=100): trips = [] for a in range(1, maxperimeter): aa = a*a for b in range(a, maxperimeter-a+1): bb = b*b for c in range(b, maxperimeter-b-a+1): cc = c*c if a+b+c > maxperimeter or cc > aa + bb: break if aa + bb == cc: trips.append((a,b,c, gcd(a, b) == 1)) return trips def pytrip(trip=(3,4,5),perim=100, prim=1): a0, b0, c0 = a, b, c = sorted(trip) t, firstprim = set(), prim>0 while a + b + c <= perim: t.add((a, b, c, firstprim>0)) a, b, c, firstprim = a+a0, b+b0, c+c0, False t2 = set() for a, b, c, firstprim in t: a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7 if a5 - b5 + c7 <= perim: t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim) if a5 + b5 + c7 <= perim: t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim) if -a5 + b5 + c7 <= perim: t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim) return t | t2 def pt2(maxperimeter=100): trips = pytrip((3,4,5), maxperimeter, 1) return trips def printit(maxperimeter=100, pt=pt1): trips = pt(maxperimeter) print(" Up to a perimeter of %i there are %i triples, of which %i are primitive" % (maxperimeter, len(trips), len([prim for a,b,c,prim in trips if prim]))) for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)): print(algo.__doc__) for maxperimeter in range(mn, mx+1, mn): printit(maxperimeter, algo)
Translate this program into Python but keep the logic exactly as in C++.
#include <set> #include <iostream> using namespace std; int main() { typedef set<int> TySet; int data[] = {1, 2, 3, 2, 3, 4}; TySet unique_set(data, data + 6); cout << "Set items:" << endl; for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++) cout << *iter << " "; cout << endl; }
items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'] unique = list(set(items))
Produce a functionally identical Python code for the snippet given in C++.
#include <iostream> #include <sstream> #include <string> std::string lookandsay(const std::string& s) { std::ostringstream r; for (std::size_t i = 0; i != s.length();) { auto new_i = s.find_first_not_of(s[i], i + 1); if (new_i == std::string::npos) new_i = s.length(); r << new_i - i << s[i]; i = new_i; } return r.str(); } int main() { std::string laf = "1"; std::cout << laf << '\n'; for (int i = 0; i < 10; ++i) { laf = lookandsay(laf); std::cout << laf << '\n'; } }
def lookandsay(number): result = "" repeat = number[0] number = number[1:]+" " times = 1 for actual in number: if actual != repeat: result += str(times)+repeat times = 1 repeat = actual else: times += 1 return result num = "1" for i in range(10): print num num = lookandsay(num)
Port the provided C++ code into Python while preserving the original functionality.
#include <cassert> #include <iomanip> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) continue; for (int j = i; j <= max; j += i) totient_[j] -= totient_[j] / i; } } int totient(int n) const { assert (n >= 1 && n < totient_.size()); return totient_[n]; } bool is_prime(int n) const { return totient(n) == n - 1; } private: std::vector<int> totient_; }; int count_primes(const totient_calculator& tc, int min, int max) { int count = 0; for (int i = min; i <= max; ++i) { if (tc.is_prime(i)) ++count; } return count; } int main() { const int max = 10000000; totient_calculator tc(max); std::cout << " n totient prime?\n"; for (int i = 1; i <= 25; ++i) { std::cout << std::setw(2) << i << std::setw(9) << tc.totient(i) << std::setw(8) << (tc.is_prime(i) ? "yes" : "no") << '\n'; } for (int n = 100; n <= max; n *= 10) { std::cout << "Count of primes up to " << n << ": " << count_primes(tc, 1, n) << '\n'; } return 0; }
from math import gcd def φ(n): return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1) if __name__ == '__main__': def is_prime(n): return φ(n) == n - 1 for n in range(1, 26): print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}") count = 0 for n in range(1, 10_000 + 1): count += is_prime(n) if n in {100, 1000, 10_000}: print(f"Primes up to {n}: {count}")
Write a version of this C++ function in Python with identical behavior.
template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse; template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType> { typedef ThenType type; }; template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType> { typedef ElseType type; }; ifthenelse<INT_MAX == 32767, long int, int> ::type myvar;
if x == 0: foo() elif x == 1: bar() elif x == 2: baz() else: qux() match x: 0 => foo() 1 => bar() 2 => baz() _ => qux() (a) ? b : c
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <iostream> #include <sstream> #include <iterator> #include <vector> #include <cmath> using namespace std; class fractran { public: void run( std::string p, int s, int l ) { start = s; limit = l; istringstream iss( p ); vector<string> tmp; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) ); string item; vector< pair<float, float> > v; pair<float, float> a; for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ ) { string::size_type pos = ( *i ).find( '/', 0 ); if( pos != std::string::npos ) { a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) ); v.push_back( a ); } } exec( &v ); } private: void exec( vector< pair<float, float> >* v ) { int cnt = 0; while( cnt < limit ) { cout << cnt << " : " << start << "\n"; cnt++; vector< pair<float, float> >::iterator it = v->begin(); bool found = false; float r; while( it != v->end() ) { r = start * ( ( *it ).first / ( *it ).second ); if( r == floor( r ) ) { found = true; break; } ++it; } if( found ) start = ( int )r; else break; } } int start, limit; }; int main( int argc, char* argv[] ) { fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 ); cin.get(); return 0; }
from fractions import Fraction def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,' '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,' '13 / 11, 15 / 14, 15 / 2, 55 / 1'): flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')] n = Fraction(n) while True: yield n.numerator for f in flist: if (n * f).denominator == 1: break else: break n *= f if __name__ == '__main__': n, m = 2, 15 print('First %i members of fractran(%i):\n ' % (m, n) + ', '.join(str(f) for f,i in zip(fractran(n), range(m))))
Keep all operations the same but rewrite the snippet in Python.
#include <iostream> #include <sstream> #include <iterator> #include <vector> #include <cmath> using namespace std; class fractran { public: void run( std::string p, int s, int l ) { start = s; limit = l; istringstream iss( p ); vector<string> tmp; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( tmp ) ); string item; vector< pair<float, float> > v; pair<float, float> a; for( vector<string>::iterator i = tmp.begin(); i != tmp.end(); i++ ) { string::size_type pos = ( *i ).find( '/', 0 ); if( pos != std::string::npos ) { a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) ); v.push_back( a ); } } exec( &v ); } private: void exec( vector< pair<float, float> >* v ) { int cnt = 0; while( cnt < limit ) { cout << cnt << " : " << start << "\n"; cnt++; vector< pair<float, float> >::iterator it = v->begin(); bool found = false; float r; while( it != v->end() ) { r = start * ( ( *it ).first / ( *it ).second ); if( r == floor( r ) ) { found = true; break; } ++it; } if( found ) start = ( int )r; else break; } } int start, limit; }; int main( int argc, char* argv[] ) { fractran f; f.run( "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 15 ); cin.get(); return 0; }
from fractions import Fraction def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,' '77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,' '13 / 11, 15 / 14, 15 / 2, 55 / 1'): flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')] n = Fraction(n) while True: yield n.numerator for f in flist: if (n * f).denominator == 1: break else: break n *= f if __name__ == '__main__': n, m = 2, 15 print('First %i members of fractran(%i):\n ' % (m, n) + ', '.join(str(f) for f,i in zip(fractran(n), range(m))))
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <iostream> #include <time.h> using namespace std; class stooge { public: void sort( int* arr, int start, int end ) { if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] ); int n = end - start; if( n > 2 ) { n /= 3; sort( arr, start, end - n ); sort( arr, start + n, end ); sort( arr, start, end - n ); } } }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80; cout << "before:\n"; for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20; cout << a[x] << " "; } s.sort( a, 0, m ); cout << "\n\nafter:\n"; for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n"; return system( "pause" ); }
>>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] >>> def stoogesort(L, i=0, j=None): if j is None: j = len(L) - 1 if L[j] < L[i]: L[i], L[j] = L[j], L[i] if j - i > 1: t = (j - i + 1) // 3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L >>> stoogesort(data) [-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10]
Translate the given C++ code snippet into Python without altering its behavior.
#include "stdafx.h" #include <windows.h> #include <stdlib.h> const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, sizeof( bi ) ); bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; HDC dc = GetDC( GetConsoleWindow() ); bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); if( !bmp ) return false; hdc = CreateCompatibleDC( dc ); SelectObject( hdc, bmp ); ReleaseDC( GetConsoleWindow(), dc ); width = w; height = h; return true; } void clear( BYTE clr = 0 ) { memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { if( brush ) DeleteObject( brush ); brush = CreateSolidBrush( bClr ); SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { clr = c; createPen(); } void setPenWidth( int w ) { wid = w; createPen(); } HDC getDC() const { return hdc; } int getWidth() const { return width; } int getHeight() const { return height; } private: void createPen() { if( pen ) DeleteObject( pen ); pen = CreatePen( PS_SOLID, wid, clr ); SelectObject( hdc, pen ); } HBITMAP bmp; HDC hdc; HPEN pen; HBRUSH brush; void *pBits; int width, height, wid; DWORD clr; }; class point { public: int x; float y; void set( int a, float b ) { x = a; y = b; } }; typedef struct { point position, offset; bool alive, start; }ball; class galton { public : galton() { bmp.create( BMP_WID, BMP_HEI ); initialize(); } void setHWND( HWND hwnd ) { _hwnd = hwnd; } void simulate() { draw(); update(); Sleep( 1 ); } private: void draw() { bmp.clear(); bmp.setPenColor( RGB( 0, 255, 0 ) ); bmp.setBrushColor( RGB( 0, 255, 0 ) ); int xx, yy; for( int y = 3; y < 14; y++ ) { yy = 10 * y; for( int x = 0; x < 41; x++ ) { xx = 10 * x; if( pins[y][x] ) Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 ); } } bmp.setPenColor( RGB( 255, 0, 0 ) ); bmp.setBrushColor( RGB( 255, 0, 0 ) ); ball* b; for( int x = 0; x < MAX_BALLS; x++ ) { b = &balls[x]; if( b->alive ) Rectangle( bmp.getDC(), static_cast<int>( b->position.x - 3 ), static_cast<int>( b->position.y - 3 ), static_cast<int>( b->position.x + 3 ), static_cast<int>( b->position.y + 3 ) ); } for( int x = 0; x < 70; x++ ) { if( cols[x] > 0 ) { xx = 10 * x; Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] ); } } HDC dc = GetDC( _hwnd ); BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY ); ReleaseDC( _hwnd, dc ); } void update() { ball* b; for( int x = 0; x < MAX_BALLS; x++ ) { b = &balls[x]; if( b->alive ) { b->position.x += b->offset.x; b->position.y += b->offset.y; if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) { b->start = true; balls[x + 1].alive = true; } int c = ( int )b->position.x, d = ( int )b->position.y + 6; if( d > 10 || d < 41 ) { if( pins[d / 10][c / 10] ) { if( rand() % 30 < 15 ) b->position.x -= 10; else b->position.x += 10; } } if( b->position.y > 160 ) { b->alive = false; cols[c / 10] += 1; } } } } void initialize() { for( int x = 0; x < MAX_BALLS; x++ ) { balls[x].position.set( 200, -10 ); balls[x].offset.set( 0, 0.5f ); balls[x].alive = balls[x].start = false; } balls[0].alive = true; for( int x = 0; x < 70; x++ ) cols[x] = 0; for( int y = 0; y < 70; y++ ) for( int x = 0; x < 41; x++ ) pins[x][y] = false; int p; for( int y = 0; y < 11; y++ ) { p = ( 41 / 2 ) - y; for( int z = 0; z < y + 1; z++ ) { pins[3 + y][p] = true; p += 2; } } } myBitmap bmp; HWND _hwnd; bool pins[70][40]; ball balls[MAX_BALLS]; int cols[70]; }; class wnd { public: int wnd::Run( HINSTANCE hInst ) { _hInst = hInst; _hwnd = InitAll(); _gtn.setHWND( _hwnd ); ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else _gtn.simulate(); } return UnregisterClass( "_GALTON_", _hInst ); } private: static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); break; default: return static_cast<int>( DefWindowProc( hWnd, msg, wParam, lParam ) ); } return 0; } HWND InitAll() { WNDCLASSEX wcex; ZeroMemory( &wcex, sizeof( wcex ) ); wcex.cbSize = sizeof( WNDCLASSEX ); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = ( WNDPROC )WndProc; wcex.hInstance = _hInst; wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); wcex.lpszClassName = "_GALTON_"; RegisterClassEx( &wcex ); RECT rc; SetRect( &rc, 0, 0, BMP_WID, BMP_HEI ); AdjustWindowRect( &rc, WS_CAPTION, FALSE ); return CreateWindow( "_GALTON_", ".: Galton Box -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL ); } HINSTANCE _hInst; HWND _hwnd; galton _gtn; }; int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { srand( GetTickCount() ); wnd myWnd; return myWnd.Run( hInstance ); }
import sys, os import random import time def print_there(x, y, text): sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text)) sys.stdout.flush() class Ball(): def __init__(self): self.x = 0 self.y = 0 def update(self): self.x += random.randint(0,1) self.y += 1 def fall(self): self.y +=1 class Board(): def __init__(self, width, well_depth, N): self.balls = [] self.fallen = [0] * (width + 1) self.width = width self.well_depth = well_depth self.N = N self.shift = 4 def update(self): for ball in self.balls: if ball.y < self.width: ball.update() elif ball.y < self.width + self.well_depth - self.fallen[ball.x]: ball.fall() elif ball.y == self.width + self.well_depth - self.fallen[ball.x]: self.fallen[ball.x] += 1 else: pass def balls_on_board(self): return len(self.balls) - sum(self.fallen) def add_ball(self): if(len(self.balls) <= self.N): self.balls.append(Ball()) def print_board(self): for y in range(self.width + 1): for x in range(y): print_there( y + 1 ,self.width - y + 2*x + self.shift + 1, " def print_ball(self, ball): if ball.y <= self.width: x = self.width - ball.y + 2*ball.x + self.shift else: x = 2*ball.x + self.shift y = ball.y + 1 print_there(y, x, "*") def print_all(self): print(chr(27) + "[2J") self.print_board(); for ball in self.balls: self.print_ball(ball) def main(): board = Board(width = 15, well_depth = 5, N = 10) board.add_ball() while(board.balls_on_board() > 0): board.print_all() time.sleep(0.25) board.update() board.print_all() time.sleep(0.25) board.update() board.add_ball() if __name__=="__main__": main()
Keep all operations the same but rewrite the snippet in Python.
#include <iostream> int circlesort(int* arr, int lo, int hi, int swaps) { if(lo == hi) { return swaps; } int high = hi; int low = lo; int mid = (high - low) / 2; while(lo < hi) { if(arr[lo] > arr[hi]) { int temp = arr[lo]; arr[lo] = arr[hi]; arr[hi] = temp; swaps++; } lo++; hi--; } if(lo == hi) { if(arr[lo] > arr[hi+1]) { int temp = arr[lo]; arr[lo] = arr[hi+1]; arr[hi+1] = temp; swaps++; } } swaps = circlesort(arr, low, low+mid, swaps); swaps = circlesort(arr, low+mid+1, high, swaps); return swaps; } void circlesortDriver(int* arr, int n) { do { for(int i = 0; i < n; i++) { std::cout << arr[i] << ' '; } std::cout << std::endl; } while(circlesort(arr, 0, n-1, 0)); } int main() { int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 }; circlesortDriver(arr, sizeof(arr)/sizeof(int)); return 0; }
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps': n = R-L if n < 2: return 0 swaps = 0 m = n//2 for i in range(m): if A[R-(i+1)] < A[L+i]: (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],) swaps += 1 if (n & 1) and (A[L+m] < A[L+m-1]): (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],) swaps += 1 return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R) def circle_sort(L:list)->'sort A in place, returning the number of swaps': swaps = 0 s = 1 while s: s = circle_sort_backend(L, 0, len(L)) swaps += s return swaps if __name__ == '__main__': from random import shuffle for i in range(309): L = list(range(i)) M = L[:] shuffle(L) N = L[:] circle_sort(L) if L != M: print(len(L)) print(N) print(L)
Write the same code in Python as shown below in C++.
#include <cassert> #include <vector> #include <QImage> template <typename scalar_type> class matrix { public: matrix(size_t rows, size_t columns) : rows_(rows), columns_(columns), elements_(rows * columns) {} matrix(size_t rows, size_t columns, const std::initializer_list<std::initializer_list<scalar_type>>& values) : rows_(rows), columns_(columns), elements_(rows * columns) { assert(values.size() <= rows_); size_t i = 0; for (const auto& row : values) { assert(row.size() <= columns_); std::copy(begin(row), end(row), &elements_[i]); i += columns_; } } size_t rows() const { return rows_; } size_t columns() const { return columns_; } const scalar_type& operator()(size_t row, size_t column) const { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } scalar_type& operator()(size_t row, size_t column) { assert(row < rows_); assert(column < columns_); return elements_[row * columns_ + column]; } private: size_t rows_; size_t columns_; std::vector<scalar_type> elements_; }; template <typename scalar_type> matrix<scalar_type> kronecker_product(const matrix<scalar_type>& a, const matrix<scalar_type>& b) { size_t arows = a.rows(); size_t acolumns = a.columns(); size_t brows = b.rows(); size_t bcolumns = b.columns(); matrix<scalar_type> c(arows * brows, acolumns * bcolumns); for (size_t i = 0; i < arows; ++i) for (size_t j = 0; j < acolumns; ++j) for (size_t k = 0; k < brows; ++k) for (size_t l = 0; l < bcolumns; ++l) c(i*brows + k, j*bcolumns + l) = a(i, j) * b(k, l); return c; } bool kronecker_fractal(const char* fileName, const matrix<unsigned char>& m, int order) { matrix<unsigned char> result = m; for (int i = 0; i < order; ++i) result = kronecker_product(result, m); size_t height = result.rows(); size_t width = result.columns(); size_t bytesPerLine = 4 * ((width + 3)/4); std::vector<uchar> imageData(bytesPerLine * height); for (size_t i = 0; i < height; ++i) for (size_t j = 0; j < width; ++j) imageData[i * bytesPerLine + j] = result(i, j); QImage image(&imageData[0], width, height, bytesPerLine, QImage::Format_Indexed8); QVector<QRgb> colours(2); colours[0] = qRgb(0, 0, 0); colours[1] = qRgb(255, 255, 255); image.setColorTable(colours); return image.save(fileName); } int main() { matrix<unsigned char> matrix1(3, 3, {{0,1,0}, {1,1,1}, {0,1,0}}); matrix<unsigned char> matrix2(3, 3, {{1,1,1}, {1,0,1}, {1,1,1}}); matrix<unsigned char> matrix3(2, 2, {{1,1}, {0,1}}); kronecker_fractal("vicsek.png", matrix1, 5); kronecker_fractal("sierpinski_carpet.png", matrix2, 5); kronecker_fractal("sierpinski_triangle.png", matrix3, 8); return 0; }
import os from PIL import Image def imgsave(path, arr): w, h = len(arr), len(arr[0]) img = Image.new('1', (w, h)) for x in range(w): for y in range(h): img.putpixel((x, y), arr[x][y]) img.save(path) def get_shape(mat): return len(mat), len(mat[0]) def kron(matrix1, matrix2): final_list = [] count = len(matrix2) for elem1 in matrix1: for i in range(count): sub_list = [] for num1 in elem1: for num2 in matrix2[i]: sub_list.append(num1 * num2) final_list.append(sub_list) return final_list def kronpow(mat): matrix = mat while True: yield matrix matrix = kron(mat, matrix) def fractal(name, mat, order=6): path = os.path.join('fractals', name) os.makedirs(path, exist_ok=True) fgen = kronpow(mat) print(name) for i in range(order): p = os.path.join(path, f'{i}.jpg') print('Calculating n =', i, end='\t', flush=True) mat = next(fgen) imgsave(p, mat) x, y = get_shape(mat) print('Saved as', x, 'x', y, 'image', p) test1 = [ [0, 1, 0], [1, 1, 1], [0, 1, 0] ] test2 = [ [1, 1, 1], [1, 0, 1], [1, 1, 1] ] test3 = [ [1, 0, 1], [0, 1, 0], [1, 0, 1] ] fractal('test1', test1) fractal('test2', test2) fractal('test3', test3)
Write a version of this C++ function in Python with identical behavior.
#include "stdafx.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string/case_conv.hpp> using namespace std; using namespace boost; typedef boost::tokenizer<boost::char_separator<char> > Tokenizer; static const char_separator<char> sep(" ","#;,"); struct configs{ string fullname; string favoritefruit; bool needspelling; bool seedsremoved; vector<string> otherfamily; } conf; void parseLine(const string &line, configs &conf) { if (line[0] == '#' || line.empty()) return; Tokenizer tokenizer(line, sep); vector<string> tokens; for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++) tokens.push_back(*iter); if (tokens[0] == ";"){ algorithm::to_lower(tokens[1]); if (tokens[1] == "needspeeling") conf.needspelling = false; if (tokens[1] == "seedsremoved") conf.seedsremoved = false; } algorithm::to_lower(tokens[0]); if (tokens[0] == "needspeeling") conf.needspelling = true; if (tokens[0] == "seedsremoved") conf.seedsremoved = true; if (tokens[0] == "fullname"){ for (unsigned int i=1; i<tokens.size(); i++) conf.fullname += tokens[i] + " "; conf.fullname.erase(conf.fullname.size() -1, 1); } if (tokens[0] == "favouritefruit") for (unsigned int i=1; i<tokens.size(); i++) conf.favoritefruit += tokens[i]; if (tokens[0] == "otherfamily"){ unsigned int i=1; string tmp; while (i<=tokens.size()){ if ( i == tokens.size() || tokens[i] ==","){ tmp.erase(tmp.size()-1, 1); conf.otherfamily.push_back(tmp); tmp = ""; i++; } else{ tmp += tokens[i]; tmp += " "; i++; } } } } int _tmain(int argc, TCHAR* argv[]) { if (argc != 2) { wstring tmp = argv[0]; wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl; return -1; } ifstream file (argv[1]); if (file.is_open()) while(file.good()) { char line[255]; file.getline(line, 255); string linestring(line); parseLine(linestring, conf); } else { cout << "Unable to open the file" << endl; return -2; } cout << "Fullname= " << conf.fullname << endl; cout << "Favorite Fruit= " << conf.favoritefruit << endl; cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl; cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl; string otherFamily; for (unsigned int i = 0; i < conf.otherfamily.size(); i++) otherFamily += conf.otherfamily[i] + ", "; otherFamily.erase(otherFamily.size()-2, 2); cout << "Other Family= " << otherFamily << endl; return 0; }
def readconf(fn): ret = {} with file(fn) as fp: for line in fp: line = line.strip() if not line or line.startswith(' boolval = True if line.startswith(';'): line = line.lstrip(';') if len(line.split()) != 1: continue boolval = False bits = line.split(None, 1) if len(bits) == 1: k = bits[0] v = boolval else: k, v = bits ret[k.lower()] = v return ret if __name__ == '__main__': import sys conf = readconf(sys.argv[1]) for k, v in sorted(conf.items()): print k, '=', v
Rewrite the snippet below in Python so it works the same as the original C++ code.
#include <algorithm> #include <string> #include <cctype> struct icompare_char { bool operator()(char c1, char c2) { return std::toupper(c1) < std::toupper(c2); } }; struct compare { bool operator()(std::string const& s1, std::string const& s2) { if (s1.length() > s2.length()) return true; if (s1.length() < s2.length()) return false; return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), icompare_char()); } }; int main() { std::string strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; std::sort(strings, strings+8, compare()); return 0; }
strings = "here are Some sample strings to be sorted".split() def mykey(x): return -len(x), x.upper() print sorted(strings, key=mykey)