Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in C++ while keeping its functionality equivalent to the Go version.
package main import "fmt" func main() { fmt.Println("Hello world!") }
#include <iostream> int main () { std::cout << "Hello world!" << std::endl; }
Translate the given Go code snippet into C++ without altering its behavior.
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } } return c } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func printHelper(cat string, le, lim, max int) (int, int, string) { cle, clim := commatize(le), commatize(lim) if cat != "unsexy primes" { cat = "sexy prime " + cat } fmt.Printf("Number of %s less than %s = %s\n", cat, clim, cle) last := max if le < last { last = le } verb := "are" if last == 1 { verb = "is" } return le, last, verb } func main() { lim := 1000035 sv := sieve(lim - 1) var pairs [][2]int var trips [][3]int var quads [][4]int var quins [][5]int var unsexy = []int{2, 3} for i := 3; i < lim; i += 2 { if i > 5 && i < lim-6 && !sv[i] && sv[i-6] && sv[i+6] { unsexy = append(unsexy, i) continue } if i < lim-6 && !sv[i] && !sv[i+6] { pair := [2]int{i, i + 6} pairs = append(pairs, pair) } else { continue } if i < lim-12 && !sv[i+12] { trip := [3]int{i, i + 6, i + 12} trips = append(trips, trip) } else { continue } if i < lim-18 && !sv[i+18] { quad := [4]int{i, i + 6, i + 12, i + 18} quads = append(quads, quad) } else { continue } if i < lim-24 && !sv[i+24] { quin := [5]int{i, i + 6, i + 12, i + 18, i + 24} quins = append(quins, quin) } } le, n, verb := printHelper("pairs", len(pairs), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, pairs[le-n:]) le, n, verb = printHelper("triplets", len(trips), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, trips[le-n:]) le, n, verb = printHelper("quadruplets", len(quads), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quads[le-n:]) le, n, verb = printHelper("quintuplets", len(quins), lim, 5) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, quins[le-n:]) le, n, verb = printHelper("unsexy primes", len(unsexy), lim, 10) fmt.Printf("The last %d %s:\n %v\n\n", n, verb, unsexy[le-n:]) }
#include <array> #include <iostream> #include <vector> #include <boost/circular_buffer.hpp> #include "prime_sieve.hpp" int main() { using std::cout; using std::vector; using boost::circular_buffer; using group_buffer = circular_buffer<vector<int>>; const int max = 1000035; const int max_group_size = 5; const int diff = 6; const int array_size = max + diff; const int max_groups = 5; const int max_unsexy = 10; prime_sieve sieve(array_size); std::array<int, max_group_size> group_count{0}; vector<group_buffer> groups(max_group_size, group_buffer(max_groups)); int unsexy_count = 0; circular_buffer<int> unsexy_primes(max_unsexy); vector<int> group; for (int p = 2; p < max; ++p) { if (!sieve.is_prime(p)) continue; if (!sieve.is_prime(p + diff) && (p - diff < 2 || !sieve.is_prime(p - diff))) { ++unsexy_count; unsexy_primes.push_back(p); } else { group.clear(); group.push_back(p); for (int group_size = 1; group_size < max_group_size; group_size++) { int next_p = p + group_size * diff; if (next_p >= max || !sieve.is_prime(next_p)) break; group.push_back(next_p); ++group_count[group_size]; groups[group_size].push_back(group); } } } for (int size = 1; size < max_group_size; ++size) { cout << "number of groups of size " << size + 1 << " is " << group_count[size] << '\n'; cout << "last " << groups[size].size() << " groups of size " << size + 1 << ":"; for (const vector<int>& group : groups[size]) { cout << " ("; for (size_t i = 0; i < group.size(); ++i) { if (i > 0) cout << ' '; cout << group[i]; } cout << ")"; } cout << "\n\n"; } cout << "number of unsexy primes is " << unsexy_count << '\n'; cout << "last " << unsexy_primes.size() << " unsexy primes:"; for (int prime : unsexy_primes) cout << ' ' << prime; cout << '\n'; return 0; }
Please provide an equivalent version of this Go code in C++.
package main import "fmt" func main() { a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73} fmt.Println(a) fmt.Println(fd(a, 9)) } func fd(a []int, ord int) []int { for i := 0; i < ord; i++ { for j := 0; j < len(a)-i-1; j++ { a[j] = a[j+1] - a[j] } } return a[:len(a)-ord] }
#include <vector> #include <iterator> #include <algorithm> template<typename InputIterator, typename OutputIterator> OutputIterator forward_difference(InputIterator first, InputIterator last, OutputIterator dest) { if (first == last) return dest; typedef typename std::iterator_traits<InputIterator>::value_type value_type; value_type temp = *first++; while (first != last) { value_type temp2 = *first++; *dest++ = temp2 - temp; temp = temp2; } return dest; } template<typename InputIterator, typename OutputIterator> OutputIterator nth_forward_difference(int order, InputIterator first, InputIterator last, OutputIterator dest) { if (order == 0) return std::copy(first, last, dest); if (order == 1) return forward_difference(first, last, dest); typedef typename std::iterator_traits<InputIterator>::value_type value_type; std::vector<value_type> temp_storage; forward_difference(first, last, std::back_inserter(temp_storage)); typename std::vector<value_type>::iterator begin = temp_storage.begin(), end = temp_storage.end(); for (int i = 1; i < order-1; ++i) end = forward_difference(begin, end, begin); return forward_difference(begin, end, dest); } #include <iostream> int main() { double array[10] = { 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0 }; std::vector<double> dest; nth_forward_difference(1, array, array+10, std::back_inserter(dest)); std::copy(dest.begin(), dest.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(2, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(9, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(10, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; nth_forward_difference(0, array, array+10, std::ostream_iterator<double>(std::cout, " ")); std::cout << std::endl; double* end = nth_forward_difference(3, array, array+10, array); for (double* p = array; p < end; ++p) std::cout << *p << " "; std::cout << std::endl; return 0; }
Write the same code in C++ as shown below in Go.
func IsPrime(n int) bool { if n < 0 { n = -n } switch { case n == 2: return true case n < 2 || n % 2 == 0: return false default: for i = 3; i*i <= n; i += 2 { if n % i == 0 { return false } } } return true }
#include <cmath> bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false; return true; }
Change the following Go code into C++ without altering its purpose.
func IsPrime(n int) bool { if n < 0 { n = -n } switch { case n == 2: return true case n < 2 || n % 2 == 0: return false default: for i = 3; i*i <= n; i += 2 { if n % i == 0 { return false } } } return true }
#include <cmath> bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false; return true; }
Transform the following Go implementation into C++, maintaining the same output and logic.
package main import "fmt" import "math/big" func main() { fmt.Println(new(big.Int).Binomial(5, 3)) fmt.Println(new(big.Int).Binomial(60, 30)) }
double Factorial(double nValue) { double result = nValue; double result_next; double pc = nValue; do { result_next = result*(pc-1); result = result_next; pc--; }while(pc>2); nValue = result; return nValue; } double binomialCoefficient(double n, double k) { if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0; if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n; return Factorial(n) /(Factorial(k)*Factorial((n - k))); }
Generate a C++ translation of this Go snippet without changing its computational steps.
package main import "fmt" func main() { var a []interface{} a = append(a, 3) a = append(a, "apples", "oranges") fmt.Println(a) }
int a[5]; a[0] = 1; int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; #include <string> std::string strings[4];
Keep all operations the same but rewrite the snippet in C++.
start := &Ele{"tacos", nil} end := start.Append("burritos") end = end.Append("fajitas") end = end.Append("enchilatas") for iter := start; iter != nil; iter = iter.Next { fmt.Println(iter) }
#include <iostream> #include <forward_list> int main() { std::forward_list<int> list{1, 2, 3, 4, 5}; for (int e : list) std::cout << e << std::endl; }
Write the same code in C++ as shown below in Go.
start := &Ele{"tacos", nil} end := start.Append("burritos") end = end.Append("fajitas") end = end.Append("enchilatas") for iter := start; iter != nil; iter = iter.Next { fmt.Println(iter) }
#include <iostream> #include <forward_list> int main() { std::forward_list<int> list{1, 2, 3, 4, 5}; for (int e : list) std::cout << e << std::endl; }
Write the same code in C++ as shown below in Go.
package raster import ( "fmt" "io" "os" ) func (b *Bitmap) WritePpmTo(w io.Writer) (err error) { if _, err = fmt.Fprintln(w, "P6"); err != nil { return } for _, c := range b.Comments { if _, err = fmt.Fprintln(w, c); err != nil { return } } _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows) if err != nil { return } b3 := make([]byte, 3*len(b.px)) n1 := 0 for _, px := range b.px { b3[n1] = px.R b3[n1+1] = px.G b3[n1+2] = px.B n1 += 3 } if _, err = w.Write(b3); err != nil { return } return } func (b *Bitmap) WritePpmFile(fn string) (err error) { var f *os.File if f, err = os.Create(fn); err != nil { return } if err = b.WritePpmTo(f); err != nil { return } return f.Close() }
#include <fstream> #include <cstdio> int main() { constexpr auto dimx = 800u, dimy = 800u; using namespace std; ofstream ofs("first.ppm", ios_base::out | ios_base::binary); ofs << "P6" << endl << dimx << ' ' << dimy << endl << "255" << endl; for (auto j = 0u; j < dimy; ++j) for (auto i = 0u; i < dimx; ++i) ofs << (char) (i % 256) << (char) (j % 256) << (char) ((i * j) % 256); ofs.close(); return EXIT_SUCCESS; }
Please provide an equivalent version of this Go code in C++.
package main import "os" func main() { os.Remove("input.txt") os.Remove("/input.txt") os.Remove("docs") os.Remove("/docs") os.RemoveAll("docs") os.RemoveAll("/docs") }
#include <cstdio> #include <direct.h> int main() { remove( "input.txt" ); remove( "/input.txt" ); _rmdir( "docs" ); _rmdir( "/docs" ); return 0; }
Convert the following code from Go to C++, ensuring the logic remains intact.
package main import "os" func main() { os.Remove("input.txt") os.Remove("/input.txt") os.Remove("docs") os.Remove("/docs") os.RemoveAll("docs") os.RemoveAll("/docs") }
#include <cstdio> #include <direct.h> int main() { remove( "input.txt" ); remove( "/input.txt" ); _rmdir( "docs" ); _rmdir( "/docs" ); return 0; }
Rewrite the snippet below in C++ so it works the same as the original Go code.
package ddate import ( "strconv" "strings" "time" ) const ( DefaultFmt = "Pungenday, Discord 5, 3131 YOLD" OldFmt = `Today is Pungenday, the 5th day of Discord in the YOLD 3131 Celebrate Mojoday` ) const ( protoLongSeason = "Discord" protoShortSeason = "Dsc" protoLongDay = "Pungenday" protoShortDay = "PD" protoOrdDay = "5" protoCardDay = "5th" protoHolyday = "Mojoday" protoYear = "3131" ) var ( longDay = []string{"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"} shortDay = []string{"SM", "BT", "PD", "PP", "SO"} longSeason = []string{ "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"} shortSeason = []string{"Chs", "Dsc", "Cfn", "Bcy", "Afm"} holyday = [][]string{{"Mungday", "Chaoflux"}, {"Mojoday", "Discoflux"}, {"Syaday", "Confuflux"}, {"Zaraday", "Bureflux"}, {"Maladay", "Afflux"}} ) type DiscDate struct { StTibs bool Dayy int Year int } func New(eris time.Time) DiscDate { t := time.Date(eris.Year(), 1, 1, eris.Hour(), eris.Minute(), eris.Second(), eris.Nanosecond(), eris.Location()) bob := int(eris.Sub(t).Hours()) / 24 raw := eris.Year() hastur := DiscDate{Year: raw + 1166} if raw%4 == 0 && (raw%100 != 0 || raw%400 == 0) { if bob > 59 { bob-- } else if bob == 59 { hastur.StTibs = true return hastur } } hastur.Dayy = bob return hastur } func (dd DiscDate) Format(f string) (r string) { var st, snarf string var dateElement bool f6 := func(proto, wibble string) { if !dateElement { snarf = r dateElement = true } if st > "" { r = "" } else { r += wibble } f = f[len(proto):] } f4 := func(proto, wibble string) { if dd.StTibs { st = "St. Tib's Day" } f6(proto, wibble) } season, day := dd.Dayy/73, dd.Dayy%73 for f > "" { switch { case strings.HasPrefix(f, protoLongDay): f4(protoLongDay, longDay[dd.Dayy%5]) case strings.HasPrefix(f, protoShortDay): f4(protoShortDay, shortDay[dd.Dayy%5]) case strings.HasPrefix(f, protoCardDay): funkychickens := "th" if day/10 != 1 { switch day % 10 { case 0: funkychickens = "st" case 1: funkychickens = "nd" case 2: funkychickens = "rd" } } f4(protoCardDay, strconv.Itoa(day+1)+funkychickens) case strings.HasPrefix(f, protoOrdDay): f4(protoOrdDay, strconv.Itoa(day+1)) case strings.HasPrefix(f, protoLongSeason): f6(protoLongSeason, longSeason[season]) case strings.HasPrefix(f, protoShortSeason): f6(protoShortSeason, shortSeason[season]) case strings.HasPrefix(f, protoHolyday): if day == 4 { r += holyday[season][0] } else if day == 49 { r += holyday[season][1] } f = f[len(protoHolyday):] case strings.HasPrefix(f, protoYear): r += strconv.Itoa(dd.Year) f = f[4:] default: r += f[:1] f = f[1:] } } if st > "" { r = snarf + st + r } return }
#include <iostream> #include <algorithm> #include <vector> #include <sstream> #include <iterator> using namespace std; class myTuple { public: void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; } bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; } string second() { return t.second; } private: pair<pair<int, int>, string> t; }; class discordian { public: discordian() { myTuple t; t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t ); t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t ); t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t ); t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t ); t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t ); t.set( 8, 12, "Afflux" ); holyday.push_back( t ); seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" ); seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" ); wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" ); wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" ); } void convert( int d, int m, int y ) { if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { cout << "\nThis is not a date!"; return; } vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); int dd = d, day, wday, sea, yr = y + 1166; for( int x = 1; x < m; x++ ) dd += getMaxDay( x, 1 ); day = dd % 73; if( !day ) day = 73; wday = dd % 5; sea = ( dd - 1 ) / 73; if( d == 29 && m == 2 && isLeap( y ) ) { cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr; return; } cout << wdays[wday] << " " << seasons[sea] << " " << day; if( day > 10 && day < 14 ) cout << "th"; else switch( day % 10) { case 1: cout << "st"; break; case 2: cout << "nd"; break; case 3: cout << "rd"; break; default: cout << "th"; } cout << ", Year of Our Lady of Discord " << yr; if( f != holyday.end() ) cout << " - " << ( *f ).second(); } private: int getMaxDay( int m, int y ) { int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; } bool isLeap( int y ) { bool l = false; if( !( y % 4 ) ) { if( y % 100 ) l = true; else if( !( y % 400 ) ) l = true; } return l; } vector<myTuple> holyday; vector<string> seasons, wdays; }; int main( int argc, char* argv[] ) { string date; discordian disc; while( true ) { cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break; if( date.length() == 10 ) { istringstream iss( date ); vector<string> vc; copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) ); disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); cout << "\n\n\n"; } else cout << "\nIs this a date?!\n\n"; } return 0; }
Port the provided Go code into C++ while preserving the original functionality.
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var n int = 3 var moves int = 0 a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } } b := make([][]int, len(a)) for i := range a { b[i] = make([]int, len(a[i])) copy(b[i], a[i]) } for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- { b = flipCol(b, rand.Intn(n) + 1) b = flipRow(b, rand.Intn(n) + 1) } fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) var rc rune var num int for { for{ fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n) _, err := fmt.Scanf("%c%d", &rc, &num) if err != nil { fmt.Println(err) continue } if num < 1 || num > n { fmt.Println("Wrong command!") continue } break } switch rc { case 'c': fmt.Printf("Column %v will be flipped\n", num) flipCol(b, num) case 'r': fmt.Printf("Row %v will be flipped\n", num) flipRow(b, num) default: fmt.Println("Wrong command!") continue } moves++ fmt.Println("\nMoves taken: ", moves) fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) if compareSlices(a, b) { fmt.Printf("Finished. You win with %d moves!\n", moves) break } } } func drawBoard (m [][]int) { fmt.Print(" ") for i := range m { fmt.Printf("%d ", i+1) } for i := range m { fmt.Println() fmt.Printf("%d ", i+1) for _, val := range m[i] { fmt.Printf(" %d", val) } } fmt.Print("\n") } func flipRow(m [][]int, row int) ([][]int) { for j := range m { m[row-1][j] ^= 1 } return m } func flipCol(m [][]int, col int) ([][]int) { for j := range m { m[j][col-1] ^= 1 } return m } func compareSlices(m [][]int, n[][]int) bool { o := true for i := range m { for j := range m { if m[i][j] != n[i][j] { o = false } } } return o }
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
Write the same code in C++ as shown below in Go.
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) var n int = 3 var moves int = 0 a := make([][]int, n) for i := range a { a[i] = make([]int, n) for j := range a { a[i][j] = rand.Intn(2) } } b := make([][]int, len(a)) for i := range a { b[i] = make([]int, len(a[i])) copy(b[i], a[i]) } for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- { b = flipCol(b, rand.Intn(n) + 1) b = flipRow(b, rand.Intn(n) + 1) } fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) var rc rune var num int for { for{ fmt.Printf("\nFlip row (r) or column (c) 1 .. %d (c1, ...): ", n) _, err := fmt.Scanf("%c%d", &rc, &num) if err != nil { fmt.Println(err) continue } if num < 1 || num > n { fmt.Println("Wrong command!") continue } break } switch rc { case 'c': fmt.Printf("Column %v will be flipped\n", num) flipCol(b, num) case 'r': fmt.Printf("Row %v will be flipped\n", num) flipRow(b, num) default: fmt.Println("Wrong command!") continue } moves++ fmt.Println("\nMoves taken: ", moves) fmt.Println("Target:") drawBoard(a) fmt.Println("\nBoard:") drawBoard(b) if compareSlices(a, b) { fmt.Printf("Finished. You win with %d moves!\n", moves) break } } } func drawBoard (m [][]int) { fmt.Print(" ") for i := range m { fmt.Printf("%d ", i+1) } for i := range m { fmt.Println() fmt.Printf("%d ", i+1) for _, val := range m[i] { fmt.Printf(" %d", val) } } fmt.Print("\n") } func flipRow(m [][]int, row int) ([][]int) { for j := range m { m[row-1][j] ^= 1 } return m } func flipCol(m [][]int, col int) ([][]int) { for j := range m { m[j][col-1] ^= 1 } return m } func compareSlices(m [][]int, n[][]int) bool { o := true for i := range m { for j := range m { if m[i][j] != n[i][j] { o = false } } } return o }
#include <time.h> #include <iostream> #include <string> typedef unsigned char byte; using namespace std; class flip { public: flip() { field = 0; target = 0; } void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); } private: void gameLoop() { int moves = 0; while( !solved() ) { display(); string r; cout << "Enter rows letters and/or column numbers: "; cin >> r; for( string::iterator i = r.begin(); i != r.end(); i++ ) { byte ii = ( *i ); if( ii - 1 >= '0' && ii - 1 <= '9' ) { flipCol( ii - '1' ); moves++; } else if( ii >= 'a' && ii <= 'z' ) { flipRow( ii - 'a' ); moves++; } } } cout << endl << endl << "** Well done! **" << endl << "Used " << moves << " moves." << endl << endl; } void display() { system( "cls" ); output( "TARGET:", target ); output( "YOU:", field ); } void output( string t, byte* f ) { cout << t << endl; cout << " "; for( int x = 0; x < wid; x++ ) cout << " " << static_cast<char>( x + '1' ); cout << endl; for( int y = 0; y < hei; y++ ) { cout << static_cast<char>( y + 'a' ) << " "; for( int x = 0; x < wid; x++ ) cout << static_cast<char>( f[x + y * wid] + 48 ) << " "; cout << endl; } cout << endl << endl; } bool solved() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( target[x + y * wid] != field[x + y * wid] ) return false; return true; } void createTarget() { for( int y = 0; y < hei; y++ ) for( int x = 0; x < wid; x++ ) if( frnd() < .5f ) target[x + y * wid] = 1; else target[x + y * wid] = 0; memcpy( field, target, wid * hei ); } void flipCol( int c ) { for( int x = 0; x < hei; x++ ) field[c + x * wid] = !field[c + x * wid]; } void flipRow( int r ) { for( int x = 0; x < wid; x++ ) field[x + r * wid] = !field[x + r * wid]; } void calcStartPos() { int flips = ( rand() % wid + wid + rand() % hei + hei ) >> 1; for( int x = 0; x < flips; x++ ) { if( frnd() < .5f ) flipCol( rand() % wid ); else flipRow( rand() % hei ); } } void createField() { if( field ){ delete [] field; delete [] target; } int t = wid * hei; field = new byte[t]; target = new byte[t]; memset( field, 0, t ); memset( target, 0, t ); createTarget(); while( true ) { calcStartPos(); if( !solved() ) break; } } float frnd() { return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX ); } byte* field, *target; int wid, hei; }; int main( int argc, char* argv[] ) { srand( time( NULL ) ); flip g; g.play( 3, 3 ); return system( "pause" ); }
Produce a functionally identical C++ code for the snippet given in Go.
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator = ln_two; for(int n = 1; n <= 17; n++) { decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; decfloat tenths_dig = floor((h - floor(h)) * 10); std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; } }
Convert the following code from Go to C++, ensuring the logic remains intact.
package main import ( "fmt" "math/big" ) func main() { ln2, _ := new(big.Rat).SetString("0.6931471805599453094172") h := big.NewRat(1, 2) h.Quo(h, ln2) var f big.Rat var w big.Int for i := int64(1); i <= 17; i++ { h.Quo(h.Mul(h, f.SetInt64(i)), ln2) w.Quo(h.Num(), h.Denom()) f.Sub(h, f.SetInt(&w)) y, _ := f.Float64() d := fmt.Sprintf("%.3f", y) fmt.Printf("n: %2d h: %18d%s Nearly integer: %t\n", i, &w, d[1:], d[2] == '0' || d[2] == '9') } }
#include <iostream> #include <iomanip> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> typedef boost::multiprecision::cpp_dec_float_50 decfloat; int main() { const decfloat ln_two = boost::math::constants::ln_two<decfloat>(); decfloat numerator = 1, denominator = ln_two; for(int n = 1; n <= 17; n++) { decfloat h = (numerator *= n) / (denominator *= ln_two) / 2; decfloat tenths_dig = floor((h - floor(h)) * 10); std::cout << "h(" << std::setw(2) << n << ") = " << std::setw(25) << std::fixed << h << (tenths_dig == 0 || tenths_dig == 9 ? " is " : " is NOT ") << "an almost-integer.\n"; } }
Port the provided Go code into C++ while preserving the original functionality.
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
Generate a C++ translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
#include <random> #include <random> #include <vector> #include <iostream> #define MAX_N 20 #define TIMES 1000000 static std::random_device rd; static std::mt19937 gen(rd()); static std::uniform_int_distribution<> dis; int randint(int n) { int r, rmax = RAND_MAX / n * n; dis=std::uniform_int_distribution<int>(0,rmax) ; r = dis(gen); return r / (RAND_MAX / n); } unsigned long long factorial(size_t n) { static std::vector<unsigned long long>factorials{1,1,2}; for (;factorials.size() <= n;) factorials.push_back(((unsigned long long) factorials.back())*factorials.size()); return factorials[n]; } long double expected(size_t n) { long double sum = 0; for (size_t i = 1; i <= n; i++) sum += factorial(n) / pow(n, i) / factorial(n - i); return sum; } int test(int n, int times) { int i, count = 0; for (i = 0; i < times; i++) { unsigned int x = 1, bits = 0; while (!(bits & x)) { count++; bits |= x; x = static_cast<unsigned int>(1 << randint(n)); } } return count; } int main() { puts(" n\tavg\texp.\tdiff\n-------------------------------"); int n; for (n = 1; n <= MAX_N; n++) { int cnt = test(n, TIMES); long double avg = (double)cnt / TIMES; long double theory = expected(static_cast<size_t>(n)); long double diff = (avg / theory - 1) * 100; printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff)); } return 0; }
Transform the following Go implementation into C++, maintaining the same output and logic.
package main import ( "fmt" ) func main() { str := "Mary had a %s lamb" txt := "little" out := fmt.Sprintf(str, txt) fmt.Println(out) }
#include <string> #include <iostream> int main( ) { std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , replacement ( "little" ) ; std::string newString = original.replace( original.find( "X" ) , toBeReplaced.length( ) , replacement ) ; std::cout << "String after replacement: " << newString << " \n" ; return 0 ; }
Generate a C++ translation of this Go snippet without changing its computational steps.
package main import ( "fmt" ) func main() { str := "Mary had a %s lamb" txt := "little" out := fmt.Sprintf(str, txt) fmt.Println(out) }
#include <string> #include <iostream> int main( ) { std::string original( "Mary had a X lamb." ) , toBeReplaced( "X" ) , replacement ( "little" ) ; std::string newString = original.replace( original.find( "X" ) , toBeReplaced.length( ) , replacement ) ; std::cout << "String after replacement: " << newString << " \n" ; return 0 ; }
Generate a C++ translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "container/heap" "sort" ) type IntPile []int func (self IntPile) Top() int { return self[len(self)-1] } func (self *IntPile) Pop() int { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x } type IntPilesHeap []IntPile func (self IntPilesHeap) Len() int { return len(self) } func (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() } func (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] } func (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) } func (self *IntPilesHeap) Pop() interface{} { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x } func patience_sort (n []int) { var piles []IntPile for _, x := range n { j := sort.Search(len(piles), func (i int) bool { return piles[i].Top() >= x }) if j != len(piles) { piles[j] = append(piles[j], x) } else { piles = append(piles, IntPile{ x }) } } hp := IntPilesHeap(piles) heap.Init(&hp) for i, _ := range n { smallPile := heap.Pop(&hp).(IntPile) n[i] = smallPile.Pop() if len(smallPile) != 0 { heap.Push(&hp, smallPile) } } if len(hp) != 0 { panic("something went wrong") } } func main() { a := []int{4, 65, 2, -31, 0, 99, 83, 782, 1} patience_sort(a) fmt.Println(a) }
#include <iostream> #include <vector> #include <stack> #include <iterator> #include <algorithm> #include <cassert> template <class E> struct pile_less { bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const { return pile1.top() < pile2.top(); } }; template <class E> struct pile_greater { bool operator()(const std::stack<E> &pile1, const std::stack<E> &pile2) const { return pile1.top() > pile2.top(); } }; template <class Iterator> void patience_sort(Iterator first, Iterator last) { typedef typename std::iterator_traits<Iterator>::value_type E; typedef std::stack<E> Pile; std::vector<Pile> piles; for (Iterator it = first; it != last; it++) { E& x = *it; Pile newPile; newPile.push(x); typename std::vector<Pile>::iterator i = std::lower_bound(piles.begin(), piles.end(), newPile, pile_less<E>()); if (i != piles.end()) i->push(x); else piles.push_back(newPile); } std::make_heap(piles.begin(), piles.end(), pile_greater<E>()); for (Iterator it = first; it != last; it++) { std::pop_heap(piles.begin(), piles.end(), pile_greater<E>()); Pile &smallPile = piles.back(); *it = smallPile.top(); smallPile.pop(); if (smallPile.empty()) piles.pop_back(); else std::push_heap(piles.begin(), piles.end(), pile_greater<E>()); } assert(piles.empty()); } int main() { int a[] = {4, 65, 2, -31, 0, 99, 83, 782, 1}; patience_sort(a, a+sizeof(a)/sizeof(*a)); std::copy(a, a+sizeof(a)/sizeof(*a), std::ostream_iterator<int>(std::cout, ", ")); std::cout << std::endl; return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT" func mutate(dna string, w [3]int) string { le := len(dna) p := rand.Intn(le) r := rand.Intn(300) bytes := []byte(dna) switch { case r < w[0]: base := bases[rand.Intn(4)] fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base) bytes[p] = base case r < w[0]+w[1]: fmt.Printf(" Delete @%3d %q\n", p, bytes[p]) copy(bytes[p:], bytes[p+1:]) bytes = bytes[0 : le-1] default: base := bases[rand.Intn(4)] bytes = append(bytes, 0) copy(bytes[p+1:], bytes[p:]) fmt.Printf(" Insert @%3d %q\n", p, base) bytes[p] = base } return string(bytes) } func generate(le int) string { bytes := make([]byte, le) for i := 0; i < le; i++ { bytes[i] = bases[rand.Intn(4)] } return string(bytes) } func prettyPrint(dna string, rowLen int) { fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += rowLen { k := i + rowLen if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======\n") } func wstring(w [3]int) string { return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2]) } func main() { rand.Seed(time.Now().UnixNano()) dna := generate(250) prettyPrint(dna, 50) muts := 10 w := [3]int{100, 100, 100} fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w)) fmt.Printf("MUTATIONS (%d):\n", muts) for i := 0; i < muts; i++ { dna = mutate(dna, w) } fmt.Println() prettyPrint(dna, 50) }
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
Produce a functionally identical C++ code for the snippet given in Go.
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT" func mutate(dna string, w [3]int) string { le := len(dna) p := rand.Intn(le) r := rand.Intn(300) bytes := []byte(dna) switch { case r < w[0]: base := bases[rand.Intn(4)] fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base) bytes[p] = base case r < w[0]+w[1]: fmt.Printf(" Delete @%3d %q\n", p, bytes[p]) copy(bytes[p:], bytes[p+1:]) bytes = bytes[0 : le-1] default: base := bases[rand.Intn(4)] bytes = append(bytes, 0) copy(bytes[p+1:], bytes[p:]) fmt.Printf(" Insert @%3d %q\n", p, base) bytes[p] = base } return string(bytes) } func generate(le int) string { bytes := make([]byte, le) for i := 0; i < le; i++ { bytes[i] = bases[rand.Intn(4)] } return string(bytes) } func prettyPrint(dna string, rowLen int) { fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += rowLen { k := i + rowLen if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======\n") } func wstring(w [3]int) string { return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2]) } func main() { rand.Seed(time.Now().UnixNano()) dna := generate(250) prettyPrint(dna, 50) muts := 10 w := [3]int{100, 100, 100} fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w)) fmt.Printf("MUTATIONS (%d):\n", muts) for i := 0; i < muts; i++ { dna = mutate(dna, w) } fmt.Println() prettyPrint(dna, 50) }
#include <array> #include <iomanip> #include <iostream> #include <random> #include <string> class sequence_generator { public: sequence_generator(); std::string generate_sequence(size_t length); void mutate_sequence(std::string&); static void print_sequence(std::ostream&, const std::string&); enum class operation { change, erase, insert }; void set_weight(operation, unsigned int); private: char get_random_base() { return bases_[base_dist_(engine_)]; } operation get_random_operation(); static const std::array<char, 4> bases_; std::mt19937 engine_; std::uniform_int_distribution<size_t> base_dist_; std::array<unsigned int, 3> operation_weight_; unsigned int total_weight_; }; const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' }; sequence_generator::sequence_generator() : engine_(std::random_device()()), base_dist_(0, bases_.size() - 1), total_weight_(operation_weight_.size()) { operation_weight_.fill(1); } sequence_generator::operation sequence_generator::get_random_operation() { std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1); unsigned int n = op_dist(engine_), op = 0, weight = 0; for (; op < operation_weight_.size(); ++op) { weight += operation_weight_[op]; if (n < weight) break; } return static_cast<operation>(op); } void sequence_generator::set_weight(operation op, unsigned int weight) { total_weight_ -= operation_weight_[static_cast<size_t>(op)]; operation_weight_[static_cast<size_t>(op)] = weight; total_weight_ += weight; } std::string sequence_generator::generate_sequence(size_t length) { std::string sequence; sequence.reserve(length); for (size_t i = 0; i < length; ++i) sequence += get_random_base(); return sequence; } void sequence_generator::mutate_sequence(std::string& sequence) { std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1); size_t pos = dist(engine_); char b; switch (get_random_operation()) { case operation::change: b = get_random_base(); std::cout << "Change base at position " << pos << " from " << sequence[pos] << " to " << b << '\n'; sequence[pos] = b; break; case operation::erase: std::cout << "Erase base " << sequence[pos] << " at position " << pos << '\n'; sequence.erase(pos, 1); break; case operation::insert: b = get_random_base(); std::cout << "Insert base " << b << " at position " << pos << '\n'; sequence.insert(pos, 1, b); break; } } void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) { constexpr size_t base_count = bases_.size(); std::array<size_t, base_count> count = { 0 }; for (size_t i = 0, n = sequence.length(); i < n; ++i) { if (i % 50 == 0) { if (i != 0) out << '\n'; out << std::setw(3) << i << ": "; } out << sequence[i]; for (size_t j = 0; j < base_count; ++j) { if (bases_[j] == sequence[i]) { ++count[j]; break; } } } out << '\n'; out << "Base counts:\n"; size_t total = 0; for (size_t j = 0; j < base_count; ++j) { total += count[j]; out << bases_[j] << ": " << count[j] << ", "; } out << "Total: " << total << '\n'; } int main() { sequence_generator gen; gen.set_weight(sequence_generator::operation::change, 2); std::string sequence = gen.generate_sequence(250); std::cout << "Initial sequence:\n"; sequence_generator::print_sequence(std::cout, sequence); constexpr int count = 10; for (int i = 0; i < count; ++i) gen.mutate_sequence(sequence); std::cout << "After " << count << " mutations:\n"; sequence_generator::print_sequence(std::cout, sequence); return 0; }
Preserve the algorithm and functionality while converting the code from Go to C++.
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } return count } func main() { fmt.Println("The first 100 tau numbers are:") count := 0 i := 1 for count < 100 { tf := countDivisors(i) if i%tf == 0 { fmt.Printf("%4d ", i) count++ if count%10 == 0 { fmt.Println() } } i++ } }
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; } if (n > 1) total *= 2; return total; } int main() { const unsigned int limit = 100; std::cout << "The first " << limit << " tau numbers are:\n"; unsigned int count = 0; for (unsigned int n = 1; count < limit; ++n) { if (n % divisor_count(n) == 0) { std::cout << std::setw(6) << n; ++count; if (count % 10 == 0) std::cout << '\n'; } } }
Convert this Go block to C++, preserving its control flow and logic.
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += float64(s) * pr } return } func permanent(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += pr } return } var m2 = [][]float64{ {1, 2}, {3, 4}} var m3 = [][]float64{ {2, 9, 4}, {7, 5, 3}, {6, 1, 8}} func main() { fmt.Println(determinant(m2), permanent(m2)) fmt.Println(determinant(m3), permanent(m3)) }
#include <iostream> #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 << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
Change the programming language of this snippet from Go to C++ without modifying what it does.
package main import ( "fmt" "permute" ) func determinant(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += float64(s) * pr } return } func permanent(m [][]float64) (d float64) { p := make([]int, len(m)) for i := range p { p[i] = i } it := permute.Iter(p) for s := it(); s != 0; s = it() { pr := 1. for i, σ := range p { pr *= m[i][σ] } d += pr } return } var m2 = [][]float64{ {1, 2}, {3, 4}} var m3 = [][]float64{ {2, 9, 4}, {7, 5, 3}, {6, 1, 8}} func main() { fmt.Println(determinant(m2), permanent(m2)) fmt.Println(determinant(m3), permanent(m3)) }
#include <iostream> #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 << ']'; } using Matrix = std::vector<std::vector<double>>; Matrix squareMatrix(size_t n) { Matrix m; for (size_t i = 0; i < n; i++) { std::vector<double> inner; for (size_t j = 0; j < n; j++) { inner.push_back(nan("")); } m.push_back(inner); } return m; } Matrix minor(const Matrix &a, int x, int y) { auto length = a.size() - 1; auto result = squareMatrix(length); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (i < x && j < y) { result[i][j] = a[i][j]; } else if (i >= x && j < y) { result[i][j] = a[i + 1][j]; } else if (i < x && j >= y) { result[i][j] = a[i][j + 1]; } else { result[i][j] = a[i + 1][j + 1]; } } } return result; } double det(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } int sign = 1; double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += sign * a[0][i] * det(minor(a, 0, i)); sign *= -1; } return sum; } double perm(const Matrix &a) { if (a.size() == 1) { return a[0][0]; } double sum = 0; for (size_t i = 0; i < a.size(); i++) { sum += a[0][i] * perm(minor(a, 0, i)); } return sum; } void test(const Matrix &m) { auto p = perm(m); auto d = det(m); std::cout << m << '\n'; std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n"; } int main() { test({ {1, 2}, {3, 4} }); test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} }); test({ {0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24} }); return 0; }
Rewrite this program in C++ while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/big" "time" ) var p []*big.Int var pd []int func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 } func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] } func partitionsP(n int) { if n < 2 { return } psum := new(big.Int) for i := 1; i <= n; i++ { pdi := partDiff(i) if pdi > n { break } sign := int64(-1) if (i-1)%4 < 2 { sign = 1 } t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign)) psum.Add(psum, t) } p[n] = psum } func main() { start := time.Now() const N = 6666 p = make([]*big.Int, N+1) pd = make([]int, N+1) p[0], pd[0] = big.NewInt(1), 1 p[1], pd[1] = big.NewInt(1), 1 for n := 2; n <= N; n++ { partitionsP(n) } fmt.Printf("p[%d)] = %d\n", N, p[N]) fmt.Printf("Took %s\n", time.Since(start)) }
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; j = (k * (3*k + 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; } } return p[n]; } int main() { auto start = std::chrono::steady_clock::now(); auto result = partitions(6666); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> ms(end - start); std::cout << result << '\n'; std::cout << "elapsed time: " << ms.count() << " milliseconds\n"; }
Change the programming language of this snippet from Go to C++ without modifying what it does.
package main import ( "fmt" "math/big" "time" ) var p []*big.Int var pd []int func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 } func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] } func partitionsP(n int) { if n < 2 { return } psum := new(big.Int) for i := 1; i <= n; i++ { pdi := partDiff(i) if pdi > n { break } sign := int64(-1) if (i-1)%4 < 2 { sign = 1 } t := new(big.Int).Mul(p[n-pdi], big.NewInt(sign)) psum.Add(psum, t) } p[n] = psum } func main() { start := time.Now() const N = 6666 p = make([]*big.Int, N+1) pd = make([]int, N+1) p[0], pd[0] = big.NewInt(1), 1 p[1], pd[1] = big.NewInt(1), 1 for n := 2; n <= N; n++ { partitionsP(n) } fmt.Printf("p[%d)] = %d\n", N, p[N]) fmt.Printf("Took %s\n", time.Since(start)) }
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; j = (k * (3*k + 1))/2; if (j > i) break; if (k & 1) p[i] += p[i - j]; else p[i] -= p[i - j]; } } return p[n]; } int main() { auto start = std::chrono::steady_clock::now(); auto result = partitions(6666); auto end = std::chrono::steady_clock::now(); std::chrono::duration<double, std::milli> ms(end - start); std::cout << result << '\n'; std::cout << "elapsed time: " << ms.count() << " milliseconds\n"; }
Change the following Go code into C++ without altering its purpose.
package main import ( "bytes" "fmt" "io/ioutil" "strings" ) var rows, cols int var rx, cx int var mn []int func main() { src, err := ioutil.ReadFile("ww.config") if err != nil { fmt.Println(err) return } srcRows := bytes.Split(src, []byte{'\n'}) rows = len(srcRows) for _, r := range srcRows { if len(r) > cols { cols = len(r) } } rx, cx = rows+2, cols+2 mn = []int{-cx-1, -cx, -cx+1, -1, 1, cx-1, cx, cx+1} odd := make([]byte, rx*cx) even := make([]byte, rx*cx) for ri, r := range srcRows { copy(odd[(ri+1)*cx+1:], r) } for { print(odd) step(even, odd) fmt.Scanln() print(even) step(odd, even) fmt.Scanln() } } func print(grid []byte) { fmt.Println(strings.Repeat("__", cols)) fmt.Println() for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { if grid[r*cx+c] == 0 { fmt.Print(" ") } else { fmt.Printf(" %c", grid[r*cx+c]) } } fmt.Println() } } func step(dst, src []byte) { for r := 1; r <= rows; r++ { for c := 1; c <= cols; c++ { x := r*cx + c dst[x] = src[x] switch dst[x] { case 'H': dst[x] = 't' case 't': dst[x] = '.' case '.': var nn int for _, n := range mn { if src[x+n] == 'H' { nn++ } } if nn == 1 || nn == 2 { dst[x] = 'H' } } } } }
#include <ggi/ggi.h> #include <set> #include <map> #include <utility> #include <iostream> #include <fstream> #include <string> #include <unistd.h> enum cell_type { none, wire, head, tail }; class display { public: display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors); ~display() { ggiClose(visual); ggiExit(); } void flush(); bool keypressed() { return ggiKbhit(visual); } void clear(); void putpixel(int x, int y, cell_type c); private: ggi_visual_t visual; int size_x, size_y; int pixel_size_x, pixel_size_y; ggi_pixel pixels[4]; }; display::display(int sizex, int sizey, int pixsizex, int pixsizey, ggi_color* colors): pixel_size_x(pixsizex), pixel_size_y(pixsizey) { if (ggiInit() < 0) { std::cerr << "couldn't open ggi\n"; exit(1); } visual = ggiOpen(NULL); if (!visual) { ggiPanic("couldn't open visual\n"); } ggi_mode mode; if (ggiCheckGraphMode(visual, sizex, sizey, GGI_AUTO, GGI_AUTO, GT_4BIT, &mode) != 0) { if (GT_DEPTH(mode.graphtype) < 2) ggiPanic("low-color displays are not supported!\n"); } if (ggiSetMode(visual, &mode) != 0) { ggiPanic("couldn't set graph mode\n"); } ggiAddFlags(visual, GGIFLAG_ASYNC); size_x = mode.virt.x; size_y = mode.virt.y; for (int i = 0; i < 4; ++i) pixels[i] = ggiMapColor(visual, colors+i); } void display::flush() { ggiSetDisplayFrame(visual, ggiGetWriteFrame(visual)); ggiFlush(visual); ggiSetWriteFrame(visual, 1-ggiGetDisplayFrame(visual)); } void display::clear() { ggiSetGCForeground(visual, pixels[0]); ggiDrawBox(visual, 0, 0, size_x, size_y); } void display::putpixel(int x, int y, cell_type cell) { ggiSetGCForeground(visual, pixels[cell]); ggiDrawBox(visual, x*pixel_size_x, y*pixel_size_y, pixel_size_x, pixel_size_y); } class wireworld { public: void set(int posx, int posy, cell_type type); void draw(display& destination); void step(); private: typedef std::pair<int, int> position; typedef std::set<position> position_set; typedef position_set::iterator positer; position_set wires, heads, tails; }; void wireworld::set(int posx, int posy, cell_type type) { position p(posx, posy); wires.erase(p); heads.erase(p); tails.erase(p); switch(type) { case head: heads.insert(p); break; case tail: tails.insert(p); break; case wire: wires.insert(p); break; } } void wireworld::draw(display& destination) { destination.clear(); for (positer i = heads.begin(); i != heads.end(); ++i) destination.putpixel(i->first, i->second, head); for (positer i = tails.begin(); i != tails.end(); ++i) destination.putpixel(i->first, i->second, tail); for (positer i = wires.begin(); i != wires.end(); ++i) destination.putpixel(i->first, i->second, wire); destination.flush(); } void wireworld::step() { std::map<position, int> new_heads; for (positer i = heads.begin(); i != heads.end(); ++i) for (int dx = -1; dx <= 1; ++dx) for (int dy = -1; dy <= 1; ++dy) { position pos(i->first + dx, i->second + dy); if (wires.count(pos)) new_heads[pos]++; } wires.insert(tails.begin(), tails.end()); tails.swap(heads); heads.clear(); for (std::map<position, int>::iterator i = new_heads.begin(); i != new_heads.end(); ++i) { if (i->second < 3) { wires.erase(i->first); heads.insert(i->first); } } } ggi_color colors[4] = {{ 0x0000, 0x0000, 0x0000 }, { 0x8000, 0x8000, 0x8000 }, { 0xffff, 0xffff, 0x0000 }, { 0xffff, 0x0000, 0x0000 }}; int main(int argc, char* argv[]) { int display_x = 800; int display_y = 600; int pixel_x = 5; int pixel_y = 5; if (argc < 2) { std::cerr << "No file name given!\n"; return 1; } std::ifstream f(argv[1]); wireworld w; std::string line; int line_number = 0; while (std::getline(f, line)) { for (int col = 0; col < line.size(); ++col) { switch (line[col]) { case 'h': case 'H': w.set(col, line_number, head); break; case 't': case 'T': w.set(col, line_number, tail); break; case 'w': case 'W': case '.': w.set(col, line_number, wire); break; default: std::cerr << "unrecognized character: " << line[col] << "\n"; return 1; case ' ': ; } } ++line_number; } display d(display_x, display_y, pixel_x, pixel_y, colors); w.draw(d); while (!d.keypressed()) { usleep(100000); w.step(); w.draw(d); } std::cout << std::endl; }
Rewrite the snippet below in C++ so it works the same as the original Go code.
package main import ( "fmt" "math" ) type xy struct { x, y float64 } type seg struct { p1, p2 xy } type poly struct { name string sides []seg } func inside(pt xy, pg poly) (i bool) { for _, side := range pg.sides { if rayIntersectsSegment(pt, side) { i = !i } } return } func rayIntersectsSegment(p xy, s seg) bool { var a, b xy if s.p1.y < s.p2.y { a, b = s.p1, s.p2 } else { a, b = s.p2, s.p1 } for p.y == a.y || p.y == b.y { p.y = math.Nextafter(p.y, math.Inf(1)) } if p.y < a.y || p.y > b.y { return false } if a.x > b.x { if p.x > a.x { return false } if p.x < b.x { return true } } else { if p.x > b.x { return false } if p.x < a.x { return true } } return (p.y-a.y)/(p.x-a.x) >= (b.y-a.y)/(b.x-a.x) } var ( p1 = xy{0, 0} p2 = xy{10, 0} p3 = xy{10, 10} p4 = xy{0, 10} p5 = xy{2.5, 2.5} p6 = xy{7.5, 2.5} p7 = xy{7.5, 7.5} p8 = xy{2.5, 7.5} p9 = xy{0, 5} p10 = xy{10, 5} p11 = xy{3, 0} p12 = xy{7, 0} p13 = xy{7, 10} p14 = xy{3, 10} ) var tpg = []poly{ {"square", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}}}, {"square hole", []seg{{p1, p2}, {p2, p3}, {p3, p4}, {p4, p1}, {p5, p6}, {p6, p7}, {p7, p8}, {p8, p5}}}, {"strange", []seg{{p1, p5}, {p5, p4}, {p4, p8}, {p8, p7}, {p7, p3}, {p3, p2}, {p2, p5}}}, {"exagon", []seg{{p11, p12}, {p12, p10}, {p10, p13}, {p13, p14}, {p14, p9}, {p9, p11}}}, } var tpt = []xy{ {5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, {10, 10}, {1, 2}, {2, 1}, } func main() { for _, pg := range tpg { fmt.Printf("%s:\n", pg.name) for _, pt := range tpt { fmt.Println(pt, inside(pt, pg)) } } }
#include <algorithm> #include <cstdlib> #include <iomanip> #include <iostream> #include <limits> using namespace std; const double epsilon = numeric_limits<float>().epsilon(); const numeric_limits<double> DOUBLE; const double MIN = DOUBLE.min(); const double MAX = DOUBLE.max(); struct Point { const double x, y; }; struct Edge { const Point a, b; bool operator()(const Point& p) const { if (a.y > b.y) return Edge{ b, a }(p); if (p.y == a.y || p.y == b.y) return operator()({ p.x, p.y + epsilon }); if (p.y > b.y || p.y < a.y || p.x > max(a.x, b.x)) return false; if (p.x < min(a.x, b.x)) return true; auto blue = abs(a.x - p.x) > MIN ? (p.y - a.y) / (p.x - a.x) : MAX; auto red = abs(a.x - b.x) > MIN ? (b.y - a.y) / (b.x - a.x) : MAX; return blue >= red; } }; struct Figure { const string name; const initializer_list<Edge> edges; bool contains(const Point& p) const { auto c = 0; for (auto e : edges) if (e(p)) c++; return c % 2 != 0; } template<unsigned char W = 3> void check(const initializer_list<Point>& points, ostream& os) const { os << "Is point inside figure " << name << '?' << endl; for (auto p : points) os << " (" << setw(W) << p.x << ',' << setw(W) << p.y << "): " << boolalpha << contains(p) << endl; os << endl; } }; int main() { const initializer_list<Point> points = { { 5.0, 5.0}, {5.0, 8.0}, {-10.0, 5.0}, {0.0, 5.0}, {10.0, 5.0}, {8.0, 5.0}, {10.0, 10.0} }; const Figure square = { "Square", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}} } }; const Figure square_hole = { "Square hole", { {{0.0, 0.0}, {10.0, 0.0}}, {{10.0, 0.0}, {10.0, 10.0}}, {{10.0, 10.0}, {0.0, 10.0}}, {{0.0, 10.0}, {0.0, 0.0}}, {{2.5, 2.5}, {7.5, 2.5}}, {{7.5, 2.5}, {7.5, 7.5}}, {{7.5, 7.5}, {2.5, 7.5}}, {{2.5, 7.5}, {2.5, 2.5}} } }; const Figure strange = { "Strange", { {{0.0, 0.0}, {2.5, 2.5}}, {{2.5, 2.5}, {0.0, 10.0}}, {{0.0, 10.0}, {2.5, 7.5}}, {{2.5, 7.5}, {7.5, 7.5}}, {{7.5, 7.5}, {10.0, 10.0}}, {{10.0, 10.0}, {10.0, 0.0}}, {{10.0, 0}, {2.5, 2.5}} } }; const Figure exagon = { "Exagon", { {{3.0, 0.0}, {7.0, 0.0}}, {{7.0, 0.0}, {10.0, 5.0}}, {{10.0, 5.0}, {7.0, 10.0}}, {{7.0, 10.0}, {3.0, 10.0}}, {{3.0, 10.0}, {0.0, 5.0}}, {{0.0, 5.0}, {3.0, 0.0}} } }; for(auto f : {square, square_hole, strange, exagon}) f.check(points, cout); return EXIT_SUCCESS; }
Change the following Go code into C++ without altering its purpose.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f, %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { return; } if(m_y == 0) { *this = EllipticPoint(); } else { double L = (3 * m_x * m_x) / (2 * m_y); double newX = L * L - 2 * m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } } public: friend std::ostream& operator<<(std::ostream&, const EllipticPoint&); constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {} explicit EllipticPoint(double yCoordinate) noexcept { m_y = yCoordinate; m_x = cbrt(m_y * m_y - B); } bool IsZero() const noexcept { bool isNotZero = abs(m_y) < ZeroThreshold; return !isNotZero; } EllipticPoint operator-() const noexcept { EllipticPoint negPt; negPt.m_x = m_x; negPt.m_y = -m_y; return negPt; } EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept { if(IsZero()) { *this = rhs; } else if (rhs.IsZero()) { } else { double L = (rhs.m_y - m_y) / (rhs.m_x - m_x); if(isfinite(L)) { double newX = L * L - m_x - rhs.m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } else { if(signbit(m_y) != signbit(rhs.m_y)) { *this = EllipticPoint(); } else { Double(); } } } return *this; } EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept { *this+= -rhs; return *this; } EllipticPoint& operator*=(int rhs) noexcept { EllipticPoint r; EllipticPoint p = *this; if(rhs < 0) { rhs = -rhs; p = -p; } for (int i = 1; i <= rhs; i <<= 1) { if (i & rhs) r += p; p.Double(); } *this = r; return *this; } }; inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += rhs; return lhs; } inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += -rhs; return lhs; } inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept { lhs *= rhs; return lhs; } inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept { rhs *= lhs; return rhs; } ostream& operator<<(ostream& os, const EllipticPoint& pt) { if(pt.IsZero()) cout << "(Zero)\n"; else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n"; return os; } int main(void) { const EllipticPoint a(1), b(2); cout << "a = " << a; cout << "b = " << b; const EllipticPoint c = a + b; cout << "c = a + b = " << c; cout << "a + b - c = " << a + b - c; cout << "a + b - (b + a) = " << a + b - (b + a) << "\n"; cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a; cout << "a * 12345 = " << a * 12345; cout << "a * -12345 = " << a * -12345; cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345; cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345); cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n"; const EllipticPoint zero; EllipticPoint g; cout << "g = zero = " << g; cout << "g += a = " << (g+=a); cout << "g += zero = " << (g+=zero); cout << "g += b = " << (g+=b); cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n"; EllipticPoint special(0); cout << "special = " << special; cout << "special *= 2 = " << (special*=2); return 0; }
Ensure the translated C++ code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { return p } L := (3 * p.x * p.x) / (2 * p.y) x := L*L - 2*p.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func add(p, q pt) pt { if p.x == q.x && p.y == q.y { return dbl(p) } if is_zero(p) { return q } if is_zero(q) { return p } L := (q.y - p.y) / (q.x - p.x) x := L*L - p.x - q.x return pt{ x: x, y: L*(p.x-x) - p.y, } } func mul(p pt, n int) pt { r := zero() for i := 1; i <= n; i <<= 1 { if i&n != 0 { r = add(r, p) } p = dbl(p) } return r } func show(s string, p pt) { fmt.Printf("%s", s) if is_zero(p) { fmt.Println("Zero") } else { fmt.Printf("(%.3f, %.3f)\n", p.x, p.y) } } func from_y(y float64) pt { return pt{ x: math.Cbrt(y*y - bCoeff), y: y, } } func main() { a := from_y(1) b := from_y(2) show("a = ", a) show("b = ", b) c := add(a, b) show("c = a + b = ", c) d := neg(c) show("d = -c = ", d) show("c + d = ", add(c, d)) show("a + b + d = ", add(a, add(b, d))) show("a * 12345 = ", mul(a, 12345)) }
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { return; } if(m_y == 0) { *this = EllipticPoint(); } else { double L = (3 * m_x * m_x) / (2 * m_y); double newX = L * L - 2 * m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } } public: friend std::ostream& operator<<(std::ostream&, const EllipticPoint&); constexpr EllipticPoint() noexcept : m_x(0), m_y(ZeroThreshold * 1.01) {} explicit EllipticPoint(double yCoordinate) noexcept { m_y = yCoordinate; m_x = cbrt(m_y * m_y - B); } bool IsZero() const noexcept { bool isNotZero = abs(m_y) < ZeroThreshold; return !isNotZero; } EllipticPoint operator-() const noexcept { EllipticPoint negPt; negPt.m_x = m_x; negPt.m_y = -m_y; return negPt; } EllipticPoint& operator+=(const EllipticPoint& rhs) noexcept { if(IsZero()) { *this = rhs; } else if (rhs.IsZero()) { } else { double L = (rhs.m_y - m_y) / (rhs.m_x - m_x); if(isfinite(L)) { double newX = L * L - m_x - rhs.m_x; m_y = L * (m_x - newX) - m_y; m_x = newX; } else { if(signbit(m_y) != signbit(rhs.m_y)) { *this = EllipticPoint(); } else { Double(); } } } return *this; } EllipticPoint& operator-=(const EllipticPoint& rhs) noexcept { *this+= -rhs; return *this; } EllipticPoint& operator*=(int rhs) noexcept { EllipticPoint r; EllipticPoint p = *this; if(rhs < 0) { rhs = -rhs; p = -p; } for (int i = 1; i <= rhs; i <<= 1) { if (i & rhs) r += p; p.Double(); } *this = r; return *this; } }; inline EllipticPoint operator+(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += rhs; return lhs; } inline EllipticPoint operator-(EllipticPoint lhs, const EllipticPoint& rhs) noexcept { lhs += -rhs; return lhs; } inline EllipticPoint operator*(EllipticPoint lhs, const int rhs) noexcept { lhs *= rhs; return lhs; } inline EllipticPoint operator*(const int lhs, EllipticPoint rhs) noexcept { rhs *= lhs; return rhs; } ostream& operator<<(ostream& os, const EllipticPoint& pt) { if(pt.IsZero()) cout << "(Zero)\n"; else cout << "(" << pt.m_x << ", " << pt.m_y << ")\n"; return os; } int main(void) { const EllipticPoint a(1), b(2); cout << "a = " << a; cout << "b = " << b; const EllipticPoint c = a + b; cout << "c = a + b = " << c; cout << "a + b - c = " << a + b - c; cout << "a + b - (b + a) = " << a + b - (b + a) << "\n"; cout << "a + a + a + a + a - 5 * a = " << a + a + a + a + a - 5 * a; cout << "a * 12345 = " << a * 12345; cout << "a * -12345 = " << a * -12345; cout << "a * 12345 + a * -12345 = " << a * 12345 + a * -12345; cout << "a * 12345 - (a * 12000 + a * 345) = " << a * 12345 - (a * 12000 + a * 345); cout << "a * 12345 - (a * 12001 + a * 345) = " << a * 12345 - (a * 12000 + a * 344) << "\n"; const EllipticPoint zero; EllipticPoint g; cout << "g = zero = " << g; cout << "g += a = " << (g+=a); cout << "g += zero = " << (g+=zero); cout << "g += b = " << (g+=b); cout << "b + b - b * 2 = " << (b + b - b * 2) << "\n"; EllipticPoint special(0); cout << "special = " << special; cout << "special *= 2 = " << (special*=2); return 0; }
Transform the following Go implementation into C++, maintaining the same output and logic.
package main import ( "fmt" "strings" ) func main() { fmt.Println(strings.Count("the three truths", "th")) fmt.Println(strings.Count("ababababab", "abab")) }
#include <iostream> #include <string> int countSubstring(const std::string& str, const std::string& sub) { if (sub.length() == 0) return 0; int count = 0; for (size_t offset = str.find(sub); offset != std::string::npos; offset = str.find(sub, offset + sub.length())) { ++count; } return count; } int main() { std::cout << countSubstring("the three truths", "th") << '\n'; std::cout << countSubstring("ababababab", "abab") << '\n'; std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n'; return 0; }
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically?
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
Convert the following code from Go to C++, ensuring the logic remains intact.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
Change the following Go code into C++ without altering its purpose.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) } return r } func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) return } for i := index; i < n; i++ { check := shouldSwap(s, index, i) if check { s[index], s[i] = s[i], s[index] findPerms(s, index+1, n, res) s[index], s[i] = s[i], s[index] } } } func main() { primes := []byte{2, 3, 5, 7} var res []string for n := 3; n <= 6; n++ { reps := combrep(n, primes) for _, rep := range reps { sum := byte(0) for _, r := range rep { sum += r } if sum == 13 { var perms []string for i := 0; i < len(rep); i++ { rep[i] += 48 } findPerms(rep, 0, len(rep), &perms) res = append(res, perms...) } } } res2 := make([]int, len(res)) for i, r := range res { res2[i], _ = strconv.Atoi(r) } sort.Ints(res2) fmt.Println("Those numbers whose digits are all prime and sum to 13 are:") fmt.Println(res2) }
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) printf("%d%d ", get<0>(i), x); else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); } return 0; }
Ensure the translated C++ code behaves exactly like the original Go snippet.
package main import ( "fmt" "strings" ) func main() { c := "cat" d := "dog" if c == d { fmt.Println(c, "is bytewise identical to", d) } if c != d { fmt.Println(c, "is bytewise different from", d) } if c > d { fmt.Println(c, "is lexically bytewise greater than", d) } if c < d { fmt.Println(c, "is lexically bytewise less than", d) } if c >= d { fmt.Println(c, "is lexically bytewise greater than or equal to", d) } if c <= d { fmt.Println(c, "is lexically bytewise less than or equal to", d) } eqf := `when interpreted as UTF-8 and compared under Unicode simple case folding rules.` if strings.EqualFold(c, d) { fmt.Println(c, "equal to", d, eqf) } else { fmt.Println(c, "not equal to", d, eqf) } }
#include <algorithm> #include <iostream> #include <sstream> #include <string> template <typename T> void demo_compare(const T &a, const T &b, const std::string &semantically) { std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ") << "exactly " << semantically << " equal." << std::endl; std::cout << a << " and " << b << " are " << ((a != b) ? "" : "not ") << semantically << "inequal." << std::endl; std::cout << a << " is " << ((a < b) ? "" : "not ") << semantically << " ordered before " << b << '.' << std::endl; std::cout << a << " is " << ((a > b) ? "" : "not ") << semantically << " ordered after " << b << '.' << std::endl; } int main(int argc, char *argv[]) { std::string a((argc > 1) ? argv[1] : "1.2.Foo"); std::string b((argc > 2) ? argv[2] : "1.3.Bar"); demo_compare<std::string>(a, b, "lexically"); std::transform(a.begin(), a.end(), a.begin(), ::tolower); std::transform(b.begin(), b.end(), b.begin(), ::tolower); demo_compare<std::string>(a, b, "lexically"); double numA, numB; std::istringstream(a) >> numA; std::istringstream(b) >> numB; demo_compare<double>(numA, numB, "numerically"); return (a == b); }
Ensure the translated C++ code behaves exactly like the original Go snippet.
package main import ( "fmt" "io" "os" "strings" "time" ) func addNote(fn string, note string) error { f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return err } _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n") if cErr := f.Close(); err == nil { err = cErr } return err } func showNotes(w io.Writer, fn string) error { f, err := os.Open(fn) if err != nil { if os.IsNotExist(err) { return nil } return err } _, err = io.Copy(w, f) f.Close() return err } func main() { const fn = "NOTES.TXT" var err error if len(os.Args) > 1 { err = addNote(fn, strings.Join(os.Args[1:], " ")) } else { err = showNotes(os.Stdout, fn) } if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
Port the provided Go code into C++ while preserving the original functionality.
package main import ( "fmt" "io" "os" "strings" "time" ) func addNote(fn string, note string) error { f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) if err != nil { return err } _, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n") if cErr := f.Close(); err == nil { err = cErr } return err } func showNotes(w io.Writer, fn string) error { f, err := os.Open(fn) if err != nil { if os.IsNotExist(err) { return nil } return err } _, err = io.Copy(w, f) f.Close() return err } func main() { const fn = "NOTES.TXT" var err error if len(os.Args) > 1 { err = addNote(fn, strings.Join(os.Args[1:], " ")) } else { err = showNotes(os.Stdout, fn) } if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
#include <fstream> #include <iostream> #include <ctime> using namespace std; #define note_file "NOTES.TXT" int main(int argc, char **argv) { if(argc>1) { ofstream Notes(note_file, ios::app); time_t timer = time(NULL); if(Notes.is_open()) { Notes << asctime(localtime(&timer)) << '\t'; for(int i=1;i<argc;i++) Notes << argv[i] << ' '; Notes << endl; Notes.close(); } } else { ifstream Notes(note_file, ios::in); string line; if(Notes.is_open()) { while(!Notes.eof()) { getline(Notes, line); cout << line << endl; } Notes.close(); } } }
Write the same algorithm in C++ as shown in this Go implementation.
package main import ( "fmt" "math" ) func main() { const nn = 32 const step = .05 xVal := make([]float64, nn) tSin := make([]float64, nn) tCos := make([]float64, nn) tTan := make([]float64, nn) for i := range xVal { xVal[i] = float64(i) * step tSin[i], tCos[i] = math.Sincos(xVal[i]) tTan[i] = tSin[i] / tCos[i] } iSin := thieleInterpolator(tSin, xVal) iCos := thieleInterpolator(tCos, xVal) iTan := thieleInterpolator(tTan, xVal) fmt.Printf("%16.14f\n", 6*iSin(.5)) fmt.Printf("%16.14f\n", 3*iCos(.5)) fmt.Printf("%16.14f\n", 4*iTan(1)) } func thieleInterpolator(x, y []float64) func(float64) float64 { n := len(x) ρ := make([][]float64, n) for i := range ρ { ρ[i] = make([]float64, n-i) ρ[i][0] = y[i] } for i := 0; i < n-1; i++ { ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]) } for i := 2; i < n; i++ { for j := 0; j < n-i; j++ { ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2] } } ρ0 := ρ[0] return func(xin float64) float64 { var a float64 for i := n - 1; i > 1; i-- { a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a) } return y[0] + (xin-x[0])/(ρ0[1]+a) } }
#include <cmath> #include <iostream> #include <iomanip> #include <string.h> constexpr unsigned int N = 32u; double xval[N], t_sin[N], t_cos[N], t_tan[N]; constexpr unsigned int N2 = N * (N - 1u) / 2u; double r_sin[N2], r_cos[N2], r_tan[N2]; double ρ(double *x, double *y, double *r, int i, int n) { if (n < 0) return 0; if (!n) return y[i]; unsigned int idx = (N - 1 - n) * (N - n) / 2 + i; if (r[idx] != r[idx]) r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2); return r[idx]; } double thiele(double *x, double *y, double *r, double xin, unsigned int n) { return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1); } inline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); } inline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); } inline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); } int main() { constexpr double step = .05; for (auto i = 0u; i < N; i++) { xval[i] = i * step; t_sin[i] = sin(xval[i]); t_cos[i] = cos(xval[i]); t_tan[i] = t_sin[i] / t_cos[i]; } for (auto i = 0u; i < N2; i++) r_sin[i] = r_cos[i] = r_tan[i] = NAN; std::cout << std::setw(16) << std::setprecision(25) << 6 * i_sin(.5) << std::endl << 3 * i_cos(.5) << std::endl << 4 * i_tan(1.) << std::endl; return 0; }
Generate a C++ translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s  %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d  %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s)) } }
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
Write the same code in C++ as shown below in Go.
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s  %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d  %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s)) } }
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
Keep all operations the same but rewrite the snippet in C++.
package main import ( "fmt" "math" ) func entropy(s string) float64 { m := map[rune]float64{} for _, r := range s { m[r]++ } hm := 0. for _, c := range m { hm += c * math.Log2(c) } l := float64(len(s)) return math.Log2(l) - hm/l } const F_Word1 = "1" const F_Word2 = "0" func FibonacciWord(n int) string { a, b := F_Word1, F_Word2 for ; n > 1; n-- { a, b = b, b+a } return a } func FibonacciWordGen() <-chan string { ch := make(chan string) go func() { a, b := F_Word1, F_Word2 for { ch <- a a, b = b, b+a } }() return ch } func main() { fibWords := FibonacciWordGen() fmt.Printf("%3s %9s  %-18s %s\n", "N", "Length", "Entropy", "Word") n := 1 for ; n < 10; n++ { s := <-fibWords if s2 := FibonacciWord(n); s != s2 { fmt.Printf("For %d, generator produced %q, function produced %q\n", n, s, s2) } fmt.Printf("%3d %9d  %.16f %s\n", n, len(s), entropy(s), s) } for ; n <= 37; n++ { s := <-fibWords fmt.Printf("%3d %9d  %.16f\n", n, len(s), entropy(s)) } }
#include <string> #include <map> #include <iostream> #include <algorithm> #include <cmath> #include <iomanip> double log2( double number ) { return ( log( number ) / log( 2 ) ) ; } double find_entropy( std::string & fiboword ) { std::map<char , int> frequencies ; std::for_each( fiboword.begin( ) , fiboword.end( ) , [ & frequencies ]( char c ) { frequencies[ c ]++ ; } ) ; int numlen = fiboword.length( ) ; double infocontent = 0 ; for ( std::pair<char , int> p : frequencies ) { double freq = static_cast<double>( p.second ) / numlen ; infocontent += freq * log2( freq ) ; } infocontent *= -1 ; return infocontent ; } void printLine( std::string &fiboword , int n ) { std::cout << std::setw( 5 ) << std::left << n ; std::cout << std::setw( 12 ) << std::right << fiboword.size( ) ; std::cout << " " << std::setw( 16 ) << std::setprecision( 13 ) << std::left << find_entropy( fiboword ) ; std::cout << "\n" ; } int main( ) { std::cout << std::setw( 5 ) << std::left << "N" ; std::cout << std::setw( 12 ) << std::right << "length" ; std::cout << " " << std::setw( 16 ) << std::left << "entropy" ; std::cout << "\n" ; std::string firststring ( "1" ) ; int n = 1 ; printLine( firststring , n ) ; std::string secondstring( "0" ) ; n++ ; printLine( secondstring , n ) ; while ( n < 37 ) { std::string resultstring = firststring + secondstring ; firststring.assign( secondstring ) ; secondstring.assign( resultstring ) ; n++ ; printLine( resultstring , n ) ; } return 0 ; }
Rewrite this program in C++ while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" "strconv" "strings" ) func d2d(d float64) float64 { return math.Mod(d, 360) } func g2g(g float64) float64 { return math.Mod(g, 400) } func m2m(m float64) float64 { return math.Mod(m, 6400) } func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) } func d2g(d float64) float64 { return d2d(d) * 400 / 360 } func d2m(d float64) float64 { return d2d(d) * 6400 / 360 } func d2r(d float64) float64 { return d2d(d) * math.Pi / 180 } func g2d(g float64) float64 { return g2g(g) * 360 / 400 } func g2m(g float64) float64 { return g2g(g) * 6400 / 400 } func g2r(g float64) float64 { return g2g(g) * math.Pi / 200 } func m2d(m float64) float64 { return m2m(m) * 360 / 6400 } func m2g(m float64) float64 { return m2m(m) * 400 / 6400 } func m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 } func r2d(r float64) float64 { return r2r(r) * 180 / math.Pi } func r2g(r float64) float64 { return r2r(r) * 200 / math.Pi } func r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi } func s(f float64) string { wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), ".") if len(wf) == 1 { return fmt.Sprintf("%7s ", wf[0]) } le := len(wf[1]) if le > 7 { le = 7 } return fmt.Sprintf("%7s.%-7s", wf[0], wf[1][:le]) } func main() { angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ft := "%s %s %s %s %s\n" fmt.Printf(ft, " degrees ", "normalized degs", " gradians ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a))) } fmt.Printf(ft, "\n gradians ", "normalized grds", " degrees ", " mils ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a))) } fmt.Printf(ft, "\n mils ", "normalized mils", " degrees ", " gradians ", " radians") for _, a := range angles { fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a))) } fmt.Printf(ft, "\n radians ", "normalized rads", " degrees ", " gradians ", " mils ") for _, a := range angles { fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(a))) } }
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(double a) { return normalize<double>(a, 400); } inline double m2m(double a) { return normalize<double>(a, 6400); } inline double r2r(double a) { return normalize<double>(a, 2*M_PI); } double d2g(double a) { return g2g(a * 10 / 9); } double d2m(double a) { return m2m(a * 160 / 9); } double d2r(double a) { return r2r(a * M_PI / 180); } double g2d(double a) { return d2d(a * 9 / 10); } double g2m(double a) { return m2m(a * 16); } double g2r(double a) { return r2r(a * M_PI / 200); } double m2d(double a) { return d2d(a * 9 / 160); } double m2g(double a) { return g2g(a / 16); } double m2r(double a) { return r2r(a * M_PI / 3200); } double r2d(double a) { return d2d(a * 180 / M_PI); } double r2g(double a) { return g2g(a * 200 / M_PI); } double r2m(double a) { return m2m(a * 3200 / M_PI); } void print(const std::vector<double> &values, const char *s, std::function<double(double)> f) { using namespace std; ostringstream out; out << " ┌───────────────────┐\n"; out << " │ " << setw(17) << s << " │\n"; out << "┌─────────────────┼───────────────────┤\n"; for (double i : values) out << "│ " << setw(15) << fixed << i << defaultfloat << " │ " << setw(17) << fixed << f(i) << defaultfloat << " │\n"; out << "└─────────────────┴───────────────────┘\n"; auto str = out.str(); boost::algorithm::replace_all(str, ".000000", " "); cout << str; } int main() { std::vector<double> values = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 }; print(values, "normalized (deg)", d2d); print(values, "normalized (grad)", g2g); print(values, "normalized (mil)", m2m); print(values, "normalized (rad)", r2r); print(values, "deg -> grad ", d2g); print(values, "deg -> mil ", d2m); print(values, "deg -> rad ", d2r); print(values, "grad -> deg ", g2d); print(values, "grad -> mil ", g2m); print(values, "grad -> rad ", g2r); print(values, "mil -> deg ", m2d); print(values, "mil -> grad ", m2g); print(values, "mil -> rad ", m2r); print(values, "rad -> deg ", r2d); print(values, "rad -> grad ", r2g); print(values, "rad -> mil ", r2m); return 0; }
Change the following Go code into C++ without altering its purpose.
package main import ( "fmt" "os" "path" ) func CommonPrefix(sep byte, paths ...string) string { switch len(paths) { case 0: return "" case 1: return path.Clean(paths[0]) } c := []byte(path.Clean(paths[0])) c = append(c, sep) for _, v := range paths[1:] { v = path.Clean(v) + string(sep) if len(v) < len(c) { c = c[:len(v)] } for i := 0; i < len(c); i++ { if v[i] != c[i] { c = c[:i] break } } } for i := len(c) - 1; i >= 0; i-- { if c[i] == sep { c = c[:i] break } } return string(c) } func main() { c := CommonPrefix(os.PathSeparator, "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", "/home "/home/user1/././tmp/covertly/foo", "/home/bob/../user1/tmp/coved/bar", ) if c == "" { fmt.Println("No common path") } else { fmt.Println("Common path:", c) } }
#include <algorithm> #include <iostream> #include <string> #include <vector> std::string longestPath( const std::vector<std::string> & , char ) ; int main( ) { std::string dirs[ ] = { "/home/user1/tmp/coverage/test" , "/home/user1/tmp/covert/operator" , "/home/user1/tmp/coven/members" } ; std::vector<std::string> myDirs ( dirs , dirs + 3 ) ; std::cout << "The longest common path of the given directories is " << longestPath( myDirs , '/' ) << "!\n" ; return 0 ; } std::string longestPath( const std::vector<std::string> & dirs , char separator ) { std::vector<std::string>::const_iterator vsi = dirs.begin( ) ; int maxCharactersCommon = vsi->length( ) ; std::string compareString = *vsi ; for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) { std::pair<std::string::const_iterator , std::string::const_iterator> p = std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ; if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) maxCharactersCommon = p.first - compareString.begin( ) ; } std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ; return compareString.substr( 0 , found ) ; }
Convert the following code from Go to C++, ensuring the logic remains intact.
package main import ( "fmt" "math" "math/rand" "time" ) func dice5() int { return rand.Intn(5) + 1 } func dice7() (i int) { for { i = 5*dice5() + dice5() if i < 27 { break } } return (i / 3) - 1 } func distCheck(f func() int, n int, repeats int, delta float64) (max float64, flatEnough bool) { count := make([]int, n) for i := 0; i < repeats; i++ { count[f()-1]++ } expected := float64(repeats) / float64(n) for _, c := range count { max = math.Max(max, math.Abs(float64(c)-expected)) } return max, max < delta } func main() { rand.Seed(time.Now().UnixNano()) const calls = 1000000 max, flatEnough := distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) max, flatEnough = distCheck(dice7, 7, calls, 500) fmt.Println("Max delta:", max, "Flat enough:", flatEnough) }
#include <map> #include <iostream> #include <cmath> template<typename F> bool test_distribution(F f, int calls, double delta) { typedef std::map<int, int> distmap; distmap dist; for (int i = 0; i < calls; ++i) ++dist[f()]; double mean = 1.0/dist.size(); bool good = true; for (distmap::iterator i = dist.begin(); i != dist.end(); ++i) { if (std::abs((1.0 * i->second)/calls - mean) > delta) { std::cout << "Relative frequency " << i->second/(1.0*calls) << " of result " << i->first << " deviates by more than " << delta << " from the expected value " << mean << "\n"; good = false; } } return good; }
Produce a language-to-language conversion: from Go to C++, same semantics.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
Produce a language-to-language conversion: from Go to C++, same semantics.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64(int64(1)) } var t big.Int for n := 1; n <= limit; n++ { for k := 1; k <= n; k++ { t.SetInt64(int64(k)) t.Mul(&t, s2[n-1][k]) s2[n][k].Add(&t, s2[n-1][k-1]) } } fmt.Println("Stirling numbers of the second kind: S2(n, k):") fmt.Printf("n/k") for i := 0; i <= last; i++ { fmt.Printf("%9d ", i) } fmt.Printf("\n--") for i := 0; i <= last; i++ { fmt.Printf("----------") } fmt.Println() for n := 0; n <= last; n++ { fmt.Printf("%2d ", n) for k := 0; k <= n; k++ { fmt.Printf("%9d ", s2[n][k]) } fmt.Println() } fmt.Println("\nMaximum value from the S2(100, *) row:") max := new(big.Int).Set(s2[limit][0]) for k := 1; k <= limit; k++ { if s2[limit][k].Cmp(max) > 0 { max.Set(s2[limit][k]) } } fmt.Println(max) fmt.Printf("which has %d digits.\n", len(max.String())) }
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; if (k == 0 || k > n) return 0; auto p = std::make_pair(n, k); auto i = cache_.find(p); if (i != cache_.end()) return i->second; integer s = k * get(n - 1, k) + get(n - 1, k - 1); cache_.emplace(p, s); return s; } void print_stirling_numbers(stirling2& s2, int n) { std::cout << "Stirling numbers of the second kind:\nn/k"; for (int j = 0; j <= n; ++j) { std::cout << std::setw(j == 0 ? 2 : 8) << j; } std::cout << '\n'; for (int i = 0; i <= n; ++i) { std::cout << std::setw(2) << i << ' '; for (int j = 0; j <= i; ++j) std::cout << std::setw(j == 0 ? 2 : 8) << s2.get(i, j); std::cout << '\n'; } } int main() { stirling2 s2; print_stirling_numbers(s2, 12); std::cout << "Maximum value of S2(n,k) where n == 100:\n"; integer max = 0; for (int k = 0; k <= 100; ++k) max = std::max(max, s2.get(100, k)); std::cout << max << '\n'; return 0; }
Convert this Go block to C++, preserving its control flow and logic.
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
Translate the given Go code snippet into C++ without altering its behavior.
package main import "fmt" func main() { a := []int{0} used := make(map[int]bool, 1001) used[0] = true used1000 := make(map[int]bool, 1001) used1000[0] = true for n, foundDup := 1, false; n <= 15 || !foundDup || len(used1000) < 1001; n++ { next := a[n-1] - n if next < 1 || used[next] { next += 2 * n } alreadyUsed := used[next] a = append(a, next) if !alreadyUsed { used[next] = true if next >= 0 && next <= 1000 { used1000[next] = true } } if n == 14 { fmt.Println("The first 15 terms of the Recaman's sequence are:", a) } if !foundDup && alreadyUsed { fmt.Printf("The first duplicated term is a[%d] = %d\n", n, next) foundDup = true } if len(used1000) == 1001 { fmt.Printf("Terms up to a[%d] are needed to generate 0 to 1000\n", n) } } }
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { os << ", " << *i; i = std::next(i); } return os << ']'; } int main() { using namespace std; vector<int> a{ 0 }; set<int> used{ 0 }; set<int> used1000{ 0 }; bool foundDup = false; int n = 1; while (n <= 15 || !foundDup || used1000.size() < 1001) { int next = a[n - 1] - n; if (next < 1 || used.find(next) != used.end()) { next += 2 * n; } bool alreadyUsed = used.find(next) != used.end(); a.push_back(next); if (!alreadyUsed) { used.insert(next); if (0 <= next && next <= 1000) { used1000.insert(next); } } if (n == 14) { cout << "The first 15 terms of the Recaman sequence are: " << a << '\n'; } if (!foundDup && alreadyUsed) { cout << "The first duplicated term is a[" << n << "] = " << next << '\n'; foundDup = true; } if (used1000.size() == 1001) { cout << "Terms up to a[" << n << "] are needed to generate 0 to 1000\n"; } n++; } return 0; }
Can you help me rewrite this code in C++ instead of Go, keeping it the same logically?
func inc(n int) { x := n + 1 println(x) }
#include <string> int main() { int* p; p = new int; delete p; p = new int(2); delete p; std::string* p2; p2 = new std::string; delete p2; p = new int[10]; delete[] p; p2 = new std::string[10]; delete[] p2; }
Write the same algorithm in C++ as shown in this Go implementation.
package main import ( "bufio" "fmt" "math/rand" "os" "strings" ) var b []byte func printBoard() { fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9]) } var pScore, cScore int var pMark, cMark byte = 'X', 'O' var in = bufio.NewReader(os.Stdin) func main() { b = make([]byte, 9) fmt.Println("Play by entering a digit.") for { for i := range b { b[i] = '1' + byte(i) } computerStart := cMark == 'X' if computerStart { fmt.Println("I go first, playing X's") } else { fmt.Println("You go first, playing X's") } TakeTurns: for { if !computerStart { if !playerTurn() { return } if gameOver() { break TakeTurns } } computerStart = false computerTurn() if gameOver() { break TakeTurns } } fmt.Println("Score: you", pScore, "me", cScore) fmt.Println("\nLet's play again.") } } func playerTurn() bool { var pm string var err error for i := 0; i < 3; i++ { printBoard() fmt.Printf("%c's move? ", pMark) if pm, err = in.ReadString('\n'); err != nil { fmt.Println(err) return false } pm = strings.TrimSpace(pm) if pm >= "1" && pm <= "9" && b[pm[0]-'1'] == pm[0] { x := pm[0] - '1' b[x] = pMark return true } } fmt.Println("You're not playing right.") return false } var choices = make([]int, 9) func computerTurn() { printBoard() var x int defer func() { fmt.Println("My move:", x+1) b[x] = cMark }() block := -1 for _, l := range lines { var mine, yours int x = -1 for _, sq := range l { switch b[sq] { case cMark: mine++ case pMark: yours++ default: x = sq } } if mine == 2 && x >= 0 { return } if yours == 2 && x >= 0 { block = x } } if block >= 0 { x = block return } choices = choices[:0] for i, sq := range b { if sq == '1'+byte(i) { choices = append(choices, i) } } x = choices[rand.Intn(len(choices))] } func gameOver() bool { for _, l := range lines { if b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]] { printBoard() if b[l[0]] == cMark { fmt.Println("I win!") cScore++ pMark, cMark = 'X', 'O' } else { fmt.Println("You win!") pScore++ pMark, cMark = 'O', 'X' } return true } } for i, sq := range b { if sq == '1'+byte(i) { return false } } fmt.Println("Cat game.") pMark, cMark = cMark, pMark return true } var lines = [][]int{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}, }
#include <windows.h> #include <iostream> #include <string> using namespace std; enum players { Computer, Human, Draw, None }; const int iWin[8][3] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, { 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, { 0, 4, 8 }, { 2, 4, 6 } }; class ttt { public: ttt() { _p = rand() % 2; reset(); } void play() { int res = Draw; while( true ) { drawGrid(); while( true ) { if( _p ) getHumanMove(); else getComputerMove(); drawGrid(); res = checkVictory(); if( res != None ) break; ++_p %= 2; } if( res == Human ) cout << "CONGRATULATIONS HUMAN --- You won!"; else if( res == Computer ) cout << "NOT SO MUCH A SURPRISE --- I won!"; else cout << "It's a draw!"; cout << endl << endl; string r; cout << "Play again( Y / N )? "; cin >> r; if( r != "Y" && r != "y" ) return; ++_p %= 2; reset(); } } private: void reset() { for( int x = 0; x < 9; x++ ) _field[x] = None; } void drawGrid() { system( "cls" ); COORD c = { 0, 2 }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); cout << " 1 | 2 | 3 " << endl; cout << "---+---+---" << endl; cout << " 4 | 5 | 6 " << endl; cout << "---+---+---" << endl; cout << " 7 | 8 | 9 " << endl << endl << endl; int f = 0; for( int y = 0; y < 5; y += 2 ) for( int x = 1; x < 11; x += 4 ) { if( _field[f] != None ) { COORD c = { x, 2 + y }; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); string o = _field[f] == Computer ? "X" : "O"; cout << o; } f++; } c.Y = 9; SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), c ); } int checkVictory() { for( int i = 0; i < 8; i++ ) { if( _field[iWin[i][0]] != None && _field[iWin[i][0]] == _field[iWin[i][1]] && _field[iWin[i][1]] == _field[iWin[i][2]] ) { return _field[iWin[i][0]]; } } int i = 0; for( int f = 0; f < 9; f++ ) { if( _field[f] != None ) i++; } if( i == 9 ) return Draw; return None; } void getHumanMove() { int m; cout << "Enter your move ( 1 - 9 ) "; while( true ) { m = 0; do { cin >> m; } while( m < 1 && m > 9 ); if( _field[m - 1] != None ) cout << "Invalid move. Try again!" << endl; else break; } _field[m - 1] = Human; } void getComputerMove() { int move = 0; do{ move = rand() % 9; } while( _field[move] != None ); for( int i = 0; i < 8; i++ ) { int try1 = iWin[i][0], try2 = iWin[i][1], try3 = iWin[i][2]; if( _field[try1] != None && _field[try1] == _field[try2] && _field[try3] == None ) { move = try3; if( _field[try1] == Computer ) break; } if( _field[try1] != None && _field[try1] == _field[try3] && _field[try2] == None ) { move = try2; if( _field[try1] == Computer ) break; } if( _field[try2] != None && _field[try2] == _field[try3] && _field[try1] == None ) { move = try1; if( _field[try2] == Computer ) break; } } _field[move] = Computer; } int _p; int _field[9]; }; int main( int argc, char* argv[] ) { srand( GetTickCount() ); ttt tic; tic.play(); return 0; }
Ensure the translated C++ code behaves exactly like the original Go snippet.
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
Convert this Go snippet to C++ and keep its semantics consistent.
package main import "fmt" func main() { for i := 1;; i++ { fmt.Println(i) } }
#include <cstdint> #include <iostream> #include <limits> int main() { auto i = std::uintmax_t{}; while (i < std::numeric_limits<decltype(i)>::max()) std::cout << ++i << '\n'; }
Port the provided Go code into C++ while preserving the original functionality.
package main import ( "fmt" "io/ioutil" "log" "math" "os" "runtime" ) func main() { _, src, _, _ := runtime.Caller(0) fmt.Println("Source file entropy:", entropy(src)) fmt.Println("Binary file entropy:", entropy(os.Args[0])) } func entropy(file string) float64 { d, err := ioutil.ReadFile(file) if err != nil { log.Fatal(err) } var f [256]float64 for _, b := range d { f[b]++ } hm := 0. for _, c := range f { if c > 0 { hm += c * math.Log2(c) } } l := float64(len(d)) return math.Log2(l) - hm/l }
#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; }
Port the following code from Go to PHP with equivalent syntax and logic.
package main import "fmt" func bitwise(a, b int16) { fmt.Printf("a: %016b\n", uint16(a)) fmt.Printf("b: %016b\n", uint16(b)) fmt.Printf("and: %016b\n", uint16(a&b)) fmt.Printf("or: %016b\n", uint16(a|b)) fmt.Printf("xor: %016b\n", uint16(a^b)) fmt.Printf("not: %016b\n", uint16(^a)) if b < 0 { fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).") return } ua := uint16(a) ub := uint32(b) fmt.Printf("shl: %016b\n", uint16(ua<<ub)) fmt.Printf("shr: %016b\n", uint16(ua>>ub)) fmt.Printf("las: %016b\n", uint16(a<<ub)) fmt.Printf("ras: %016b\n", uint16(a>>ub)) fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub)))) fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub))) } func main() { var a, b int16 = -460, 6 bitwise(a, b) }
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Maintain the same structure and functionality when rewriting this code in PHP.
package main import "fmt" func bitwise(a, b int16) { fmt.Printf("a: %016b\n", uint16(a)) fmt.Printf("b: %016b\n", uint16(b)) fmt.Printf("and: %016b\n", uint16(a&b)) fmt.Printf("or: %016b\n", uint16(a|b)) fmt.Printf("xor: %016b\n", uint16(a^b)) fmt.Printf("not: %016b\n", uint16(^a)) if b < 0 { fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).") return } ua := uint16(a) ub := uint32(b) fmt.Printf("shl: %016b\n", uint16(ua<<ub)) fmt.Printf("shr: %016b\n", uint16(ua>>ub)) fmt.Printf("las: %016b\n", uint16(a<<ub)) fmt.Printf("ras: %016b\n", uint16(a>>ub)) fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub)))) fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub))) } func main() { var a, b int16 = -460, 6 bitwise(a, b) }
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Produce a functionally identical PHP code for the snippet given in Go.
package main import ( "bufio" "fmt" "log" "os" ) func init() { log.SetFlags(log.Lshortfile) } func main() { inputFile, err := os.Open("byline.go") if err != nil { log.Fatal("Error opening input file:", err) } defer inputFile.Close() scanner := bufio.NewScanner(inputFile) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(scanner.Err()) } }
<?php $file = fopen(__FILE__, 'r'); // read current file while ($line = fgets($file)) { $line = rtrim($line); // removes linebreaks and spaces at end echo strrev($line) . "\n"; // reverse line and upload it }
Convert this Go snippet to PHP and keep its semantics consistent.
package main import ( "bufio" "fmt" "log" "os" ) func init() { log.SetFlags(log.Lshortfile) } func main() { inputFile, err := os.Open("byline.go") if err != nil { log.Fatal("Error opening input file:", err) } defer inputFile.Close() scanner := bufio.NewScanner(inputFile) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(scanner.Err()) } }
<?php $file = fopen(__FILE__, 'r'); // read current file while ($line = fgets($file)) { $line = rtrim($line); // removes linebreaks and spaces at end echo strrev($line) . "\n"; // reverse line and upload it }
Rewrite the snippet below in PHP so it works the same as the original Go code.
package main import ( "fmt" "math/big" "strconv" ) func main () { s := strconv.FormatInt(26, 16) fmt.Println(s) i, err := strconv.ParseInt("1a", 16, 64) if err == nil { fmt.Println(i) } b, ok := new(big.Int).SetString("1a", 16) if ok { fmt.Println(b) } }
base_convert("26", 10, 16); // returns "1a"
Write a version of this Go function in PHP with identical behavior.
package main import ( "fmt" "math/big" "strconv" ) func main () { s := strconv.FormatInt(26, 16) fmt.Println(s) i, err := strconv.ParseInt("1a", 16, 64) if err == nil { fmt.Println(i) } b, ok := new(big.Int).SetString("1a", 16) if ok { fmt.Println(b) } }
base_convert("26", 10, 16); // returns "1a"
Write a version of this Go function in PHP with identical behavior.
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Change the following Go code into PHP without altering its purpose.
package main import ( "fmt" "os" "path/filepath" ) func VisitFile(fp string, fi os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if fi.IsDir() { return nil } matched, err := filepath.Match("*.mp3", fi.Name()) if err != nil { fmt.Println(err) return err } if matched { fmt.Println(fp) } return nil } func main() { filepath.Walk("/", VisitFile) }
function findFiles($dir = '.', $pattern = '/./'){ $prefix = $dir . '/'; $dir = dir($dir); while (false !== ($file = $dir->read())){ if ($file === '.' || $file === '..') continue; $file = $prefix . $file; if (is_dir($file)) findFiles($file, $pattern); if (preg_match($pattern, $file)){ echo $file . "\n"; } } } findFiles('./foo', '/\.bar$/');
Transform the following Go implementation into PHP, maintaining the same output and logic.
package main import ( "fmt" "hash/crc32" ) func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));
Convert this Go block to PHP, preserving its control flow and logic.
package main import ( "fmt" "hash/crc32" ) func main() { s := []byte("The quick brown fox jumps over the lazy dog") result := crc32.ChecksumIEEE(s) fmt.Printf("%X\n", result) }
printf("%x\n", crc32("The quick brown fox jumps over the lazy dog"));
Can you help me rewrite this code in PHP instead of Go, keeping it the same logically?
package main import "fmt" type picnicBasket struct { nServings int corkscrew bool } func (b *picnicBasket) happy() bool { return b.nServings > 1 && b.corkscrew } func newPicnicBasket(nPeople int) *picnicBasket { return &picnicBasket{nPeople, nPeople > 0} } func main() { var pb picnicBasket pbl := picnicBasket{} pbp := &picnicBasket{} pbn := new(picnicBasket) forTwo := newPicnicBasket(2) forToo := &picnicBasket{nServings: 2, corkscrew: true} fmt.Println(pb.nServings, pb.corkscrew) fmt.Println(pbl.nServings, pbl.corkscrew) fmt.Println(pbp) fmt.Println(pbn) fmt.Println(forTwo) fmt.Println(forToo) }
class MyClass { public static $classVar; public $instanceVar; // can also initialize it here function __construct() { $this->instanceVar = 0; } function someMethod() { $this->instanceVar = 1; self::$classVar = 3; } } $myObj = new MyClass();
Please provide an equivalent version of this Go code in PHP.
package main import "fmt" type picnicBasket struct { nServings int corkscrew bool } func (b *picnicBasket) happy() bool { return b.nServings > 1 && b.corkscrew } func newPicnicBasket(nPeople int) *picnicBasket { return &picnicBasket{nPeople, nPeople > 0} } func main() { var pb picnicBasket pbl := picnicBasket{} pbp := &picnicBasket{} pbn := new(picnicBasket) forTwo := newPicnicBasket(2) forToo := &picnicBasket{nServings: 2, corkscrew: true} fmt.Println(pb.nServings, pb.corkscrew) fmt.Println(pbl.nServings, pbl.corkscrew) fmt.Println(pbp) fmt.Println(pbn) fmt.Println(forTwo) fmt.Println(forToo) }
class MyClass { public static $classVar; public $instanceVar; // can also initialize it here function __construct() { $this->instanceVar = 0; } function someMethod() { $this->instanceVar = 1; self::$classVar = 3; } } $myObj = new MyClass();
Rewrite the snippet below in PHP so it works the same as the original Go code.
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
Transform the following Go implementation into PHP, maintaining the same output and logic.
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
Keep all operations the same but rewrite the snippet in PHP.
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
Change the following Go code into PHP without altering its purpose.
package main import ( "fmt" "strconv" ) func kaprekar(n uint64, base uint64) (bool, int) { order := 0 if n == 1 { return true, -1 } nn, power := n*n, uint64(1) for power <= nn { power *= base order++ } power /= base order-- for ; power > 1; power /= base { q, r := nn/power, nn%power if q >= n { return false, -1 } if q+r == n { return true, order } order-- } return false, -1 } func main() { max := uint64(10000) fmt.Printf("Kaprekar numbers < %d:\n", max) for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { fmt.Println(" ", m) } } max = 1e6 var count int for m := uint64(0); m < max; m++ { if is, _ := kaprekar(m, 10); is { count++ } } fmt.Printf("\nThere are %d Kaprekar numbers < %d.\n", count, max) const base = 17 maxB := "1000000" fmt.Printf("\nKaprekar numbers between 1 and %s(base %d):\n", maxB, base) max, _ = strconv.ParseUint(maxB, base, 64) fmt.Printf("\n Base 10 Base %d Square Split\n", base) for m := uint64(2); m < max; m++ { is, pos := kaprekar(m, base) if !is { continue } sq := strconv.FormatUint(m*m, base) str := strconv.FormatUint(m, base) split := len(sq)-pos fmt.Printf("%8d %7s %12s %6s + %s\n", m, str, sq, sq[:split], sq[split:]) } }
set_time_limit(300); print_r(array_filter(range(1, 10000), 'isKaprekar')); echo count(array_filter(range(1, 1000000), 'isKaprekar')); function isKaprekar($n) { $a = $n * $n; $b = bcmod("$a", "10"); for ($d = 1, $t = 0; $a > 0; $d *= 10) { $b += $t * $d; if ($b > $n) break; $a = floor($a / 10); if ($b && $a + $b == $n) return true; $t = bcmod("$a", "10"); } return false; }
Write the same code in PHP as shown below in Go.
package main import ( "fmt" "log" "strings" ) func compress(uncompressed string) []int { dictSize := 256 dictionary := make(map[string]int, dictSize) for i := 0; i < dictSize; i++ { dictionary[string([]byte{byte(i)})] = i } var result []int var w []byte for i := 0; i < len(uncompressed); i++ { c := uncompressed[i] wc := append(w, c) if _, ok := dictionary[string(wc)]; ok { w = wc } else { result = append(result, dictionary[string(w)]) dictionary[string(wc)] = dictSize dictSize++ wc[0] = c w = wc[:1] } } if len(w) > 0 { result = append(result, dictionary[string(w)]) } return result } type BadSymbolError int func (e BadSymbolError) Error() string { return fmt.Sprint("Bad compressed symbol ", int(e)) } func decompress(compressed []int) (string, error) { dictSize := 256 dictionary := make(map[int][]byte, dictSize) for i := 0; i < dictSize; i++ { dictionary[i] = []byte{byte(i)} } var result strings.Builder var w []byte for _, k := range compressed { var entry []byte if x, ok := dictionary[k]; ok { entry = x[:len(x):len(x)] } else if k == dictSize && len(w) > 0 { entry = append(w, w[0]) } else { return result.String(), BadSymbolError(k) } result.Write(entry) if len(w) > 0 { w = append(w, entry[0]) dictionary[dictSize] = w dictSize++ } w = entry } return result.String(), nil } func main() { compressed := compress("TOBEORNOTTOBEORTOBEORNOT") fmt.Println(compressed) decompressed, err := decompress(compressed) if err != nil { log.Fatal(err) } fmt.Println(decompressed) }
class LZW { function compress($unc) { $i;$c;$wc; $w = ""; $dictionary = array(); $result = array(); $dictSize = 256; for ($i = 0; $i < 256; $i += 1) { $dictionary[chr($i)] = $i; } for ($i = 0; $i < strlen($unc); $i++) { $c = $unc[$i]; $wc = $w.$c; if (array_key_exists($w.$c, $dictionary)) { $w = $w.$c; } else { array_push($result,$dictionary[$w]); $dictionary[$wc] = $dictSize++; $w = (string)$c; } } if ($w !== "") { array_push($result,$dictionary[$w]); } return implode(",",$result); } function decompress($com) { $com = explode(",",$com); $i;$w;$k;$result; $dictionary = array(); $entry = ""; $dictSize = 256; for ($i = 0; $i < 256; $i++) { $dictionary[$i] = chr($i); } $w = chr($com[0]); $result = $w; for ($i = 1; $i < count($com);$i++) { $k = $com[$i]; if (isset($dictionary[$k])) { $entry = $dictionary[$k]; } else { if ($k === $dictSize) { $entry = $w.$w[0]; } else { return null; } } $result .= $entry; $dictionary[$dictSize++] = $w . $entry[0]; $w = $entry; } return $result; } } $str = 'TOBEORNOTTOBEORTOBEORNOT'; $lzw = new LZW(); $com = $lzw->compress($str); $dec = $lzw->decompress($com); echo $com . "<br>" . $dec;
Convert the following code from Go to PHP, ensuring the logic remains intact.
package main import ( "fmt" "log" "strings" ) func compress(uncompressed string) []int { dictSize := 256 dictionary := make(map[string]int, dictSize) for i := 0; i < dictSize; i++ { dictionary[string([]byte{byte(i)})] = i } var result []int var w []byte for i := 0; i < len(uncompressed); i++ { c := uncompressed[i] wc := append(w, c) if _, ok := dictionary[string(wc)]; ok { w = wc } else { result = append(result, dictionary[string(w)]) dictionary[string(wc)] = dictSize dictSize++ wc[0] = c w = wc[:1] } } if len(w) > 0 { result = append(result, dictionary[string(w)]) } return result } type BadSymbolError int func (e BadSymbolError) Error() string { return fmt.Sprint("Bad compressed symbol ", int(e)) } func decompress(compressed []int) (string, error) { dictSize := 256 dictionary := make(map[int][]byte, dictSize) for i := 0; i < dictSize; i++ { dictionary[i] = []byte{byte(i)} } var result strings.Builder var w []byte for _, k := range compressed { var entry []byte if x, ok := dictionary[k]; ok { entry = x[:len(x):len(x)] } else if k == dictSize && len(w) > 0 { entry = append(w, w[0]) } else { return result.String(), BadSymbolError(k) } result.Write(entry) if len(w) > 0 { w = append(w, entry[0]) dictionary[dictSize] = w dictSize++ } w = entry } return result.String(), nil } func main() { compressed := compress("TOBEORNOTTOBEORTOBEORNOT") fmt.Println(compressed) decompressed, err := decompress(compressed) if err != nil { log.Fatal(err) } fmt.Println(decompressed) }
class LZW { function compress($unc) { $i;$c;$wc; $w = ""; $dictionary = array(); $result = array(); $dictSize = 256; for ($i = 0; $i < 256; $i += 1) { $dictionary[chr($i)] = $i; } for ($i = 0; $i < strlen($unc); $i++) { $c = $unc[$i]; $wc = $w.$c; if (array_key_exists($w.$c, $dictionary)) { $w = $w.$c; } else { array_push($result,$dictionary[$w]); $dictionary[$wc] = $dictSize++; $w = (string)$c; } } if ($w !== "") { array_push($result,$dictionary[$w]); } return implode(",",$result); } function decompress($com) { $com = explode(",",$com); $i;$w;$k;$result; $dictionary = array(); $entry = ""; $dictSize = 256; for ($i = 0; $i < 256; $i++) { $dictionary[$i] = chr($i); } $w = chr($com[0]); $result = $w; for ($i = 1; $i < count($com);$i++) { $k = $com[$i]; if (isset($dictionary[$k])) { $entry = $dictionary[$k]; } else { if ($k === $dictSize) { $entry = $w.$w[0]; } else { return null; } } $result .= $entry; $dictionary[$dictSize++] = $w . $entry[0]; $w = $entry; } return $result; } } $str = 'TOBEORNOTTOBEORTOBEORNOT'; $lzw = new LZW(); $com = $lzw->compress($str); $dec = $lzw->decompress($com); echo $com . "<br>" . $dec;
Generate a PHP translation of this Go snippet without changing its computational steps.
package main import "fmt" func main() { for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} { f, ok := arFib(n) if ok { fmt.Printf("fib %d = %d\n", n, f) } else { fmt.Println("fib undefined for negative numbers") } } } func arFib(n int) (int, bool) { switch { case n < 0: return 0, false case n < 2: return n, true } return yc(func(recurse fn) fn { return func(left, term1, term2 int) int { if left == 0 { return term1+term2 } return recurse(left-1, term1+term2, term1) } })(n-2, 1, 0), true } type fn func(int, int, int) int type ff func(fn) fn type fx func(fx) fn func yc(f ff) fn { return func(x fx) fn { return x(x) }(func(x fx) fn { return f(func(a1, a2, a3 int) int { return x(x)(a1, a2, a3) }) }) }
<?php function fib($n) { if ($n < 0) throw new Exception('Negative numbers not allowed'); $f = function($n) { // This function must be called using call_user_func() only if ($n < 2) return 1; else { $g = debug_backtrace()[1]['args'][0]; return call_user_func($g, $n-1) + call_user_func($g, $n-2); } }; return call_user_func($f, $n); } echo fib(8), "\n"; ?>
Rewrite the snippet below in PHP so it works the same as the original Go code.
package main import "fmt" func main() { for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} { f, ok := arFib(n) if ok { fmt.Printf("fib %d = %d\n", n, f) } else { fmt.Println("fib undefined for negative numbers") } } } func arFib(n int) (int, bool) { switch { case n < 0: return 0, false case n < 2: return n, true } return yc(func(recurse fn) fn { return func(left, term1, term2 int) int { if left == 0 { return term1+term2 } return recurse(left-1, term1+term2, term1) } })(n-2, 1, 0), true } type fn func(int, int, int) int type ff func(fn) fn type fx func(fx) fn func yc(f ff) fn { return func(x fx) fn { return x(x) }(func(x fx) fn { return f(func(a1, a2, a3 int) int { return x(x)(a1, a2, a3) }) }) }
<?php function fib($n) { if ($n < 0) throw new Exception('Negative numbers not allowed'); $f = function($n) { // This function must be called using call_user_func() only if ($n < 2) return 1; else { $g = debug_backtrace()[1]['args'][0]; return call_user_func($g, $n-1) + call_user_func($g, $n-2); } }; return call_user_func($f, $n); } echo fib(8), "\n"; ?>
Port the provided Go code into PHP while preserving the original functionality.
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
<?php echo substr("knight", 1), "\n"; // strip first character echo substr("socks", 0, -1), "\n"; // strip last character echo substr("brooms", 1, -1), "\n"; // strip both first and last characters ?>
Generate a PHP translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
<?php echo substr("knight", 1), "\n"; // strip first character echo substr("socks", 0, -1), "\n"; // strip last character echo substr("brooms", 1, -1), "\n"; // strip both first and last characters ?>
Please provide an equivalent version of this Go code in PHP.
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
<?php echo substr("knight", 1), "\n"; // strip first character echo substr("socks", 0, -1), "\n"; // strip last character echo substr("brooms", 1, -1), "\n"; // strip both first and last characters ?>
Rewrite the snippet below in PHP so it works the same as the original Go code.
package main import ( "fmt" "unicode/utf8" ) func main() { s := "ASCII" fmt.Println("String: ", s) fmt.Println("First byte removed: ", s[1:]) fmt.Println("Last byte removed: ", s[:len(s)-1]) fmt.Println("First and last removed:", s[1:len(s)-1]) u := "Δημοτική" fmt.Println("String: ", u) _, sizeFirst := utf8.DecodeRuneInString(u) fmt.Println("First rune removed: ", u[sizeFirst:]) _, sizeLast := utf8.DecodeLastRuneInString(u) fmt.Println("Last rune removed: ", u[:len(u)-sizeLast]) fmt.Println("First and last removed:", u[sizeFirst:len(u)-sizeLast]) }
<?php echo substr("knight", 1), "\n"; // strip first character echo substr("socks", 0, -1), "\n"; // strip last character echo substr("brooms", 1, -1), "\n"; // strip both first and last characters ?>
Convert this Go block to PHP, preserving its control flow and logic.
package main import ( "bufio" "os" ) func main() { in := bufio.NewReader(os.Stdin) var blankLine = "\n" var printLongest func(string) string printLongest = func(candidate string) (longest string) { longest = candidate s, err := in.ReadString('\n') defer func() { recover() defer func() { recover() }() _ = blankLine[0] func() { defer func() { recover() }() _ = s[len(longest)] longest = s }() longest = printLongest(longest) func() { defer func() { recover() os.Stdout.WriteString(s) }() _ = longest[len(s)] s = "" }() }() _ = err.(error) os.Stdout.WriteString(blankLine) blankLine = "" return } printLongest("") }
<?php echo 'Enter strings (empty string to finish) :', PHP_EOL; $output = $previous = readline(); while ($current = readline()) { $p = $previous; $c = $current; while ($p and $c) { $p = substr($p, 1); $c = substr($c, 1); } if (!$p and !$c) { $output .= PHP_EOL . $current; } if ($c) { $output = $previous = $current; } } echo 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;
Keep all operations the same but rewrite the snippet in PHP.
package main import ( "bufio" "os" ) func main() { in := bufio.NewReader(os.Stdin) var blankLine = "\n" var printLongest func(string) string printLongest = func(candidate string) (longest string) { longest = candidate s, err := in.ReadString('\n') defer func() { recover() defer func() { recover() }() _ = blankLine[0] func() { defer func() { recover() }() _ = s[len(longest)] longest = s }() longest = printLongest(longest) func() { defer func() { recover() os.Stdout.WriteString(s) }() _ = longest[len(s)] s = "" }() }() _ = err.(error) os.Stdout.WriteString(blankLine) blankLine = "" return } printLongest("") }
<?php echo 'Enter strings (empty string to finish) :', PHP_EOL; $output = $previous = readline(); while ($current = readline()) { $p = $previous; $c = $current; while ($p and $c) { $p = substr($p, 1); $c = substr($c, 1); } if (!$p and !$c) { $output .= PHP_EOL . $current; } if ($c) { $output = $previous = $current; } } echo 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;
Translate the given Go code snippet into PHP without altering its behavior.
package main import ( "fmt" "os" ) func createFile(fn string) { f, err := os.Create(fn) if err != nil { fmt.Println(err) return } fmt.Println("file", fn, "created!") f.Close() } func createDir(dn string) { err := os.Mkdir(dn, 0666) if err != nil { fmt.Println(err) return } fmt.Println("directory", dn, "created!") } func main() { createFile("input.txt") createFile("/input.txt") createDir("docs") createDir("/docs") }
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Can you help me rewrite this code in PHP instead of Go, keeping it the same logically?
package main import ( "fmt" "os" ) func createFile(fn string) { f, err := os.Create(fn) if err != nil { fmt.Println(err) return } fmt.Println("file", fn, "created!") f.Close() } func createDir(dn string) { err := os.Mkdir(dn, 0666) if err != nil { fmt.Println(err) return } fmt.Println("directory", dn, "created!") } func main() { createFile("input.txt") createFile("/input.txt") createDir("docs") createDir("/docs") }
<?php touch('output.txt'); mkdir('docs'); touch('/output.txt'); mkdir('/docs'); ?>
Produce a functionally identical PHP code for the snippet given in Go.
package main import "fmt" type link struct { int next *link } func linkInts(s []int) *link { if len(s) == 0 { return nil } return &link{s[0], linkInts(s[1:])} } func (l *link) String() string { if l == nil { return "nil" } r := fmt.Sprintf("[%d", l.int) for l = l.next; l != nil; l = l.next { r = fmt.Sprintf("%s %d", r, l.int) } return r + "]" } func main() { a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66}) fmt.Println("before:", a) b := strandSort(a) fmt.Println("after: ", b) } func strandSort(a *link) (result *link) { for a != nil { sublist := a a = a.next sTail := sublist for p, pPrev := a, a; p != nil; p = p.next { if p.int > sTail.int { sTail.next = p sTail = p if p == a { a = p.next } else { pPrev.next = p.next } } else { pPrev = p } } sTail.next = nil if result == nil { result = sublist continue } var m, rr *link if sublist.int < result.int { m = sublist sublist = m.next rr = result } else { m = result rr = m.next } result = m for { if sublist == nil { m.next = rr break } if rr == nil { m.next = sublist break } if sublist.int < rr.int { m.next = sublist m = sublist sublist = m.next } else { m.next = rr m = rr rr = m.next } } } return }
$lst = new SplDoublyLinkedList(); foreach (array(1,20,64,72,48,75,96,55,42,74) as $v) $lst->push($v); foreach (strandSort($lst) as $v) echo "$v "; function strandSort(SplDoublyLinkedList $lst) { $result = new SplDoublyLinkedList(); while (!$lst->isEmpty()) { $sorted = new SplDoublyLinkedList(); $remain = new SplDoublyLinkedList(); $sorted->push($lst->shift()); foreach ($lst as $item) { if ($sorted->top() <= $item) { $sorted->push($item); } else { $remain->push($item); } } $result = _merge($sorted, $result); $lst = $remain; } return $result; } function _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) { $res = new SplDoublyLinkedList(); while (!$left->isEmpty() && !$right->isEmpty()) { if ($left->bottom() <= $right->bottom()) { $res->push($left->shift()); } else { $res->push($right->shift()); } } foreach ($left as $v) $res->push($v); foreach ($right as $v) $res->push($v); return $res; }
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
package main import "fmt" type link struct { int next *link } func linkInts(s []int) *link { if len(s) == 0 { return nil } return &link{s[0], linkInts(s[1:])} } func (l *link) String() string { if l == nil { return "nil" } r := fmt.Sprintf("[%d", l.int) for l = l.next; l != nil; l = l.next { r = fmt.Sprintf("%s %d", r, l.int) } return r + "]" } func main() { a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66}) fmt.Println("before:", a) b := strandSort(a) fmt.Println("after: ", b) } func strandSort(a *link) (result *link) { for a != nil { sublist := a a = a.next sTail := sublist for p, pPrev := a, a; p != nil; p = p.next { if p.int > sTail.int { sTail.next = p sTail = p if p == a { a = p.next } else { pPrev.next = p.next } } else { pPrev = p } } sTail.next = nil if result == nil { result = sublist continue } var m, rr *link if sublist.int < result.int { m = sublist sublist = m.next rr = result } else { m = result rr = m.next } result = m for { if sublist == nil { m.next = rr break } if rr == nil { m.next = sublist break } if sublist.int < rr.int { m.next = sublist m = sublist sublist = m.next } else { m.next = rr m = rr rr = m.next } } } return }
$lst = new SplDoublyLinkedList(); foreach (array(1,20,64,72,48,75,96,55,42,74) as $v) $lst->push($v); foreach (strandSort($lst) as $v) echo "$v "; function strandSort(SplDoublyLinkedList $lst) { $result = new SplDoublyLinkedList(); while (!$lst->isEmpty()) { $sorted = new SplDoublyLinkedList(); $remain = new SplDoublyLinkedList(); $sorted->push($lst->shift()); foreach ($lst as $item) { if ($sorted->top() <= $item) { $sorted->push($item); } else { $remain->push($item); } } $result = _merge($sorted, $result); $lst = $remain; } return $result; } function _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) { $res = new SplDoublyLinkedList(); while (!$left->isEmpty() && !$right->isEmpty()) { if ($left->bottom() <= $right->bottom()) { $res->push($left->shift()); } else { $res->push($right->shift()); } } foreach ($left as $v) $res->push($v); foreach ($right as $v) $res->push($v); return $res; }
Port the following code from Go to PHP with equivalent syntax and logic.
package main import "fmt" type Delegator struct { delegate interface{} } type Thingable interface { thing() string } func (self Delegator) operation() string { if v, ok := self.delegate.(Thingable); ok { return v.thing() } return "default implementation" } type Delegate int func (Delegate) thing() string { return "delegate implementation" } func main() { a := Delegator{} fmt.Println(a.operation()) a.delegate = "A delegate may be any object" fmt.Println(a.operation()) var d Delegate a.delegate = d fmt.Println(a.operation()) }
class Delegator { function __construct() { $this->delegate = NULL ; } function operation() { if(method_exists($this->delegate, "thing")) return $this->delegate->thing() ; return 'default implementation' ; } } class Delegate { function thing() { return 'Delegate Implementation' ; } } $a = new Delegator() ; print "{$a->operation()}\n" ; $a->delegate = 'A delegate may be any object' ; print "{$a->operation()}\n" ; $a->delegate = new Delegate() ; print "{$a->operation()}\n" ;
Write the same code in PHP as shown below in Go.
package main import "fmt" type Delegator struct { delegate interface{} } type Thingable interface { thing() string } func (self Delegator) operation() string { if v, ok := self.delegate.(Thingable); ok { return v.thing() } return "default implementation" } type Delegate int func (Delegate) thing() string { return "delegate implementation" } func main() { a := Delegator{} fmt.Println(a.operation()) a.delegate = "A delegate may be any object" fmt.Println(a.operation()) var d Delegate a.delegate = d fmt.Println(a.operation()) }
class Delegator { function __construct() { $this->delegate = NULL ; } function operation() { if(method_exists($this->delegate, "thing")) return $this->delegate->thing() ; return 'default implementation' ; } } class Delegate { function thing() { return 'Delegate Implementation' ; } } $a = new Delegator() ; print "{$a->operation()}\n" ; $a->delegate = 'A delegate may be any object' ; print "{$a->operation()}\n" ; $a->delegate = new Delegate() ; print "{$a->operation()}\n" ;
Ensure the translated PHP code behaves exactly like the original Go snippet.
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)]; } return $rs; }
Write a version of this Go function in PHP with identical behavior.
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)]; } return $rs; }
Write the same code in PHP as shown below in Go.
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)]; } return $rs; }
Can you help me rewrite this code in PHP instead of Go, keeping it the same logically?
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
$commands = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up'; $input = 'riG rePEAT copies put mo rest types fup. 6 poweRin'; $expect = 'RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT'; $table = makeCommandTable($commands); $table_keys = array_keys($table); $inputTable = processInput($input); foreach ($inputTable as $word) { $rs = searchCommandTable($word, $table); if ($rs) { $output[] = $rs; } else { $output[] = '*error*'; } } echo 'Input: '. $input. PHP_EOL; echo 'Output: '. implode(' ', $output). PHP_EOL; function searchCommandTable($search, $table) { foreach ($table as $key => $value) { if ((strtoupper(substr($value['word'], 0, strlen($search))) === strtoupper($search)) && (strlen($search) >= $value['min_length'])) { return $key; } } return false; } function processInput($input) { $input = preg_replace('!\s+!', ' ', $input); $pieces = explode(' ', trim($input)); return $pieces; } function makeCommandTable($commands) { $commands = preg_replace('!\s+!', ' ', $commands); $pieces = explode(' ', trim($commands)); foreach ($pieces as $word) { $rs[strtoupper($word)] = ['word'=>$word, 'min_length' => preg_match_all("/[A-Z]/", $word)]; } return $rs; }
Translate this program into PHP but keep the logic exactly as in Go.
package main func main() { s := "immutable" s[0] = 'a' }
define("PI", 3.14159265358); define("MSG", "Hello World");
Can you help me rewrite this code in PHP instead of Go, keeping it the same logically?
package main func main() { s := "immutable" s[0] = 'a' }
define("PI", 3.14159265358); define("MSG", "Hello World");
Translate the given Go code snippet into PHP without altering its behavior.
package main import "fmt" type point struct { x, y float32 } var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}} var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}} func main() { var cp1, cp2, s, e point inside := func(p point) bool { return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) } intersection := func() (p point) { dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y dpx, dpy := s.x-e.x, s.y-e.y n1 := cp1.x*cp2.y - cp1.y*cp2.x n2 := s.x*e.y - s.y*e.x n3 := 1 / (dcx*dpy - dcy*dpx) p.x = (n1*dpx - n2*dcx) * n3 p.y = (n1*dpy - n2*dcy) * n3 return } outputList := subjectPolygon cp1 = clipPolygon[len(clipPolygon)-1] for _, cp2 = range clipPolygon { inputList := outputList outputList = nil s = inputList[len(inputList)-1] for _, e = range inputList { if inside(e) { if !inside(s) { outputList = append(outputList, intersection()) } outputList = append(outputList, e) } else if inside(s) { outputList = append(outputList, intersection()) } s = e } cp1 = cp2 } fmt.Println(outputList) }
<?php function clip ($subjectPolygon, $clipPolygon) { function inside ($p, $cp1, $cp2) { return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]); } function intersection ($cp1, $cp2, $e, $s) { $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ]; $dp = [ $s[0] - $e[0], $s[1] - $e[1] ]; $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0]; $n2 = $s[0] * $e[1] - $s[1] * $e[0]; $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]); return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3]; } $outputList = $subjectPolygon; $cp1 = end($clipPolygon); foreach ($clipPolygon as $cp2) { $inputList = $outputList; $outputList = []; $s = end($inputList); foreach ($inputList as $e) { if (inside($e, $cp1, $cp2)) { if (!inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $outputList[] = $e; } else if (inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $s = $e; } $cp1 = $cp2; } return $outputList; } $subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]]; $clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]]; $clippedPolygon = clip($subjectPolygon, $clipPolygon); echo json_encode($clippedPolygon); echo "\n"; ?>
Convert the following code from Go to PHP, ensuring the logic remains intact.
package main import "fmt" type point struct { x, y float32 } var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}} var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}} func main() { var cp1, cp2, s, e point inside := func(p point) bool { return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x) } intersection := func() (p point) { dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y dpx, dpy := s.x-e.x, s.y-e.y n1 := cp1.x*cp2.y - cp1.y*cp2.x n2 := s.x*e.y - s.y*e.x n3 := 1 / (dcx*dpy - dcy*dpx) p.x = (n1*dpx - n2*dcx) * n3 p.y = (n1*dpy - n2*dcy) * n3 return } outputList := subjectPolygon cp1 = clipPolygon[len(clipPolygon)-1] for _, cp2 = range clipPolygon { inputList := outputList outputList = nil s = inputList[len(inputList)-1] for _, e = range inputList { if inside(e) { if !inside(s) { outputList = append(outputList, intersection()) } outputList = append(outputList, e) } else if inside(s) { outputList = append(outputList, intersection()) } s = e } cp1 = cp2 } fmt.Println(outputList) }
<?php function clip ($subjectPolygon, $clipPolygon) { function inside ($p, $cp1, $cp2) { return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]); } function intersection ($cp1, $cp2, $e, $s) { $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ]; $dp = [ $s[0] - $e[0], $s[1] - $e[1] ]; $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0]; $n2 = $s[0] * $e[1] - $s[1] * $e[0]; $n3 = 1.0 / ($dc[0] * $dp[1] - $dc[1] * $dp[0]); return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3]; } $outputList = $subjectPolygon; $cp1 = end($clipPolygon); foreach ($clipPolygon as $cp2) { $inputList = $outputList; $outputList = []; $s = end($inputList); foreach ($inputList as $e) { if (inside($e, $cp1, $cp2)) { if (!inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $outputList[] = $e; } else if (inside($s, $cp1, $cp2)) { $outputList[] = intersection($cp1, $cp2, $e, $s); } $s = $e; } $cp1 = $cp2; } return $outputList; } $subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]]; $clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]]; $clippedPolygon = clip($subjectPolygon, $clipPolygon); echo json_encode($clippedPolygon); echo "\n"; ?>
Write the same code in PHP as shown below in Go.
package main import "C" import ( "fmt" "unsafe" ) func main() { go1 := "hello C" c1 := C.CString(go1) go1 = "" c2 := C.strdup(c1) C.free(unsafe.Pointer(c1)) go2 := C.GoString(c2) C.free(unsafe.Pointer(c2)) fmt.Println(go2) }
$ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll"); $cstr = $ffi->_strdup("success"); $str = FFI::string($cstr); echo $str; FFI::free($cstr);
Maintain the same structure and functionality when rewriting this code in PHP.
package main import "C" import ( "fmt" "unsafe" ) func main() { go1 := "hello C" c1 := C.CString(go1) go1 = "" c2 := C.strdup(c1) C.free(unsafe.Pointer(c1)) go2 := C.GoString(c2) C.free(unsafe.Pointer(c2)) fmt.Println(go2) }
$ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll"); $cstr = $ffi->_strdup("success"); $str = FFI::string($cstr); echo $str; FFI::free($cstr);
Change the following Go code into PHP without altering its purpose.
package main import ( "fmt" "math/rand" "time" ) func sOfNCreator(n int) func(byte) []byte { s := make([]byte, 0, n) m := n return func(item byte) []byte { if len(s) < n { s = append(s, item) } else { m++ if rand.Intn(m) < n { s[rand.Intn(n)] = item } } return s } } func main() { rand.Seed(time.Now().UnixNano()) var freq [10]int for r := 0; r < 1e5; r++ { sOfN := sOfNCreator(3) for d := byte('0'); d < '9'; d++ { sOfN(d) } for _, d := range sOfN('9') { freq[d-'0']++ } } fmt.Println(freq) }
<?php function s_of_n_creator($n) { $sample = array(); $i = 0; return function($item) use (&$sample, &$i, $n) { $i++; if ($i <= $n) { $sample[] = $item; } else if (rand(0, $i-1) < $n) { $sample[rand(0, $n-1)] = $item; } return $sample; }; } $items = range(0, 9); for ($trial = 0; $trial < 100000; $trial++) { $s_of_n = s_of_n_creator(3); foreach ($items as $item) $sample = $s_of_n($item); foreach ($sample as $s) $bin[$s]++; } print_r($bin); ?>
Keep all operations the same but rewrite the snippet in PHP.
package main import ( "fmt" "math/rand" "time" ) func sOfNCreator(n int) func(byte) []byte { s := make([]byte, 0, n) m := n return func(item byte) []byte { if len(s) < n { s = append(s, item) } else { m++ if rand.Intn(m) < n { s[rand.Intn(n)] = item } } return s } } func main() { rand.Seed(time.Now().UnixNano()) var freq [10]int for r := 0; r < 1e5; r++ { sOfN := sOfNCreator(3) for d := byte('0'); d < '9'; d++ { sOfN(d) } for _, d := range sOfN('9') { freq[d-'0']++ } } fmt.Println(freq) }
<?php function s_of_n_creator($n) { $sample = array(); $i = 0; return function($item) use (&$sample, &$i, $n) { $i++; if ($i <= $n) { $sample[] = $item; } else if (rand(0, $i-1) < $n) { $sample[rand(0, $n-1)] = $item; } return $sample; }; } $items = range(0, 9); for ($trial = 0; $trial < 100000; $trial++) { $s_of_n = s_of_n_creator(3); foreach ($items as $item) $sample = $s_of_n($item); foreach ($sample as $s) $bin[$s]++; } print_r($bin); ?>