Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Write a version of this Go function in C++ with identical behavior.
package main import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" ) func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number of holes (the code length, 4-10)") guesses := flag.Int("guesses", 12, "number of guesses allowed (7-20)") unique := flag.Bool("unique", false, "disallow duplicate colours in the code") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMastermind(*colours, *holes, *guesses, *unique) if err != nil { log.Fatal(err) } err = m.Play() if err != nil { log.Fatal(err) } } type mastermind struct { colours int holes int guesses int unique bool code string past []string scores []string } func NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) { if colours < 2 || colours > 20 { return nil, errors.New("colours must be between 2 and 20 inclusive") } if holes < 4 || holes > 10 { return nil, errors.New("holes must be between 4 and 10 inclusive") } if guesses < 7 || guesses > 20 { return nil, errors.New("guesses must be between 7 and 20 inclusive") } if unique && holes > colours { return nil, errors.New("holes must be > colours when using unique") } return &mastermind{ colours: colours, holes: holes, guesses: guesses, unique: unique, past: make([]string, 0, guesses), scores: make([]string, 0, guesses), }, nil } func (m *mastermind) Play() error { m.generateCode() fmt.Printf("A set of %s has been selected as the code.\n", m.describeCode(m.unique)) fmt.Printf("You have %d guesses.\n", m.guesses) for len(m.past) < m.guesses { guess, err := m.inputGuess() if err != nil { return err } fmt.Println() m.past = append(m.past, guess) str, won := m.scoreString(m.score(guess)) if won { plural := "es" if len(m.past) == 1 { plural = "" } fmt.Printf("You found the code in %d guess%s.\n", len(m.past), plural) return nil } m.scores = append(m.scores, str) m.printHistory() fmt.Println() } fmt.Printf("You are out of guesses. The code was %s.\n", m.code) return nil } const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" const blacks = "XXXXXXXXXX" const whites = "OOOOOOOOOO" const nones = "----------" func (m *mastermind) describeCode(unique bool) string { ustr := "" if unique { ustr = " unique" } return fmt.Sprintf("%d%s letters (from 'A' to %q)", m.holes, ustr, charset[m.colours-1], ) } func (m *mastermind) printHistory() { for i, g := range m.past { fmt.Printf("-----%s---%[1]s--\n", nones[:m.holes]) fmt.Printf("%2d: %s : %s\n", i+1, g, m.scores[i]) } } func (m *mastermind) generateCode() { code := make([]byte, m.holes) if m.unique { p := rand.Perm(m.colours) for i := range code { code[i] = charset[p[i]] } } else { for i := range code { code[i] = charset[rand.Intn(m.colours)] } } m.code = string(code) } func (m *mastermind) inputGuess() (string, error) { var input string for { fmt.Printf("Enter guess #%d: ", len(m.past)+1) if _, err := fmt.Scanln(&input); err != nil { return "", err } input = strings.ToUpper(strings.TrimSpace(input)) if m.validGuess(input) { return input, nil } fmt.Printf("A guess must consist of %s.\n", m.describeCode(false)) } } func (m *mastermind) validGuess(input string) bool { if len(input) != m.holes { return false } for i := 0; i < len(input); i++ { c := input[i] if c < 'A' || c > charset[m.colours-1] { return false } } return true } func (m *mastermind) score(guess string) (black, white int) { scored := make([]bool, m.holes) for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { black++ scored[i] = true } } for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { continue } for j := 0; j < len(m.code); j++ { if i != j && !scored[j] && guess[i] == m.code[j] { white++ scored[j] = true } } } return } func (m *mastermind) scoreString(black, white int) (string, bool) { none := m.holes - black - white return blacks[:black] + whites[:white] + nones[:none], black == m.holes }
#include <iostream> #include <algorithm> #include <ctime> #include <string> #include <vector> typedef std::vector<char> vecChar; class master { public: master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) { std::string color = "ABCDEFGHIJKLMNOPQRST"; if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10; if( !rpt && clr_count < code_len ) clr_count = code_len; if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20; if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20; codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt; for( size_t s = 0; s < colorsCnt; s++ ) { colors.append( 1, color.at( s ) ); } } void play() { bool win = false; combo = getCombo(); while( guessCnt ) { showBoard(); if( checkInput( getInput() ) ) { win = true; break; } guessCnt--; } if( win ) { std::cout << "\n\n--------------------------------\n" << "Very well done!\nYou found the code: " << combo << "\n--------------------------------\n\n"; } else { std::cout << "\n\n--------------------------------\n" << "I am sorry, you couldn't make it!\nThe code was: " << combo << "\n--------------------------------\n\n"; } } private: void showBoard() { vecChar::iterator y; for( int x = 0; x < guesses.size(); x++ ) { std::cout << "\n--------------------------------\n"; std::cout << x + 1 << ": "; for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) { std::cout << *y << " "; } std::cout << " : "; for( y = results[x].begin(); y != results[x].end(); y++ ) { std::cout << *y << " "; } int z = codeLen - results[x].size(); if( z > 0 ) { for( int x = 0; x < z; x++ ) std::cout << "- "; } } std::cout << "\n\n"; } std::string getInput() { std::string a; while( true ) { std::cout << "Enter your guess (" << colors << "): "; a = ""; std::cin >> a; std::transform( a.begin(), a.end(), a.begin(), ::toupper ); if( a.length() > codeLen ) a.erase( codeLen ); bool r = true; for( std::string::iterator x = a.begin(); x != a.end(); x++ ) { if( colors.find( *x ) == std::string::npos ) { r = false; break; } } if( r ) break; } return a; } bool checkInput( std::string a ) { vecChar g; for( std::string::iterator x = a.begin(); x != a.end(); x++ ) { g.push_back( *x ); } guesses.push_back( g ); int black = 0, white = 0; std::vector<bool> gmatch( codeLen, false ); std::vector<bool> cmatch( codeLen, false ); for( int i = 0; i < codeLen; i++ ) { if( a.at( i ) == combo.at( i ) ) { gmatch[i] = true; cmatch[i] = true; black++; } } for( int i = 0; i < codeLen; i++ ) { if (gmatch[i]) continue; for( int j = 0; j < codeLen; j++ ) { if (i == j || cmatch[j]) continue; if( a.at( i ) == combo.at( j ) ) { cmatch[j] = true; white++; break; } } } vecChar r; for( int b = 0; b < black; b++ ) r.push_back( 'X' ); for( int w = 0; w < white; w++ ) r.push_back( 'O' ); results.push_back( r ); return ( black == codeLen ); } std::string getCombo() { std::string c, clr = colors; int l, z; for( size_t s = 0; s < codeLen; s++ ) { z = rand() % ( int )clr.length(); c.append( 1, clr[z] ); if( !repeatClr ) clr.erase( z, 1 ); } return c; } size_t codeLen, colorsCnt, guessCnt; bool repeatClr; std::vector<vecChar> guesses, results; std::string colors, combo; }; int main( int argc, char* argv[] ) { srand( unsigned( time( 0 ) ) ); master m( 4, 8, 12, false ); m.play(); return 0; }
Translate the given Go code snippet into C++ without altering its behavior.
package main import ( "errors" "flag" "fmt" "log" "math/rand" "strings" "time" ) func main() { log.SetPrefix("mastermind: ") log.SetFlags(0) colours := flag.Int("colours", 6, "number of colours to use (2-20)") flag.IntVar(colours, "colors", 6, "alias for colours") holes := flag.Int("holes", 4, "number of holes (the code length, 4-10)") guesses := flag.Int("guesses", 12, "number of guesses allowed (7-20)") unique := flag.Bool("unique", false, "disallow duplicate colours in the code") flag.Parse() rand.Seed(time.Now().UnixNano()) m, err := NewMastermind(*colours, *holes, *guesses, *unique) if err != nil { log.Fatal(err) } err = m.Play() if err != nil { log.Fatal(err) } } type mastermind struct { colours int holes int guesses int unique bool code string past []string scores []string } func NewMastermind(colours, holes, guesses int, unique bool) (*mastermind, error) { if colours < 2 || colours > 20 { return nil, errors.New("colours must be between 2 and 20 inclusive") } if holes < 4 || holes > 10 { return nil, errors.New("holes must be between 4 and 10 inclusive") } if guesses < 7 || guesses > 20 { return nil, errors.New("guesses must be between 7 and 20 inclusive") } if unique && holes > colours { return nil, errors.New("holes must be > colours when using unique") } return &mastermind{ colours: colours, holes: holes, guesses: guesses, unique: unique, past: make([]string, 0, guesses), scores: make([]string, 0, guesses), }, nil } func (m *mastermind) Play() error { m.generateCode() fmt.Printf("A set of %s has been selected as the code.\n", m.describeCode(m.unique)) fmt.Printf("You have %d guesses.\n", m.guesses) for len(m.past) < m.guesses { guess, err := m.inputGuess() if err != nil { return err } fmt.Println() m.past = append(m.past, guess) str, won := m.scoreString(m.score(guess)) if won { plural := "es" if len(m.past) == 1 { plural = "" } fmt.Printf("You found the code in %d guess%s.\n", len(m.past), plural) return nil } m.scores = append(m.scores, str) m.printHistory() fmt.Println() } fmt.Printf("You are out of guesses. The code was %s.\n", m.code) return nil } const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" const blacks = "XXXXXXXXXX" const whites = "OOOOOOOOOO" const nones = "----------" func (m *mastermind) describeCode(unique bool) string { ustr := "" if unique { ustr = " unique" } return fmt.Sprintf("%d%s letters (from 'A' to %q)", m.holes, ustr, charset[m.colours-1], ) } func (m *mastermind) printHistory() { for i, g := range m.past { fmt.Printf("-----%s---%[1]s--\n", nones[:m.holes]) fmt.Printf("%2d: %s : %s\n", i+1, g, m.scores[i]) } } func (m *mastermind) generateCode() { code := make([]byte, m.holes) if m.unique { p := rand.Perm(m.colours) for i := range code { code[i] = charset[p[i]] } } else { for i := range code { code[i] = charset[rand.Intn(m.colours)] } } m.code = string(code) } func (m *mastermind) inputGuess() (string, error) { var input string for { fmt.Printf("Enter guess #%d: ", len(m.past)+1) if _, err := fmt.Scanln(&input); err != nil { return "", err } input = strings.ToUpper(strings.TrimSpace(input)) if m.validGuess(input) { return input, nil } fmt.Printf("A guess must consist of %s.\n", m.describeCode(false)) } } func (m *mastermind) validGuess(input string) bool { if len(input) != m.holes { return false } for i := 0; i < len(input); i++ { c := input[i] if c < 'A' || c > charset[m.colours-1] { return false } } return true } func (m *mastermind) score(guess string) (black, white int) { scored := make([]bool, m.holes) for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { black++ scored[i] = true } } for i := 0; i < len(guess); i++ { if guess[i] == m.code[i] { continue } for j := 0; j < len(m.code); j++ { if i != j && !scored[j] && guess[i] == m.code[j] { white++ scored[j] = true } } } return } func (m *mastermind) scoreString(black, white int) (string, bool) { none := m.holes - black - white return blacks[:black] + whites[:white] + nones[:none], black == m.holes }
#include <iostream> #include <algorithm> #include <ctime> #include <string> #include <vector> typedef std::vector<char> vecChar; class master { public: master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) { std::string color = "ABCDEFGHIJKLMNOPQRST"; if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10; if( !rpt && clr_count < code_len ) clr_count = code_len; if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20; if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20; codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt; for( size_t s = 0; s < colorsCnt; s++ ) { colors.append( 1, color.at( s ) ); } } void play() { bool win = false; combo = getCombo(); while( guessCnt ) { showBoard(); if( checkInput( getInput() ) ) { win = true; break; } guessCnt--; } if( win ) { std::cout << "\n\n--------------------------------\n" << "Very well done!\nYou found the code: " << combo << "\n--------------------------------\n\n"; } else { std::cout << "\n\n--------------------------------\n" << "I am sorry, you couldn't make it!\nThe code was: " << combo << "\n--------------------------------\n\n"; } } private: void showBoard() { vecChar::iterator y; for( int x = 0; x < guesses.size(); x++ ) { std::cout << "\n--------------------------------\n"; std::cout << x + 1 << ": "; for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) { std::cout << *y << " "; } std::cout << " : "; for( y = results[x].begin(); y != results[x].end(); y++ ) { std::cout << *y << " "; } int z = codeLen - results[x].size(); if( z > 0 ) { for( int x = 0; x < z; x++ ) std::cout << "- "; } } std::cout << "\n\n"; } std::string getInput() { std::string a; while( true ) { std::cout << "Enter your guess (" << colors << "): "; a = ""; std::cin >> a; std::transform( a.begin(), a.end(), a.begin(), ::toupper ); if( a.length() > codeLen ) a.erase( codeLen ); bool r = true; for( std::string::iterator x = a.begin(); x != a.end(); x++ ) { if( colors.find( *x ) == std::string::npos ) { r = false; break; } } if( r ) break; } return a; } bool checkInput( std::string a ) { vecChar g; for( std::string::iterator x = a.begin(); x != a.end(); x++ ) { g.push_back( *x ); } guesses.push_back( g ); int black = 0, white = 0; std::vector<bool> gmatch( codeLen, false ); std::vector<bool> cmatch( codeLen, false ); for( int i = 0; i < codeLen; i++ ) { if( a.at( i ) == combo.at( i ) ) { gmatch[i] = true; cmatch[i] = true; black++; } } for( int i = 0; i < codeLen; i++ ) { if (gmatch[i]) continue; for( int j = 0; j < codeLen; j++ ) { if (i == j || cmatch[j]) continue; if( a.at( i ) == combo.at( j ) ) { cmatch[j] = true; white++; break; } } } vecChar r; for( int b = 0; b < black; b++ ) r.push_back( 'X' ); for( int w = 0; w < white; w++ ) r.push_back( 'O' ); results.push_back( r ); return ( black == codeLen ); } std::string getCombo() { std::string c, clr = colors; int l, z; for( size_t s = 0; s < codeLen; s++ ) { z = rand() % ( int )clr.length(); c.append( 1, clr[z] ); if( !repeatClr ) clr.erase( z, 1 ); } return c; } size_t codeLen, colorsCnt, guessCnt; bool repeatClr; std::vector<vecChar> guesses, results; std::string colors, combo; }; int main( int argc, char* argv[] ) { srand( unsigned( time( 0 ) ) ); master m( 4, 8, 12, false ); m.play(); return 0; }
Generate an equivalent C++ version of this Go code.
package main import "fmt" func sumDivisors(n int) int { sum := 1 k := 2 if n%2 == 0 { k = 1 } for i := 1 + k; i*i <= n; i += k { if n%i == 0 { sum += i j := n / i if j != i { sum += j } } } return sum } func sieve(n int) []bool { n++ s := make([]bool, n+1) for i := 6; i <= n; i++ { sd := sumDivisors(i) if sd <= n { s[sd] = true } } return s } func primeSieve(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 main() { limit := 1000000 c := primeSieve(limit) s := sieve(63 * limit) untouchable := []int{2, 5} for n := 6; n <= limit; n += 2 { if !s[n] && c[n-1] && c[n-3] { untouchable = append(untouchable, n) } } fmt.Println("List of untouchable numbers <= 2,000:") count := 0 for i := 0; untouchable[i] <= 2000; i++ { fmt.Printf("%6s", commatize(untouchable[i])) if (i+1)%10 == 0 { fmt.Println() } count++ } fmt.Printf("\n\n%7s untouchable numbers were found <= 2,000\n", commatize(count)) p := 10 count = 0 for _, n := range untouchable { count++ if n > p { cc := commatize(count - 1) cp := commatize(p) fmt.Printf("%7s untouchable numbers were found <= %9s\n", cc, cp) p = p * 10 if p == limit { break } } } cu := commatize(len(untouchable)) cl := commatize(limit) fmt.Printf("%7s untouchable numbers were found <= %s\n", cu, cl) }
#include <functional> #include <bitset> #include <iostream> #include <cmath> using namespace std; using Z0=long long; using Z1=optional<Z0>; using Z2=optional<array<int,3>>; using Z3=function<Z2()>; const int maxUT{3000000}, dL{(int)log2(maxUT)}; struct uT{ bitset<maxUT+1>N; vector<int> G{}; array<Z3,int(dL+1)>L{Z3{}}; int sG{0},mUT{}; void _g(int n,int g){if(g<=mUT){N[g]=false; return _g(n,n+g);}} Z1 nxt(const int n){if(n>mUT) return Z1{}; if(N[n]) return Z1(n); return nxt(n+1);} Z3 fN(const Z0 n,const Z0 i,int g){return [=]()mutable{if(g<sG && ((n+i)*(1+G[g])-n*G[g]<=mUT)) return Z2{{n,i,g++}}; return Z2{};};} Z3 fG(Z0 n,Z0 i,const int g){Z0 e{n+i},l{1},p{1}; return [=]()mutable{n=n*G[g]; p=p*G[g]; l=l+p; i=e*l-n; if(i<=mUT) return Z2{{n,i,g}}; return Z2{};};} void fL(Z3 n, int g){for(;;){ if(auto i=n()){N[(*i)[1]]=false; L[g+1]=fN((*i)[0],(*i)[1],(*i)[2]+1); g=g+1; continue;} if(auto i=L[g]()){n=fG((*i)[0],(*i)[1],(*i)[2]); continue;} if(g>0) if(auto i=L[g-1]()){ g=g-1; n=fG((*i)[0],(*i)[1],(*i)[2]); continue;} if(g>0){ n=[](){return Z2{};}; g=g-1; continue;} break;} } int count(){int g{0}; for(auto n=nxt(0); n; n=nxt(*n+1)) ++g; return g;} uT(const int n):mUT{n}{ N.set(); N[0]=false; N[1]=false; for(auto n=nxt(0);*n<=sqrt(mUT);n=nxt(*n+1)) _g(*n,*n+*n); for(auto n=nxt(0); n; n=nxt(*n+1)) G.push_back(*n); sG=G.size(); N.set(); N[0]=false; L[0]=fN(1,0,0); fL([](){return Z2{};},0); } };
Generate an equivalent C++ version of this Go code.
package main import "fmt" func sumDivisors(n int) int { sum := 1 k := 2 if n%2 == 0 { k = 1 } for i := 1 + k; i*i <= n; i += k { if n%i == 0 { sum += i j := n / i if j != i { sum += j } } } return sum } func sieve(n int) []bool { n++ s := make([]bool, n+1) for i := 6; i <= n; i++ { sd := sumDivisors(i) if sd <= n { s[sd] = true } } return s } func primeSieve(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 main() { limit := 1000000 c := primeSieve(limit) s := sieve(63 * limit) untouchable := []int{2, 5} for n := 6; n <= limit; n += 2 { if !s[n] && c[n-1] && c[n-3] { untouchable = append(untouchable, n) } } fmt.Println("List of untouchable numbers <= 2,000:") count := 0 for i := 0; untouchable[i] <= 2000; i++ { fmt.Printf("%6s", commatize(untouchable[i])) if (i+1)%10 == 0 { fmt.Println() } count++ } fmt.Printf("\n\n%7s untouchable numbers were found <= 2,000\n", commatize(count)) p := 10 count = 0 for _, n := range untouchable { count++ if n > p { cc := commatize(count - 1) cp := commatize(p) fmt.Printf("%7s untouchable numbers were found <= %9s\n", cc, cp) p = p * 10 if p == limit { break } } } cu := commatize(len(untouchable)) cl := commatize(limit) fmt.Printf("%7s untouchable numbers were found <= %s\n", cu, cl) }
#include <functional> #include <bitset> #include <iostream> #include <cmath> using namespace std; using Z0=long long; using Z1=optional<Z0>; using Z2=optional<array<int,3>>; using Z3=function<Z2()>; const int maxUT{3000000}, dL{(int)log2(maxUT)}; struct uT{ bitset<maxUT+1>N; vector<int> G{}; array<Z3,int(dL+1)>L{Z3{}}; int sG{0},mUT{}; void _g(int n,int g){if(g<=mUT){N[g]=false; return _g(n,n+g);}} Z1 nxt(const int n){if(n>mUT) return Z1{}; if(N[n]) return Z1(n); return nxt(n+1);} Z3 fN(const Z0 n,const Z0 i,int g){return [=]()mutable{if(g<sG && ((n+i)*(1+G[g])-n*G[g]<=mUT)) return Z2{{n,i,g++}}; return Z2{};};} Z3 fG(Z0 n,Z0 i,const int g){Z0 e{n+i},l{1},p{1}; return [=]()mutable{n=n*G[g]; p=p*G[g]; l=l+p; i=e*l-n; if(i<=mUT) return Z2{{n,i,g}}; return Z2{};};} void fL(Z3 n, int g){for(;;){ if(auto i=n()){N[(*i)[1]]=false; L[g+1]=fN((*i)[0],(*i)[1],(*i)[2]+1); g=g+1; continue;} if(auto i=L[g]()){n=fG((*i)[0],(*i)[1],(*i)[2]); continue;} if(g>0) if(auto i=L[g-1]()){ g=g-1; n=fG((*i)[0],(*i)[1],(*i)[2]); continue;} if(g>0){ n=[](){return Z2{};}; g=g-1; continue;} break;} } int count(){int g{0}; for(auto n=nxt(0); n; n=nxt(*n+1)) ++g; return g;} uT(const int n):mUT{n}{ N.set(); N[0]=false; N[1]=false; for(auto n=nxt(0);*n<=sqrt(mUT);n=nxt(*n+1)) _g(*n,*n+*n); for(auto n=nxt(0); n; n=nxt(*n+1)) G.push_back(*n); sG=G.size(); N.set(); N[0]=false; L[0]=fN(1,0,0); fL([](){return Z2{};},0); } };
Ensure the translated PHP 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) } }
#!/usr/bin/php <?php if ($argc > 1) file_put_contents( 'notes.txt', date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", FILE_APPEND ); else @readfile('notes.txt');
Please provide an equivalent version of this Go code in PHP.
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) } }
#!/usr/bin/php <?php if ($argc > 1) file_put_contents( 'notes.txt', date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n", FILE_APPEND ); else @readfile('notes.txt');
Translate the given Go code snippet into PHP without altering its behavior.
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) } }
<?php function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]); $arr[$i] = count($dirList[$i]); } $min = min($arr); for($i = 0; $i < count($dirList); $i++) { while(count($dirList[$i]) > $min) { array_pop($dirList[$i]); } $dirList[$i] = '/' . implode('/' , $dirList[$i]); } $dirList = array_unique($dirList); while(count($dirList) !== 1) { $dirList = array_map('dirname', $dirList); $dirList = array_unique($dirList); } reset($dirList); return current($dirList); } $dirs = array( '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members', ); if('/home/user1/tmp' !== common_path($dirs)) { echo 'test fail'; } else { echo 'test success'; } ?>
Convert the following code from Go to PHP, ensuring the logic remains intact.
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) } }
<?php function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]); $arr[$i] = count($dirList[$i]); } $min = min($arr); for($i = 0; $i < count($dirList); $i++) { while(count($dirList[$i]) > $min) { array_pop($dirList[$i]); } $dirList[$i] = '/' . implode('/' , $dirList[$i]); } $dirList = array_unique($dirList); while(count($dirList) !== 1) { $dirList = array_map('dirname', $dirList); $dirList = array_unique($dirList); } reset($dirList); return current($dirList); } $dirs = array( '/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members', ); if('/home/user1/tmp' !== common_path($dirs)) { echo 'test fail'; } else { echo 'test success'; } ?>
Write a version of this Go function in PHP with identical 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) } } }
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
Convert the following code from Go to PHP, ensuring the logic remains intact.
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) } } }
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
Write a version of this Go function in PHP with identical 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) } } }
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
Please provide an equivalent version of this Go code in PHP.
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) } } }
<?php $a = array(); array_push($a, 0); $used = array(); array_push($used, 0); $used1000 = array(); array_push($used1000, 0); $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { $next = $a[$n - 1] - $n; if ($next < 1 || in_array($next, $used)) { $next += 2 * $n; } $alreadyUsed = in_array($next, $used); array_push($a, $next); if (!$alreadyUsed) { array_push($used, $next); if (0 <= $next && $next <= 1000) { array_push($used1000, $next); } } if ($n == 14) { echo "The first 15 terms of the Recaman sequence are : ["; foreach($a as $i => $v) { if ( $i == count($a) - 1) echo "$v"; else echo "$v, "; } echo "]\n"; } if (!$foundDup && $alreadyUsed) { printf("The first duplicate term is a[%d] = %d\n", $n, $next); $foundDup = true; } if (count($used1000) == 1001) { printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); } $n++; }
Can you help me rewrite this code in PHP instead of Go, keeping it the same logically?
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}, }
<?php const BOARD_NUM = 9; const ROW_NUM = 3; $EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM); function isGameOver($board, $pin) { $pat = '/X{3}|' . //Horz 'X..X..X..|' . //Vert Left '.X..X..X.|' . //Vert Middle '..X..X..X|' . //Vert Right '..X.X.X..|' . //Diag TL->BR 'X...X...X|' . //Diag TR->BL '[^\.]{9}/i'; //Cat's game if ($pin == 'O') $pat = str_replace('X', 'O', $pat); return preg_match($pat, $board); } $boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR; $turn = substr_count($boardStr, '.')%2==0? 'O' : 'X'; $oppTurn = $turn == 'X'? 'O' : 'X'; $gameOver = isGameOver($boardStr, $oppTurn); echo '<style>'; echo 'td {width: 200px; height: 200px; text-align: center; }'; echo '.pin {font-size:72pt; text-decoration:none; color: black}'; echo '.pin.X {color:red}'; echo '.pin.O {color:blue}'; echo '</style>'; echo '<table border="1">'; $p = 0; for ($r = 0; $r < ROW_NUM; $r++) { echo '<tr>'; for ($c = 0; $c < ROW_NUM; $c++) { $pin = $boardStr[$p]; echo '<td>'; if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied else { //Available $boardDelta = $boardStr; $boardDelta[$p] = $turn; echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">'; echo $boardStr[$p]; echo '</a>'; } echo '</td>'; $p++; } echo '</tr>'; echo '<input type="hidden" name="b" value="', $boardStr, '"/>'; } echo '</table>'; echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>'; if ($gameOver) echo '<h1>Game Over!</h1>';
Please provide an equivalent version of this Go code in PHP.
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}, }
<?php const BOARD_NUM = 9; const ROW_NUM = 3; $EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM); function isGameOver($board, $pin) { $pat = '/X{3}|' . //Horz 'X..X..X..|' . //Vert Left '.X..X..X.|' . //Vert Middle '..X..X..X|' . //Vert Right '..X.X.X..|' . //Diag TL->BR 'X...X...X|' . //Diag TR->BL '[^\.]{9}/i'; //Cat's game if ($pin == 'O') $pat = str_replace('X', 'O', $pat); return preg_match($pat, $board); } $boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR; $turn = substr_count($boardStr, '.')%2==0? 'O' : 'X'; $oppTurn = $turn == 'X'? 'O' : 'X'; $gameOver = isGameOver($boardStr, $oppTurn); echo '<style>'; echo 'td {width: 200px; height: 200px; text-align: center; }'; echo '.pin {font-size:72pt; text-decoration:none; color: black}'; echo '.pin.X {color:red}'; echo '.pin.O {color:blue}'; echo '</style>'; echo '<table border="1">'; $p = 0; for ($r = 0; $r < ROW_NUM; $r++) { echo '<tr>'; for ($c = 0; $c < ROW_NUM; $c++) { $pin = $boardStr[$p]; echo '<td>'; if ($gameOver || $pin != '.') echo '<span class="pin ', $pin, '">', $pin, '</span>'; //Occupied else { //Available $boardDelta = $boardStr; $boardDelta[$p] = $turn; echo '<a class="pin ', $pin, '" href="?b=', $boardDelta, '">'; echo $boardStr[$p]; echo '</a>'; } echo '</td>'; $p++; } echo '</tr>'; echo '<input type="hidden" name="b" value="', $boardStr, '"/>'; } echo '</table>'; echo '<a href="?b=', $EMPTY_BOARD_STR, '">Reset</a>'; if ($gameOver) echo '<h1>Game Over!</h1>';
Port the following code from Go to PHP with equivalent syntax and logic.
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 }
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
Port the provided Go code into PHP 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 }
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
Translate this program into PHP but keep the logic exactly as in Go.
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 }
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
Port the following code from Go to PHP with equivalent syntax and logic.
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 }
<?php $h = 0; $s = file_get_contents(__FILE__); $l = strlen($s); foreach ( count_chars($s, 1) as $c ) $h -= ( $c / $l ) * log( $c / $l, 2 ); echo $h;
Preserve the algorithm and functionality while converting the code from Go to PHP.
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
<?php $ipv4_record = dns_get_record("www.kame.net",DNS_A); $ipv6_record = dns_get_record("www.kame.net",DNS_AAAA); print "ipv4: " . $ipv4_record[0]["ip"] . "\n"; print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n"; ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "net" ) func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
<?php $ipv4_record = dns_get_record("www.kame.net",DNS_A); $ipv6_record = dns_get_record("www.kame.net",DNS_AAAA); print "ipv4: " . $ipv4_record[0]["ip"] . "\n"; print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n"; ?>
Preserve the algorithm and functionality while converting the code from Go to PHP.
package main import ( "fmt" "math/rand" "strings" "time" ) const rps = "rps" var msg = []string{ "Rock breaks scissors", "Paper covers rock", "Scissors cut paper", } func main() { rand.Seed(time.Now().UnixNano()) fmt.Println("Rock Paper Scissors") fmt.Println("Enter r, p, or s as your play. Anything else ends the game.") fmt.Println("Running score shown as <your wins>:<my wins>") var pi string var aScore, pScore int sl := 3 pcf := make([]int, 3) var plays int aChoice := rand.Intn(3) for { fmt.Print("Play: ") _, err := fmt.Scanln(&pi) if err != nil || len(pi) != 1 { break } pChoice := strings.Index(rps, pi) if pChoice < 0 { break } pcf[pChoice]++ plays++ fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice]) switch (aChoice - pChoice + 3) % 3 { case 0: fmt.Println("Tie.") case 1: fmt.Printf("%s. My point.\n", msg[aChoice]) aScore++ case 2: fmt.Printf("%s. Your point.\n", msg[pChoice]) pScore++ } sl, _ = fmt.Printf("%d:%d ", pScore, aScore) switch rn := rand.Intn(plays); { case rn < pcf[0]: aChoice = 1 case rn < pcf[0]+pcf[1]: aChoice = 2 default: aChoice = 0 } } }
<?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo ""; $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>"; echo "<br>"; echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>"; $results = ""; if ($player == $a_i){ $results = "Draw"; } else if($wins[$a_i] == $player ){ $results = "A.I wins"; } else { $results = "Player wins"; } echo "<br>" . $results; ?>
Can you help me rewrite this code in PHP instead of Go, keeping it the same logically?
package main import ( "fmt" "math/rand" "strings" "time" ) const rps = "rps" var msg = []string{ "Rock breaks scissors", "Paper covers rock", "Scissors cut paper", } func main() { rand.Seed(time.Now().UnixNano()) fmt.Println("Rock Paper Scissors") fmt.Println("Enter r, p, or s as your play. Anything else ends the game.") fmt.Println("Running score shown as <your wins>:<my wins>") var pi string var aScore, pScore int sl := 3 pcf := make([]int, 3) var plays int aChoice := rand.Intn(3) for { fmt.Print("Play: ") _, err := fmt.Scanln(&pi) if err != nil || len(pi) != 1 { break } pChoice := strings.Index(rps, pi) if pChoice < 0 { break } pcf[pChoice]++ plays++ fmt.Printf("My play:%s%c. ", strings.Repeat(" ", sl-2), rps[aChoice]) switch (aChoice - pChoice + 3) % 3 { case 0: fmt.Println("Tie.") case 1: fmt.Printf("%s. My point.\n", msg[aChoice]) aScore++ case 2: fmt.Printf("%s. Your point.\n", msg[pChoice]) pScore++ } sl, _ = fmt.Printf("%d:%d ", pScore, aScore) switch rn := rand.Intn(plays); { case rn < pcf[0]: aChoice = 1 case rn < pcf[0]+pcf[1]: aChoice = 2 default: aChoice = 0 } } }
<?php echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>"; echo "<h2>"; echo ""; $player = strtoupper( $_GET["moves"] ); $wins = [ 'ROCK' => 'SCISSORS', 'PAPER' => 'ROCK', 'SCISSORS' => 'PAPER' ]; $a_i = array_rand($wins); echo "<br>"; echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>"; echo "<br>"; echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>"; $results = ""; if ($player == $a_i){ $results = "Draw"; } else if($wins[$a_i] == $player ){ $results = "A.I wins"; } else { $results = "Player wins"; } echo "<br>" . $results; ?>
Write the same algorithm in PHP as shown in this Go implementation.
package main import "fmt" type Func func(int) int type FuncFunc func(Func) Func type RecursiveFunc func (RecursiveFunc) Func func main() { fac := Y(almost_fac) fib := Y(almost_fib) fmt.Println("fac(10) = ", fac(10)) fmt.Println("fib(10) = ", fib(10)) } func Y(f FuncFunc) Func { g := func(r RecursiveFunc) Func { return f(func(x int) int { return r(r)(x) }) } return g(g) } func almost_fac(f Func) Func { return func(x int) int { if x <= 1 { return 1 } return x * f(x-1) } } func almost_fib(f Func) Func { return func(x int) int { if x <= 2 { return 1 } return f(x-1)+f(x-2) } }
<?php function Y($f) { $g = function($w) use($f) { return $f(function() use($w) { return call_user_func_array($w($w), func_get_args()); }); }; return $g($g); } $fibonacci = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); }; }); echo $fibonacci(10), "\n"; $factorial = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); }; }); echo $factorial(10), "\n"; ?>
Translate the given Go code snippet into PHP without altering its behavior.
package main import "fmt" type Func func(int) int type FuncFunc func(Func) Func type RecursiveFunc func (RecursiveFunc) Func func main() { fac := Y(almost_fac) fib := Y(almost_fib) fmt.Println("fac(10) = ", fac(10)) fmt.Println("fib(10) = ", fib(10)) } func Y(f FuncFunc) Func { g := func(r RecursiveFunc) Func { return f(func(x int) int { return r(r)(x) }) } return g(g) } func almost_fac(f Func) Func { return func(x int) int { if x <= 1 { return 1 } return x * f(x-1) } } func almost_fib(f Func) Func { return func(x int) int { if x <= 2 { return 1 } return f(x-1)+f(x-2) } }
<?php function Y($f) { $g = function($w) use($f) { return $f(function() use($w) { return call_user_func_array($w($w), func_get_args()); }); }; return $g($g); } $fibonacci = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? $i : ($f($i-1) + $f($i-2)); }; }); echo $fibonacci(10), "\n"; $factorial = Y(function($f) { return function($i) use($f) { return ($i <= 1) ? 1 : ($f($i - 1) * $i); }; }); echo $factorial(10), "\n"; ?>
Convert the following code from Go to PHP, ensuring the logic remains intact.
func addsub(x, y int) (int, int) { return x + y, x - y }
function addsub($x, $y) { return array($x + $y, $x - $y); }
Port the following code from Go to PHP with equivalent syntax and logic.
func addsub(x, y int) (int, int) { return x + y, x - y }
function addsub($x, $y) { return array($x + $y, $x - $y); }
Generate an equivalent PHP version of this Go code.
package main import ( "fmt" "io" "log" "os" "github.com/stacktic/ftp" ) func main() { const ( hostport = "localhost:21" username = "anonymous" password = "anonymous" dir = "pub" file = "somefile.bin" ) conn, err := ftp.Connect(hostport) if err != nil { log.Fatal(err) } defer conn.Quit() fmt.Println(conn) if err = conn.Login(username, password); err != nil { log.Fatal(err) } if err = conn.ChangeDir(dir); err != nil { log.Fatal(err) } fmt.Println(conn.CurrentDir()) files, err := conn.List(".") if err != nil { log.Fatal(err) } for _, f := range files { fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name) } r, err := conn.Retr(file) if err != nil { log.Fatal(err) } defer r.Close() f, err := os.Create(file) if err != nil { log.Fatal(err) } defer f.Close() n, err := io.Copy(f, r) if err != nil { log.Fatal(err) } fmt.Println("Wrote", n, "bytes to", file) }
$server = "speedtest.tele2.net"; $user = "anonymous"; $pass = "ftptest@example.com"; $conn = ftp_connect($server); if (!$conn) { die('unable to connect to: '. $server); } $login = ftp_login($conn, $user, $pass); if (!$login) { echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass; } else{ echo 'connected successfully'.PHP_EOL; $directory = ftp_nlist($conn,''); print_r($directory); } if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) { echo "Successfully downloaded file".PHP_EOL; } else { echo "failed to download file"; }
Write the same algorithm in PHP as shown in this Go implementation.
package main import ( "fmt" "io" "log" "os" "github.com/stacktic/ftp" ) func main() { const ( hostport = "localhost:21" username = "anonymous" password = "anonymous" dir = "pub" file = "somefile.bin" ) conn, err := ftp.Connect(hostport) if err != nil { log.Fatal(err) } defer conn.Quit() fmt.Println(conn) if err = conn.Login(username, password); err != nil { log.Fatal(err) } if err = conn.ChangeDir(dir); err != nil { log.Fatal(err) } fmt.Println(conn.CurrentDir()) files, err := conn.List(".") if err != nil { log.Fatal(err) } for _, f := range files { fmt.Printf("%v %12d %v %v\n", f.Time, f.Size, f.Type, f.Name) } r, err := conn.Retr(file) if err != nil { log.Fatal(err) } defer r.Close() f, err := os.Create(file) if err != nil { log.Fatal(err) } defer f.Close() n, err := io.Copy(f, r) if err != nil { log.Fatal(err) } fmt.Println("Wrote", n, "bytes to", file) }
$server = "speedtest.tele2.net"; $user = "anonymous"; $pass = "ftptest@example.com"; $conn = ftp_connect($server); if (!$conn) { die('unable to connect to: '. $server); } $login = ftp_login($conn, $user, $pass); if (!$login) { echo 'unable to log in to '. $server. ' with user: '.$user.' and pass: '. $pass; } else{ echo 'connected successfully'.PHP_EOL; $directory = ftp_nlist($conn,''); print_r($directory); } if (ftp_get($conn, '1KB.zip', '1KB.zip', FTP_BINARY)) { echo "Successfully downloaded file".PHP_EOL; } else { echo "failed to download file"; }
Write the same algorithm in PHP as shown in this Go implementation.
package main import ( "fmt" "math" "math/rand" "time" ) func main() { rand.Seed(time.Now().Unix()) n := make([]rune, 4) for i := range n { n[i] = rune(rand.Intn(9) + '1') } fmt.Printf("Your numbers: %c\n", n) fmt.Print("Enter RPN: ") var expr string fmt.Scan(&expr) if len(expr) != 7 { fmt.Println("invalid. expression length must be 7." + " (4 numbers, 3 operators, no spaces)") return } stack := make([]float64, 0, 4) for _, r := range expr { if r >= '0' && r <= '9' { if len(n) == 0 { fmt.Println("too many numbers.") return } i := 0 for n[i] != r { i++ if i == len(n) { fmt.Println("wrong numbers.") return } } n = append(n[:i], n[i+1:]...) stack = append(stack, float64(r-'0')) continue } if len(stack) < 2 { fmt.Println("invalid expression syntax.") return } switch r { case '+': stack[len(stack)-2] += stack[len(stack)-1] case '-': stack[len(stack)-2] -= stack[len(stack)-1] case '*': stack[len(stack)-2] *= stack[len(stack)-1] case '/': stack[len(stack)-2] /= stack[len(stack)-1] default: fmt.Printf("%c invalid.\n", r) return } stack = stack[:len(stack)-1] } if math.Abs(stack[0]-24) > 1e-6 { fmt.Println("incorrect.", stack[0], "!= 24") } else { fmt.Println("correct.") } }
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
Produce a language-to-language conversion: from Go to PHP, same semantics.
package main import ( "fmt" "math" "math/rand" "time" ) func main() { rand.Seed(time.Now().Unix()) n := make([]rune, 4) for i := range n { n[i] = rune(rand.Intn(9) + '1') } fmt.Printf("Your numbers: %c\n", n) fmt.Print("Enter RPN: ") var expr string fmt.Scan(&expr) if len(expr) != 7 { fmt.Println("invalid. expression length must be 7." + " (4 numbers, 3 operators, no spaces)") return } stack := make([]float64, 0, 4) for _, r := range expr { if r >= '0' && r <= '9' { if len(n) == 0 { fmt.Println("too many numbers.") return } i := 0 for n[i] != r { i++ if i == len(n) { fmt.Println("wrong numbers.") return } } n = append(n[:i], n[i+1:]...) stack = append(stack, float64(r-'0')) continue } if len(stack) < 2 { fmt.Println("invalid expression syntax.") return } switch r { case '+': stack[len(stack)-2] += stack[len(stack)-1] case '-': stack[len(stack)-2] -= stack[len(stack)-1] case '*': stack[len(stack)-2] *= stack[len(stack)-1] case '/': stack[len(stack)-2] /= stack[len(stack)-1] default: fmt.Printf("%c invalid.\n", r) return } stack = stack[:len(stack)-1] } if math.Abs(stack[0]-24) > 1e-6 { fmt.Println("incorrect.", stack[0], "!= 24") } else { fmt.Println("correct.") } }
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
Please provide an equivalent version of this Go code in PHP.
package main import ( "fmt" "math" "math/rand" "time" ) func main() { rand.Seed(time.Now().Unix()) n := make([]rune, 4) for i := range n { n[i] = rune(rand.Intn(9) + '1') } fmt.Printf("Your numbers: %c\n", n) fmt.Print("Enter RPN: ") var expr string fmt.Scan(&expr) if len(expr) != 7 { fmt.Println("invalid. expression length must be 7." + " (4 numbers, 3 operators, no spaces)") return } stack := make([]float64, 0, 4) for _, r := range expr { if r >= '0' && r <= '9' { if len(n) == 0 { fmt.Println("too many numbers.") return } i := 0 for n[i] != r { i++ if i == len(n) { fmt.Println("wrong numbers.") return } } n = append(n[:i], n[i+1:]...) stack = append(stack, float64(r-'0')) continue } if len(stack) < 2 { fmt.Println("invalid expression syntax.") return } switch r { case '+': stack[len(stack)-2] += stack[len(stack)-1] case '-': stack[len(stack)-2] -= stack[len(stack)-1] case '*': stack[len(stack)-2] *= stack[len(stack)-1] case '/': stack[len(stack)-2] /= stack[len(stack)-1] default: fmt.Printf("%c invalid.\n", r) return } stack = stack[:len(stack)-1] } if math.Abs(stack[0]-24) > 1e-6 { fmt.Println("incorrect.", stack[0], "!= 24") } else { fmt.Println("correct.") } }
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
Convert this Go snippet to PHP and keep its semantics consistent.
package main import ( "fmt" "math" "math/rand" "time" ) func main() { rand.Seed(time.Now().Unix()) n := make([]rune, 4) for i := range n { n[i] = rune(rand.Intn(9) + '1') } fmt.Printf("Your numbers: %c\n", n) fmt.Print("Enter RPN: ") var expr string fmt.Scan(&expr) if len(expr) != 7 { fmt.Println("invalid. expression length must be 7." + " (4 numbers, 3 operators, no spaces)") return } stack := make([]float64, 0, 4) for _, r := range expr { if r >= '0' && r <= '9' { if len(n) == 0 { fmt.Println("too many numbers.") return } i := 0 for n[i] != r { i++ if i == len(n) { fmt.Println("wrong numbers.") return } } n = append(n[:i], n[i+1:]...) stack = append(stack, float64(r-'0')) continue } if len(stack) < 2 { fmt.Println("invalid expression syntax.") return } switch r { case '+': stack[len(stack)-2] += stack[len(stack)-1] case '-': stack[len(stack)-2] -= stack[len(stack)-1] case '*': stack[len(stack)-2] *= stack[len(stack)-1] case '/': stack[len(stack)-2] /= stack[len(stack)-1] default: fmt.Printf("%c invalid.\n", r) return } stack = stack[:len(stack)-1] } if math.Abs(stack[0]-24) > 1e-6 { fmt.Println("incorrect.", stack[0], "!= 24") } else { fmt.Println("correct.") } }
#!/usr/bin/env php The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24. An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. Otherwise you are repeatedly asked for an expression until it evaluates to 24 Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. <?php while (true) { $numbers = make_numbers(); for ($iteration_num = 1; ; $iteration_num++) { echo "Expresion $iteration_num: "; $entry = rtrim(fgets(STDIN)); if ($entry === '!') break; if ($entry === 'q') exit; $result = play($numbers, $entry); if ($result === null) { echo "That's not valid\n"; continue; } elseif ($result != 24) { echo "Sorry, that's $result\n"; continue; } else { echo "That's right! 24!!\n"; exit; } } } function make_numbers() { $numbers = array(); echo "Your four digits: "; for ($i = 0; $i < 4; $i++) { $number = rand(1, 9); if (!isset($numbers[$number])) { $numbers[$number] = 0; } $numbers[$number]++; print "$number "; } print "\n"; return $numbers; } function play($numbers, $expression) { $operator = true; for ($i = 0, $length = strlen($expression); $i < $length; $i++) { $character = $expression[$i]; if (in_array($character, array('(', ')', ' ', "\t"))) continue; $operator = !$operator; if (!$operator) { if (!empty($numbers[$character])) { $numbers[$character]--; continue; } return; } elseif (!in_array($character, array('+', '-', '*', '/'))) { return; } } foreach ($numbers as $remaining) { if ($remaining > 0) { return; } } return eval("return $expression;"); } ?>
Maintain the same structure and functionality when rewriting this code in PHP.
package main import "fmt" func main() { for i := 1; i <= 10; i++ { fmt.Printf("%d", i) if i%5 == 0 { fmt.Printf("\n") continue } fmt.Printf(", ") } }
for ($i = 1; $i <= 10; $i++) { echo $i; if ($i % 5 == 0) { echo "\n"; continue; } echo ', '; }
Please provide an equivalent version of this Go code in PHP.
package main import "fmt" func main() { for i := 1; i <= 10; i++ { fmt.Printf("%d", i) if i%5 == 0 { fmt.Printf("\n") continue } fmt.Printf(", ") } }
for ($i = 1; $i <= 10; $i++) { echo $i; if ($i % 5 == 0) { echo "\n"; continue; } echo ', '; }
Maintain the same structure and functionality when rewriting this code in PHP.
package main import "github.com/fogleman/gg" var colors = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func drawBars(dc *gg.Context) { w := float64(dc.Width() / len(colors)) h := float64(dc.Height()) for i := range colors { dc.SetHexColor(colors[i]) dc.DrawRectangle(w*float64(i), 0, w, h) dc.Fill() } } func main() { dc := gg.NewContext(400, 400) drawBars(dc) dc.SavePNG("color_bars.png") }
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480); $image = imagecreate(BARWIDTH * count($colors), HEIGHT); foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); } header('Content-type:image/png'); imagepng($image); imagedestroy($image);
Convert this Go block to PHP, preserving its control flow and logic.
package main import "github.com/fogleman/gg" var colors = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func drawBars(dc *gg.Context) { w := float64(dc.Width() / len(colors)) h := float64(dc.Height()) for i := range colors { dc.SetHexColor(colors[i]) dc.DrawRectangle(w*float64(i), 0, w, h) dc.Fill() } } func main() { dc := gg.NewContext(400, 400) drawBars(dc) dc.SavePNG("color_bars.png") }
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480); $image = imagecreate(BARWIDTH * count($colors), HEIGHT); foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); } header('Content-type:image/png'); imagepng($image); imagedestroy($image);
Port the following code from Go to PHP with equivalent syntax and logic.
package main import "github.com/fogleman/gg" var colors = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func drawBars(dc *gg.Context) { w := float64(dc.Width() / len(colors)) h := float64(dc.Height()) for i := range colors { dc.SetHexColor(colors[i]) dc.DrawRectangle(w*float64(i), 0, w, h) dc.Fill() } } func main() { dc := gg.NewContext(400, 400) drawBars(dc) dc.SavePNG("color_bars.png") }
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480); $image = imagecreate(BARWIDTH * count($colors), HEIGHT); foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); } header('Content-type:image/png'); imagepng($image); imagedestroy($image);
Produce a functionally identical PHP code for the snippet given in Go.
package main import "github.com/fogleman/gg" var colors = [8]string{ "000000", "FF0000", "00FF00", "0000FF", "FF00FF", "00FFFF", "FFFF00", "FFFFFF", } func drawBars(dc *gg.Context) { w := float64(dc.Width() / len(colors)) h := float64(dc.Height()) for i := range colors { dc.SetHexColor(colors[i]) dc.DrawRectangle(w*float64(i), 0, w, h) dc.Fill() } } func main() { dc := gg.NewContext(400, 400) drawBars(dc) dc.SavePNG("color_bars.png") }
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480); $image = imagecreate(BARWIDTH * count($colors), HEIGHT); foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); } header('Content-type:image/png'); imagepng($image); imagedestroy($image);
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
package main import ( "fmt" ) const numbers = 3 func main() { max := 20 words := map[int]string{ 3: "Fizz", 5: "Buzz", 7: "Baxx", } keys := []int{3, 5, 7} divisible := false for i := 1; i <= max; i++ { for _, n := range keys { if i % n == 0 { fmt.Print(words[n]) divisible = true } } if !divisible { fmt.Print(i) } fmt.Println() divisible = false } }
<?php $max = 20; $factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz'); for ($i = 1 ; $i <= $max ; $i++) { $matched = false; foreach ($factor AS $number => $word) { if ($i % $number == 0) { echo $word; $matched = true; } } echo ($matched ? '' : $i), PHP_EOL; } ?>
Generate an equivalent PHP version of this Go code.
package main import ( "fmt" ) const numbers = 3 func main() { max := 20 words := map[int]string{ 3: "Fizz", 5: "Buzz", 7: "Baxx", } keys := []int{3, 5, 7} divisible := false for i := 1; i <= max; i++ { for _, n := range keys { if i % n == 0 { fmt.Print(words[n]) divisible = true } } if !divisible { fmt.Print(i) } fmt.Println() divisible = false } }
<?php $max = 20; $factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz'); for ($i = 1 ; $i <= $max ; $i++) { $matched = false; foreach ($factor AS $number => $word) { if ($i % $number == 0) { echo $word; $matched = true; } } echo ($matched ? '' : $i), PHP_EOL; } ?>
Produce a functionally identical PHP code for the snippet given in Go.
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
Generate an equivalent PHP version of this Go code.
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
Port the following code from Go to PHP with equivalent syntax and logic.
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
Write the same code in PHP as shown below in Go.
package main import ( "bufio" "errors" "fmt" "io" "os" ) func main() { if line, err := rsl("input.txt", 7); err == nil { fmt.Println("7th line:") fmt.Println(line) } else { fmt.Println("rsl:", err) } } func rsl(fn string, n int) (string, error) { if n < 1 { return "", fmt.Errorf("invalid request: line %d", n) } f, err := os.Open(fn) if err != nil { return "", err } defer f.Close() bf := bufio.NewReader(f) var line string for lnum := 0; lnum < n; lnum++ { line, err = bf.ReadString('\n') if err == io.EOF { switch lnum { case 0: return "", errors.New("no lines in file") case 1: return "", errors.New("only 1 line") default: return "", fmt.Errorf("only %d lines", lnum) } } if err != nil { return "", err } } if line == "" { return "", fmt.Errorf("line %d empty", n) } return line, nil }
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT']; function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); } @ $fp = fopen("$DOCROOT/exercises/words.txt", 'r'); if (!$fp) die("Input file not found!"); echo fileLine(7, $fp); ?>
Convert this Go block to PHP, preserving its control flow and logic.
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf("%20s : %s \n", $test[0],$result); }
Write the same algorithm in PHP as shown in this Go implementation.
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf("%20s : %s \n", $test[0],$result); }
Convert the following code from Go to PHP, ensuring the logic remains intact.
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf("%20s : %s \n", $test[0],$result); }
Write the same algorithm in PHP as shown in this Go implementation.
package main import ( "fmt" "strings" ) var extensions = []string{"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} func fileExtInList(filename string) (bool, string) { filename2 := strings.ToLower(filename) for _, ext := range extensions { ext2 := "." + strings.ToLower(ext) if strings.HasSuffix(filename2, ext2) { return true, ext } } s := strings.Split(filename, ".") if len(s) > 1 { t := s[len(s)-1] if t != "" { return false, t } else { return false, "<empty>" } } else { return false, "<none>" } } func main() { fmt.Println("The listed extensions are:") fmt.Println(extensions, "\n") tests := []string{ "MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2", } for _, test := range tests { ok, ext := fileExtInList(test) fmt.Printf("%-20s => %-5t (extension = %s)\n", test, ok, ext) } }
$allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2']; $lc_allowed = array_map('strtolower', $allowed); $tests = [ ['MyData.a##',true], ['MyData.tar.Gz',true], ['MyData.gzip',false], ['MyData.7z.backup',false], ['MyData...',false], ['MyData',false], ['archive.tar.gz', true] ]; foreach ($tests as $test) { $ext = pathinfo($test[0], PATHINFO_EXTENSION); if (in_array(strtolower($ext), $lc_allowed)) { $result = 'true'; } else { $result = 'false'; } printf("%20s : %s \n", $test[0],$result); }
Maintain the same structure and functionality when rewriting this code in PHP.
package main import ( "fmt" "strings" "unicode" "unicode/utf8" ) func main() { show("alphaBETA") show("alpha BETA") show("DŽLjnj") show("o'hare O'HARE o’hare don't") } func show(s string) { fmt.Println("\nstring: ", s, " len:", utf8.RuneCountInString(s), "runes") fmt.Println("All upper case: ", strings.ToUpper(s)) fmt.Println("All lower case: ", strings.ToLower(s)) fmt.Println("All title case: ", strings.ToTitle(s)) fmt.Println("Title words: ", strings.Title(s)) fmt.Println("Swapping case: ", strings.Map(unicode.SimpleFold, s)) }
$str = "alphaBETA"; echo strtoupper($str), "\n"; // ALPHABETA echo strtolower($str), "\n"; // alphabeta echo ucfirst($str), "\n"; // AlphaBETA echo lcfirst("FOObar"), "\n"; // fOObar echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
Translate this program into PHP but keep the logic exactly as in Go.
package main import ( "fmt" "strings" "unicode" "unicode/utf8" ) func main() { show("alphaBETA") show("alpha BETA") show("DŽLjnj") show("o'hare O'HARE o’hare don't") } func show(s string) { fmt.Println("\nstring: ", s, " len:", utf8.RuneCountInString(s), "runes") fmt.Println("All upper case: ", strings.ToUpper(s)) fmt.Println("All lower case: ", strings.ToLower(s)) fmt.Println("All title case: ", strings.ToTitle(s)) fmt.Println("Title words: ", strings.Title(s)) fmt.Println("Swapping case: ", strings.Map(unicode.SimpleFold, s)) }
$str = "alphaBETA"; echo strtoupper($str), "\n"; // ALPHABETA echo strtolower($str), "\n"; // alphabeta echo ucfirst($str), "\n"; // AlphaBETA echo lcfirst("FOObar"), "\n"; // fOObar echo ucwords("foO baR baZ"), "\n"; // FoO BaR BaZ echo lcwords("FOo BAr BAz"), "\n"; // fOo bAr bAz
Write the same code in PHP as shown below in Go.
package main import ( "crypto/md5" "fmt" ) func main() { for _, p := range [][2]string{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"}, {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"}, {"d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" + "123456789012345678901234567890123456789012345678901234567890"}, {"e38ca1d920c4b8b8d3946b2c72f01680", "The quick brown fox jumped over the lazy dog's back"}, } { validate(p[0], p[1]) } } var h = md5.New() func validate(check, s string) { h.Reset() h.Write([]byte(s)) sum := fmt.Sprintf("%x", h.Sum(nil)) if sum != check { fmt.Println("MD5 fail") fmt.Println(" for string,", s) fmt.Println(" expected: ", check) fmt.Println(" got: ", sum) } }
$string = "The quick brown fox jumped over the lazy dog's back"; echo md5( $string );
Produce a language-to-language conversion: from Go to PHP, same semantics.
package main import ( "crypto/md5" "fmt" ) func main() { for _, p := range [][2]string{ {"d41d8cd98f00b204e9800998ecf8427e", ""}, {"0cc175b9c0f1b6a831c399e269772661", "a"}, {"900150983cd24fb0d6963f7d28e17f72", "abc"}, {"f96b697d7cb7938d525a2f31aaf161d0", "message digest"}, {"c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz"}, {"d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"}, {"57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890" + "123456789012345678901234567890123456789012345678901234567890"}, {"e38ca1d920c4b8b8d3946b2c72f01680", "The quick brown fox jumped over the lazy dog's back"}, } { validate(p[0], p[1]) } } var h = md5.New() func validate(check, s string) { h.Reset() h.Write([]byte(s)) sum := fmt.Sprintf("%x", h.Sum(nil)) if sum != check { fmt.Println("MD5 fail") fmt.Println(" for string,", s) fmt.Println(" expected: ", check) fmt.Println(" got: ", sum) } }
$string = "The quick brown fox jumped over the lazy dog's back"; echo md5( $string );
Convert this Go snippet to PHP and keep its semantics consistent.
package main import ( "fmt" "time" ) const taskDate = "March 7 2009 7:30pm EST" const taskFormat = "January 2 2006 3:04pm MST" func main() { if etz, err := time.LoadLocation("US/Eastern"); err == nil { time.Local = etz } fmt.Println("Input: ", taskDate) t, err := time.Parse(taskFormat, taskDate) if err != nil { fmt.Println(err) return } t = t.Add(12 * time.Hour) fmt.Println("+12 hrs: ", t) if _, offset := t.Zone(); offset == 0 { fmt.Println("No time zone info.") return } atz, err := time.LoadLocation("US/Arizona") if err == nil { fmt.Println("+12 hrs in Arizona:", t.In(atz)) } }
<?php $time = new DateTime('March 7 2009 7:30pm EST'); $time->modify('+12 hours'); echo $time->format('c'); ?>
Convert the following code from Go to PHP, ensuring the logic remains intact.
package main import ( "fmt" "time" ) const taskDate = "March 7 2009 7:30pm EST" const taskFormat = "January 2 2006 3:04pm MST" func main() { if etz, err := time.LoadLocation("US/Eastern"); err == nil { time.Local = etz } fmt.Println("Input: ", taskDate) t, err := time.Parse(taskFormat, taskDate) if err != nil { fmt.Println(err) return } t = t.Add(12 * time.Hour) fmt.Println("+12 hrs: ", t) if _, offset := t.Zone(); offset == 0 { fmt.Println("No time zone info.") return } atz, err := time.LoadLocation("US/Arizona") if err == nil { fmt.Println("+12 hrs in Arizona:", t.In(atz)) } }
<?php $time = new DateTime('March 7 2009 7:30pm EST'); $time->modify('+12 hours'); echo $time->format('c'); ?>
Port the following code from Go to PHP with equivalent syntax and logic.
package main import ( "fmt" "log" "os" "strconv" "time" ) func main() { out := make(chan uint64) for _, a := range os.Args[1:] { i, err := strconv.ParseUint(a, 10, 64) if err != nil { log.Fatal(err) } go func(n uint64) { time.Sleep(time.Duration(n) * time.Millisecond) out <- n }(i) } for _ = range os.Args[1:] { fmt.Println(<-out) } }
<?php $buffer = 1; $pids = []; for ($i = 1; $i < $argc; $i++) { $pid = pcntl_fork(); if ($pid < 0) { die("failed to start child process"); } if ($pid === 0) { sleep($argv[$i] + $buffer); echo $argv[$i] . "\n"; exit(); } $pids[] = $pid; } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); }
Port the following code from Go to PHP with equivalent syntax and logic.
package main import ( "fmt" "log" "os" "strconv" "time" ) func main() { out := make(chan uint64) for _, a := range os.Args[1:] { i, err := strconv.ParseUint(a, 10, 64) if err != nil { log.Fatal(err) } go func(n uint64) { time.Sleep(time.Duration(n) * time.Millisecond) out <- n }(i) } for _ = range os.Args[1:] { fmt.Println(<-out) } }
<?php $buffer = 1; $pids = []; for ($i = 1; $i < $argc; $i++) { $pid = pcntl_fork(); if ($pid < 0) { die("failed to start child process"); } if ($pid === 0) { sleep($argv[$i] + $buffer); echo $argv[$i] . "\n"; exit(); } $pids[] = $pid; } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); }
Maintain the same structure and functionality when rewriting this code in PHP.
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) values := make([][]int, 10) for i := range values { values[i] = make([]int, 10) for j := range values[i] { values[i][j] = rand.Intn(20) + 1 } } outerLoop: for i, row := range values { fmt.Printf("%3d)", i) for _, value := range row { fmt.Printf(" %3d", value) if value == 20 { break outerLoop } } fmt.Printf("\n") } fmt.Printf("\n") }
<?php for ($i = 0; $i < 10; $i++) for ($j = 0; $j < 10; $j++) $a[$i][$j] = rand(1, 20); foreach ($a as $row) { foreach ($row as $element) { echo " $element"; if ($element == 20) break 2; // 2 is the number of loops we want to break out of } echo "\n"; } echo "\n"; ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) values := make([][]int, 10) for i := range values { values[i] = make([]int, 10) for j := range values[i] { values[i][j] = rand.Intn(20) + 1 } } outerLoop: for i, row := range values { fmt.Printf("%3d)", i) for _, value := range row { fmt.Printf(" %3d", value) if value == 20 { break outerLoop } } fmt.Printf("\n") } fmt.Printf("\n") }
<?php for ($i = 0; $i < 10; $i++) for ($j = 0; $j < 10; $j++) $a[$i][$j] = rand(1, 20); foreach ($a as $row) { foreach ($row as $element) { echo " $element"; if ($element == 20) break 2; // 2 is the number of loops we want to break out of } echo "\n"; } echo "\n"; ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
Rewrite the snippet below in PHP so it works the same as the original Go code.
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
Translate this program into PHP but keep the logic exactly as in Go.
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
Can you help me rewrite this code in PHP instead of Go, keeping it the same logically?
package main import "fmt" var total, prim, maxPeri int64 func newTri(s0, s1, s2 int64) { if p := s0 + s1 + s2; p <= maxPeri { prim++ total += maxPeri / p newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2) newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2) newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2) } } func main() { for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 { prim = 0 total = 0 newTri(3, 4, 5) fmt.Printf("Up to %d: %d triples, %d primitives\n", maxPeri, total, prim) } }
<?php function gcd($a, $b) { if ($a == 0) return $b; if ($b == 0) return $a; if($a == $b) return $a; if($a > $b) return gcd($a-$b, $b); return gcd($a, $b-$a); } $pytha = 0; $prim = 0; $max_p = 100; for ($a = 1; $a <= $max_p / 3; $a++) { $aa = $a**2; for ($b = $a + 1; $b < $max_p/2; $b++) { $bb = $b**2; for ($c = $b + 1; $c < $max_p/2; $c++) { $cc = $c**2; if ($aa + $bb < $cc) break; if ($a + $b + $c > $max_p) break; if ($aa + $bb == $cc) { $pytha++; if (gcd($a, $b) == 1) $prim++; } } } } echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';
Keep all operations the same but rewrite the snippet in PHP.
package main import "fmt" func uniq(list []int) []int { unique_set := make(map[int]bool, len(list)) for _, x := range list { unique_set[x] = true } result := make([]int, 0, len(unique_set)) for x := range unique_set { result = append(result, x) } return result } func main() { fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) }
$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'); $unique_list = array_unique($list);
Convert this Go block to PHP, preserving its control flow and logic.
package main import "fmt" func uniq(list []int) []int { unique_set := make(map[int]bool, len(list)) for _, x := range list { unique_set[x] = true } result := make([]int, 0, len(unique_set)) for x := range unique_set { result = append(result, x) } return result } func main() { fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) }
$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'); $unique_list = array_unique($list);
Keep all operations the same but rewrite the snippet in PHP.
package main import ( "fmt" "strconv" ) func lss(s string) (r string) { c := s[0] nc := 1 for i := 1; i < len(s); i++ { d := s[i] if d == c { nc++ continue } r += strconv.Itoa(nc) + string(c) c = d nc = 1 } return r + strconv.Itoa(nc) + string(c) } func main() { s := "1" fmt.Println(s) for i := 0; i < 8; i++ { s = lss(s) fmt.Println(s) } }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Transform the following Go implementation into PHP, maintaining the same output and logic.
package main import ( "fmt" "strconv" ) func lss(s string) (r string) { c := s[0] nc := 1 for i := 1; i < len(s); i++ { d := s[i] if d == c { nc++ continue } r += strconv.Itoa(nc) + string(c) c = d nc = 1 } return r + strconv.Itoa(nc) + string(c) } func main() { s := "1" fmt.Println(s) for i := 0; i < 8; i++ { s = lss(s) fmt.Println(s) } }
<?php function lookAndSay($str) { return preg_replace_callback('#(.)\1*#', function($matches) { return strlen($matches[0]).$matches[1]; }, $str); } $num = "1"; foreach(range(1,10) as $i) { echo $num."<br/>"; $num = lookAndSay($num); } ?>
Produce a language-to-language conversion: from Go to PHP, same semantics.
var intStack []int
$stack = array(); empty( $stack ); // true array_push( $stack, 1 ); // or $stack[] = 1; array_push( $stack, 2 ); // or $stack[] = 2; empty( $stack ); // false echo array_pop( $stack ); // outputs "2" echo array_pop( $stack ); // outputs "1"
Keep all operations the same but rewrite the snippet in PHP.
var intStack []int
$stack = array(); empty( $stack ); // true array_push( $stack, 1 ); // or $stack[] = 1; array_push( $stack, 2 ); // or $stack[] = 2; empty( $stack ); // false echo array_pop( $stack ); // outputs "2" echo array_pop( $stack ); // outputs "1"
Produce a functionally identical PHP code for the snippet given in Go.
if booleanExpression { statements }
<?php $foo = 3; if ($foo == 2) if ($foo == 3) else if ($foo != 0) { } else { } ?>
Ensure the translated PHP code behaves exactly like the original Go snippet.
if booleanExpression { statements }
<?php $foo = 3; if ($foo == 2) if ($foo == 3) else if ($foo != 0) { } else { } ?>
Generate a PHP translation of this Go snippet without changing its computational steps.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) stoogesort(a) fmt.Println("after: ", a) fmt.Println("nyuk nyuk nyuk") } func stoogesort(a []int) { last := len(a) - 1 if a[last] < a[0] { a[0], a[last] = a[last], a[0] } if last > 1 { t := len(a) / 3 stoogesort(a[:len(a)-t]) stoogesort(a[t:]) stoogesort(a[:len(a)-t]) } }
function stoogeSort(&$arr, $i, $j) { if($arr[$j] < $arr[$i]) { list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); } if(($j - $i) > 1) { $t = ($j - $i + 1) / 3; stoogesort($arr, $i, $j - $t); stoogesort($arr, $i + $t, $j); stoogesort($arr, $i, $j - $t); } }
Convert this Go snippet to PHP and keep its semantics consistent.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) stoogesort(a) fmt.Println("after: ", a) fmt.Println("nyuk nyuk nyuk") } func stoogesort(a []int) { last := len(a) - 1 if a[last] < a[0] { a[0], a[last] = a[last], a[0] } if last > 1 { t := len(a) / 3 stoogesort(a[:len(a)-t]) stoogesort(a[t:]) stoogesort(a[:len(a)-t]) } }
function stoogeSort(&$arr, $i, $j) { if($arr[$j] < $arr[$i]) { list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); } if(($j - $i) > 1) { $t = ($j - $i + 1) / 3; stoogesort($arr, $i, $j - $t); stoogesort($arr, $i + $t, $j); stoogesort($arr, $i, $j - $t); } }
Write the same algorithm in PHP as shown in this Go implementation.
package config import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" ) var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") ) type varError struct { err error n string t VarType } func (err *varError) Error() string { return fmt.Sprintf("%v: (%q, %v)", err.err, err.n, err.t) } type VarType int const ( Bool VarType = 1 + iota Array String ) func (t VarType) String() string { switch t { case Bool: return "Bool" case Array: return "Array" case String: return "String" } panic("Unknown VarType") } type confvar struct { Type VarType Val interface{} } type Config struct { m map[string]confvar } func Parse(r io.Reader) (c *Config, err error) { c = new(Config) c.m = make(map[string]confvar) buf, err := ioutil.ReadAll(r) if err != nil { return } lines := bytes.Split(buf, []byte{'\n'}) for _, line := range lines { line = bytes.TrimSpace(line) if len(line) == 0 { continue } switch line[0] { case '#', ';': continue } parts := bytes.SplitN(line, []byte{' '}, 2) nam := string(bytes.ToLower(parts[0])) if len(parts) == 1 { c.m[nam] = confvar{Bool, true} continue } if strings.Contains(string(parts[1]), ",") { tmpB := bytes.Split(parts[1], []byte{','}) for i := range tmpB { tmpB[i] = bytes.TrimSpace(tmpB[i]) } tmpS := make([]string, 0, len(tmpB)) for i := range tmpB { tmpS = append(tmpS, string(tmpB[i])) } c.m[nam] = confvar{Array, tmpS} continue } c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))} } return } func (c *Config) Bool(name string) (bool, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return false, nil } if c.m[name].Type != Bool { return false, &varError{EBADTYPE, name, Bool} } v, ok := c.m[name].Val.(bool) if !ok { return false, &varError{EBADVAL, name, Bool} } return v, nil } func (c *Config) Array(name string) ([]string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return nil, &varError{ENONE, name, Array} } if c.m[name].Type != Array { return nil, &varError{EBADTYPE, name, Array} } v, ok := c.m[name].Val.([]string) if !ok { return nil, &varError{EBADVAL, name, Array} } return v, nil } func (c *Config) String(name string) (string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return "", &varError{ENONE, name, String} } if c.m[name].Type != String { return "", &varError{EBADTYPE, name, String} } v, ok := c.m[name].Val.(string) if !ok { return "", &varError{EBADVAL, name, String} } return v, nil }
<?php $conf = file_get_contents('parse-conf-file.txt'); $conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf); $conf = preg_replace_callback( '/^([a-z]+)\s*=((?=.*\,.*).*)$/mi', function ($matches) { $r = ''; foreach (explode(',', $matches[2]) AS $val) { $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL; } return $r; }, $conf ); $conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf); $ini = parse_ini_string($conf); echo 'Full name = ', $ini['FULLNAME'], PHP_EOL; echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL; echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL; echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL; echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
Preserve the algorithm and functionality while converting the code from Go to PHP.
package config import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" ) var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") ) type varError struct { err error n string t VarType } func (err *varError) Error() string { return fmt.Sprintf("%v: (%q, %v)", err.err, err.n, err.t) } type VarType int const ( Bool VarType = 1 + iota Array String ) func (t VarType) String() string { switch t { case Bool: return "Bool" case Array: return "Array" case String: return "String" } panic("Unknown VarType") } type confvar struct { Type VarType Val interface{} } type Config struct { m map[string]confvar } func Parse(r io.Reader) (c *Config, err error) { c = new(Config) c.m = make(map[string]confvar) buf, err := ioutil.ReadAll(r) if err != nil { return } lines := bytes.Split(buf, []byte{'\n'}) for _, line := range lines { line = bytes.TrimSpace(line) if len(line) == 0 { continue } switch line[0] { case '#', ';': continue } parts := bytes.SplitN(line, []byte{' '}, 2) nam := string(bytes.ToLower(parts[0])) if len(parts) == 1 { c.m[nam] = confvar{Bool, true} continue } if strings.Contains(string(parts[1]), ",") { tmpB := bytes.Split(parts[1], []byte{','}) for i := range tmpB { tmpB[i] = bytes.TrimSpace(tmpB[i]) } tmpS := make([]string, 0, len(tmpB)) for i := range tmpB { tmpS = append(tmpS, string(tmpB[i])) } c.m[nam] = confvar{Array, tmpS} continue } c.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))} } return } func (c *Config) Bool(name string) (bool, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return false, nil } if c.m[name].Type != Bool { return false, &varError{EBADTYPE, name, Bool} } v, ok := c.m[name].Val.(bool) if !ok { return false, &varError{EBADVAL, name, Bool} } return v, nil } func (c *Config) Array(name string) ([]string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return nil, &varError{ENONE, name, Array} } if c.m[name].Type != Array { return nil, &varError{EBADTYPE, name, Array} } v, ok := c.m[name].Val.([]string) if !ok { return nil, &varError{EBADVAL, name, Array} } return v, nil } func (c *Config) String(name string) (string, error) { name = strings.ToLower(name) if _, ok := c.m[name]; !ok { return "", &varError{ENONE, name, String} } if c.m[name].Type != String { return "", &varError{EBADTYPE, name, String} } v, ok := c.m[name].Val.(string) if !ok { return "", &varError{EBADVAL, name, String} } return v, nil }
<?php $conf = file_get_contents('parse-conf-file.txt'); $conf = preg_replace('/^([a-z]+)/mi', '$1 =', $conf); $conf = preg_replace_callback( '/^([a-z]+)\s*=((?=.*\,.*).*)$/mi', function ($matches) { $r = ''; foreach (explode(',', $matches[2]) AS $val) { $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL; } return $r; }, $conf ); $conf = preg_replace('/^([a-z]+)\s*=$/mi', '$1 = true', $conf); $ini = parse_ini_string($conf); echo 'Full name = ', $ini['FULLNAME'], PHP_EOL; echo 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL; echo 'Need spelling = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL; echo 'Seeds removed = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL; echo 'Other family = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;
Convert this Go block to PHP, preserving its control flow and logic.
package main import ( "fmt" "sort" "strings" ) type sortable []string func (s sortable) Len() int { return len(s) } func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortable) Less(i, j int) bool { a, b := s[i], s[j] if len(a) != len(b) { return len(a) > len(b) } return strings.ToLower(a) < strings.ToLower(b) } func main() { var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") fmt.Println(s, "(original)") sort.Sort(s) fmt.Println(s, "(sorted)") }
<?php function mycmp($s1, $s2) { if ($d = strlen($s2) - strlen($s1)) return $d; return strcasecmp($s1, $s2); } $strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted"); usort($strings, "mycmp"); ?>
Generate an equivalent PHP version of this Go code.
package main import ( "fmt" "sort" "strings" ) type sortable []string func (s sortable) Len() int { return len(s) } func (s sortable) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s sortable) Less(i, j int) bool { a, b := s[i], s[j] if len(a) != len(b) { return len(a) > len(b) } return strings.ToLower(a) < strings.ToLower(b) } func main() { var s sortable = strings.Fields("To tell your name the livelong day To an admiring bog") fmt.Println(s, "(original)") sort.Sort(s) fmt.Println(s, "(sorted)") }
<?php function mycmp($s1, $s2) { if ($d = strlen($s2) - strlen($s1)) return $d; return strcasecmp($s1, $s2); } $strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted"); usort($strings, "mycmp"); ?>
Keep all operations the same but rewrite the snippet in PHP.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) selectionSort(a) fmt.Println("after: ", a) } func selectionSort(a []int) { last := len(a) - 1 for i := 0; i < last; i++ { aMin := a[i] iMin := i for j := i + 1; j < len(a); j++ { if a[j] < aMin { aMin = a[j] iMin = j } } a[i], a[iMin] = aMin, a[i] } }
function selection_sort(&$arr) { $n = count($arr); for($i = 0; $i < count($arr); $i++) { $min = $i; for($j = $i + 1; $j < $n; $j++){ if($arr[$j] < $arr[$min]){ $min = $j; } } list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]); } }
Write the same code in PHP as shown below in Go.
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) selectionSort(a) fmt.Println("after: ", a) } func selectionSort(a []int) { last := len(a) - 1 for i := 0; i < last; i++ { aMin := a[i] iMin := i for j := i + 1; j < len(a); j++ { if a[j] < aMin { aMin = a[j] iMin = j } } a[i], a[iMin] = aMin, a[i] } }
function selection_sort(&$arr) { $n = count($arr); for($i = 0; $i < count($arr); $i++) { $min = $i; for($j = $i + 1; $j < $n; $j++){ if($arr[$j] < $arr[$min]){ $min = $j; } } list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]); } }
Write the same code in PHP as shown below in Go.
package main import "fmt" func main() { for _, i := range []int{1, 2, 3, 4, 5} { fmt.Println(i * i) } }
function cube($n) { return($n * $n * $n); } $a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b);
Maintain the same structure and functionality when rewriting this code in PHP.
package main import "fmt" func main() { for _, i := range []int{1, 2, 3, 4, 5} { fmt.Println(i * i) } }
function cube($n) { return($n * $n * $n); } $a = array(1, 2, 3, 4, 5); $b = array_map("cube", $a); print_r($b);
Port the following code from Go to PHP with equivalent syntax and logic.
package main import ( "log" "math/rand" "sync" "time" ) var ( instance string once sync.Once ) func claim(color string, w *sync.WaitGroup) { time.Sleep(time.Duration(rand.Intn(1e8))) log.Println("trying to claim", color) once.Do(func() { instance = color }) log.Printf("tried %s. instance: %s", color, instance) w.Done() } func main() { rand.Seed(time.Now().Unix()) var w sync.WaitGroup w.Add(2) go claim("red", &w) go claim("blue", &w) w.Wait() log.Println("after trying both, instance =", instance) }
class Singleton { protected static $instance = null; public $test_var; private function __construct(){ } public static function getInstance(){ if (is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } } $foo = Singleton::getInstance(); $foo->test_var = 'One'; $bar = Singleton::getInstance(); echo $bar->test_var; //Prints 'One' $fail = new Singleton(); //Fatal error
Preserve the algorithm and functionality while converting the code from Go to PHP.
package main import ( "log" "math/rand" "sync" "time" ) var ( instance string once sync.Once ) func claim(color string, w *sync.WaitGroup) { time.Sleep(time.Duration(rand.Intn(1e8))) log.Println("trying to claim", color) once.Do(func() { instance = color }) log.Printf("tried %s. instance: %s", color, instance) w.Done() } func main() { rand.Seed(time.Now().Unix()) var w sync.WaitGroup w.Add(2) go claim("red", &w) go claim("blue", &w) w.Wait() log.Println("after trying both, instance =", instance) }
class Singleton { protected static $instance = null; public $test_var; private function __construct(){ } public static function getInstance(){ if (is_null(self::$instance)){ self::$instance = new self(); } return self::$instance; } } $foo = Singleton::getInstance(); $foo->test_var = 'One'; $bar = Singleton::getInstance(); echo $bar->test_var; //Prints 'One' $fail = new Singleton(); //Fatal error
Convert this Go block to PHP, preserving its control flow and logic.
package dogs import "fmt" var dog = "Salt" var Dog = "Pepper" var DOG = "Mustard" func PackageSees() map[*string]int { fmt.Println("Package sees:", dog, Dog, DOG) return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1} }
<?php $dog = 'Benjamin'; $Dog = 'Samba'; $DOG = 'Bernie'; echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n"; function DOG() { return 'Bernie'; } echo 'There is only 1 dog named ' . dog() . "\n";
Port the following code from Go to PHP with equivalent syntax and logic.
package dogs import "fmt" var dog = "Salt" var Dog = "Pepper" var DOG = "Mustard" func PackageSees() map[*string]int { fmt.Println("Package sees:", dog, Dog, DOG) return map[*string]int{&dog: 1, &Dog: 1, &DOG: 1} }
<?php $dog = 'Benjamin'; $Dog = 'Samba'; $DOG = 'Bernie'; echo "There are 3 dogs named {$dog}, {$Dog} and {$DOG}\n"; function DOG() { return 'Bernie'; } echo 'There is only 1 dog named ' . dog() . "\n";
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
for i := 10; i >= 0; i-- { fmt.Println(i) }
for ($i = 10; $i >= 0; $i--) echo "$i\n";
Change the following Go code into PHP without altering its purpose.
for i := 10; i >= 0; i-- { fmt.Println(i) }
for ($i = 10; $i >= 0; $i--) echo "$i\n";
Convert this Go block to PHP, preserving its control flow and logic.
import "io/ioutil" func main() { ioutil.WriteFile("path/to/your.file", []byte("data"), 0644) }
file_put_contents($filename, $data)
Port the provided Go code into PHP while preserving the original functionality.
import "io/ioutil" func main() { ioutil.WriteFile("path/to/your.file", []byte("data"), 0644) }
file_put_contents($filename, $data)
Generate an equivalent PHP version of this Go code.
package main import "fmt" func main() { for i := 1; i <= 5; i++ { for j := 1; j <= i; j++ { fmt.Printf("*") } fmt.Printf("\n") } }
for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo '*'; } echo "\n"; }
Produce a functionally identical PHP code for the snippet given in Go.
package main import "fmt" func main() { for i := 1; i <= 5; i++ { for j := 1; j <= i; j++ { fmt.Printf("*") } fmt.Printf("\n") } }
for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo '*'; } echo "\n"; }
Change the programming language of this snippet from Go to PHP without modifying what it does.
package main import "fmt" func d(b byte) byte { if b < '0' || b > '9' { panic("digit 0-9 expected") } return b - '0' } func add(x, y string) string { if len(y) > len(x) { x, y = y, x } b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { if i <= len(y) { c += d(y[len(y)-i]) } s := d(x[len(x)-i]) + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mulDigit(x string, y byte) string { if y == '0' { return "0" } y = d(y) b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { s := d(x[len(x)-i])*y + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mul(x, y string) string { result := mulDigit(x, y[len(y)-1]) for i, zeros := 2, ""; i <= len(y); i++ { zeros += "0" result = add(result, mulDigit(x, y[len(y)-i])+zeros) } return result } const n = "18446744073709551616" func main() { fmt.Println(mul(n, n)) }
<?php function longMult($a, $b) { $as = (string) $a; $bs = (string) $b; for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--) { for($p = 0; $p < $pi; $p++) { $regi[$ai][] = 0; } for($bi = strlen($bs) - 1; $bi >= 0; $bi--) { $regi[$ai][] = $as[$ai] * $bs[$bi]; } } return $regi; } function longAdd($arr) { $outer = count($arr); $inner = count($arr[$outer-1]) + $outer; for($i = 0; $i <= $inner; $i++) { for($o = 0; $o < $outer; $o++) { $val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0; @$sum[$i] += $val; } } return $sum; } function carry($arr) { for($i = 0; $i < count($arr); $i++) { $s = (string) $arr[$i]; switch(strlen($s)) { case 2: $arr[$i] = $s{1}; @$arr[$i+1] += $s{0}; break; case 3: $arr[$i] = $s{2}; @$arr[$i+1] += $s{0}.$s{1}; break; } } return ltrim(implode('',array_reverse($arr)),'0'); } function lm($a,$b) { return carry(longAdd(longMult($a,$b))); } if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456') { echo 'pass!'; }; // 2^64 * 2^64
Write a version of this Go function in PHP with identical behavior.
package main import "fmt" func d(b byte) byte { if b < '0' || b > '9' { panic("digit 0-9 expected") } return b - '0' } func add(x, y string) string { if len(y) > len(x) { x, y = y, x } b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { if i <= len(y) { c += d(y[len(y)-i]) } s := d(x[len(x)-i]) + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mulDigit(x string, y byte) string { if y == '0' { return "0" } y = d(y) b := make([]byte, len(x)+1) var c byte for i := 1; i <= len(x); i++ { s := d(x[len(x)-i])*y + c c = s / 10 b[len(b)-i] = (s % 10) + '0' } if c == 0 { return string(b[1:]) } b[0] = c + '0' return string(b) } func mul(x, y string) string { result := mulDigit(x, y[len(y)-1]) for i, zeros := 2, ""; i <= len(y); i++ { zeros += "0" result = add(result, mulDigit(x, y[len(y)-i])+zeros) } return result } const n = "18446744073709551616" func main() { fmt.Println(mul(n, n)) }
<?php function longMult($a, $b) { $as = (string) $a; $bs = (string) $b; for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--) { for($p = 0; $p < $pi; $p++) { $regi[$ai][] = 0; } for($bi = strlen($bs) - 1; $bi >= 0; $bi--) { $regi[$ai][] = $as[$ai] * $bs[$bi]; } } return $regi; } function longAdd($arr) { $outer = count($arr); $inner = count($arr[$outer-1]) + $outer; for($i = 0; $i <= $inner; $i++) { for($o = 0; $o < $outer; $o++) { $val = isset($arr[$o][$i]) ? $arr[$o][$i] : 0; @$sum[$i] += $val; } } return $sum; } function carry($arr) { for($i = 0; $i < count($arr); $i++) { $s = (string) $arr[$i]; switch(strlen($s)) { case 2: $arr[$i] = $s{1}; @$arr[$i+1] += $s{0}; break; case 3: $arr[$i] = $s{2}; @$arr[$i+1] += $s{0}.$s{1}; break; } } return ltrim(implode('',array_reverse($arr)),'0'); } function lm($a,$b) { return carry(longAdd(longMult($a,$b))); } if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456') { echo 'pass!'; }; // 2^64 * 2^64
Write the same algorithm in PHP as shown in this Go implementation.
package main import ( "bufio" "bytes" "fmt" "math/rand" "os" "strings" "time" ) func main() { fmt.Println(`Cows and Bulls Guess four digit number of unique digits in the range 1 to 9. A correct digit but not in the correct place is a cow. A correct digit in the correct place is a bull.`) pat := make([]byte, 4) rand.Seed(time.Now().Unix()) r := rand.Perm(9) for i := range pat { pat[i] = '1' + byte(r[i]) } valid := []byte("123456789") guess: for in := bufio.NewReader(os.Stdin); ; { fmt.Print("Guess: ") guess, err := in.ReadString('\n') if err != nil { fmt.Println("\nSo, bye.") return } guess = strings.TrimSpace(guess) if len(guess) != 4 { fmt.Println("Please guess a four digit number.") continue } var cows, bulls int for ig, cg := range guess { if strings.IndexRune(guess[:ig], cg) >= 0 { fmt.Printf("Repeated digit: %c\n", cg) continue guess } switch bytes.IndexByte(pat, byte(cg)) { case -1: if bytes.IndexByte(valid, byte(cg)) == -1 { fmt.Printf("Invalid digit: %c\n", cg) continue guess } default: cows++ case ig: bulls++ } } fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls) if bulls == 4 { fmt.Println("You got it.") return } } }
<?php $size = 4; $chosen = implode(array_rand(array_flip(range(1,9)), $size)); echo "I've chosen a number from $size unique digits from 1 to 9; you need to input $size unique digits to guess my number\n"; for ($guesses = 1; ; $guesses++) { while (true) { echo "\nNext guess [$guesses]: "; $guess = rtrim(fgets(STDIN)); if (!checkguess($guess)) echo "$size digits, no repetition, no 0... retry\n"; else break; } if ($guess == $chosen) { echo "You did it in $guesses attempts!\n"; break; } else { $bulls = 0; $cows = 0; foreach (range(0, $size-1) as $i) { if ($guess[$i] == $chosen[$i]) $bulls++; else if (strpos($chosen, $guess[$i]) !== FALSE) $cows++; } echo "$cows cows, $bulls bulls\n"; } } function checkguess($g) { global $size; return count(array_unique(str_split($g))) == $size && preg_match("/^[1-9]{{$size}}$/", $g); } ?>
Write a version of this Go function in PHP with identical behavior.
package main import ( "bufio" "bytes" "fmt" "math/rand" "os" "strings" "time" ) func main() { fmt.Println(`Cows and Bulls Guess four digit number of unique digits in the range 1 to 9. A correct digit but not in the correct place is a cow. A correct digit in the correct place is a bull.`) pat := make([]byte, 4) rand.Seed(time.Now().Unix()) r := rand.Perm(9) for i := range pat { pat[i] = '1' + byte(r[i]) } valid := []byte("123456789") guess: for in := bufio.NewReader(os.Stdin); ; { fmt.Print("Guess: ") guess, err := in.ReadString('\n') if err != nil { fmt.Println("\nSo, bye.") return } guess = strings.TrimSpace(guess) if len(guess) != 4 { fmt.Println("Please guess a four digit number.") continue } var cows, bulls int for ig, cg := range guess { if strings.IndexRune(guess[:ig], cg) >= 0 { fmt.Printf("Repeated digit: %c\n", cg) continue guess } switch bytes.IndexByte(pat, byte(cg)) { case -1: if bytes.IndexByte(valid, byte(cg)) == -1 { fmt.Printf("Invalid digit: %c\n", cg) continue guess } default: cows++ case ig: bulls++ } } fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls) if bulls == 4 { fmt.Println("You got it.") return } } }
<?php $size = 4; $chosen = implode(array_rand(array_flip(range(1,9)), $size)); echo "I've chosen a number from $size unique digits from 1 to 9; you need to input $size unique digits to guess my number\n"; for ($guesses = 1; ; $guesses++) { while (true) { echo "\nNext guess [$guesses]: "; $guess = rtrim(fgets(STDIN)); if (!checkguess($guess)) echo "$size digits, no repetition, no 0... retry\n"; else break; } if ($guess == $chosen) { echo "You did it in $guesses attempts!\n"; break; } else { $bulls = 0; $cows = 0; foreach (range(0, $size-1) as $i) { if ($guess[$i] == $chosen[$i]) $bulls++; else if (strpos($chosen, $guess[$i]) !== FALSE) $cows++; } echo "$cows cows, $bulls bulls\n"; } } function checkguess($g) { global $size; return count(array_unique(str_split($g))) == $size && preg_match("/^[1-9]{{$size}}$/", $g); } ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
package main import "fmt" func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list) bubblesort(list) fmt.Println("sorted! ", list) } func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } }
function bubbleSort(array $array){ foreach($array as $i => &$val){ foreach($array as $k => &$val2){ if($k <= $i) continue; if($val > $val2) { list($val, $val2) = [$val2, $val]; break; } } } return $array; }
Write a version of this Go function in PHP with identical behavior.
package main import "fmt" func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list) bubblesort(list) fmt.Println("sorted! ", list) } func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } }
function bubbleSort(array $array){ foreach($array as $i => &$val){ foreach($array as $k => &$val2){ if($k <= $i) continue; if($val > $val2) { list($val, $val2) = [$val2, $val]; break; } } } return $array; }
Rewrite this program in PHP while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "io/ioutil" ) func main() { b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) } }
<?php if (!$in = fopen('input.txt', 'r')) { die('Could not open input file.'); } if (!$out = fopen('output.txt', 'w')) { die('Could not open output file.'); } while (!feof($in)) { $data = fread($in, 512); fwrite($out, $data); } fclose($out); fclose($in); ?>
Produce a functionally identical PHP code for the snippet given in Go.
package main import ( "fmt" "io/ioutil" ) func main() { b, err := ioutil.ReadFile("input.txt") if err != nil { fmt.Println(err) return } if err = ioutil.WriteFile("output.txt", b, 0666); err != nil { fmt.Println(err) } }
<?php if (!$in = fopen('input.txt', 'r')) { die('Could not open input file.'); } if (!$out = fopen('output.txt', 'w')) { die('Could not open output file.'); } while (!feof($in)) { $data = fread($in, 512); fwrite($out, $data); } fclose($out); fclose($in); ?>
Convert this Go block to PHP, preserving its control flow and logic.
package main import "fmt" func main() { var a, b int fmt.Print("enter two integers: ") fmt.Scanln(&a, &b) fmt.Printf("%d + %d = %d\n", a, b, a+b) fmt.Printf("%d - %d = %d\n", a, b, a-b) fmt.Printf("%d * %d = %d\n", a, b, a*b) fmt.Printf("%d / %d = %d\n", a, b, a/b) fmt.Printf("%d %% %d = %d\n", a, b, a%b) }
<?php $a = fgets(STDIN); $b = fgets(STDIN); echo "sum: ", $a + $b, "\n", "difference: ", $a - $b, "\n", "product: ", $a * $b, "\n", "truncating quotient: ", (int)($a / $b), "\n", "flooring quotient: ", floor($a / $b), "\n", "remainder: ", $a % $b, "\n", "power: ", $a ** $b, "\n"; // PHP 5.6+ only ?>
Write the same code in PHP as shown below in Go.
package main import "fmt" func main() { var a, b int fmt.Print("enter two integers: ") fmt.Scanln(&a, &b) fmt.Printf("%d + %d = %d\n", a, b, a+b) fmt.Printf("%d - %d = %d\n", a, b, a-b) fmt.Printf("%d * %d = %d\n", a, b, a*b) fmt.Printf("%d / %d = %d\n", a, b, a/b) fmt.Printf("%d %% %d = %d\n", a, b, a%b) }
<?php $a = fgets(STDIN); $b = fgets(STDIN); echo "sum: ", $a + $b, "\n", "difference: ", $a - $b, "\n", "product: ", $a * $b, "\n", "truncating quotient: ", (int)($a / $b), "\n", "flooring quotient: ", floor($a / $b), "\n", "remainder: ", $a % $b, "\n", "power: ", $a ** $b, "\n"; // PHP 5.6+ only ?>