Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Preserve the algorithm and functionality while converting the code from REXX to C#.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Convert the following code from REXX to C++, ensuring the logic remains intact.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Port the provided REXX code into C++ while preserving the original functionality.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Port the following code from REXX to Java with equivalent syntax and logic.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Generate a Java translation of this REXX snippet without changing its computational steps.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Generate an equivalent Python version of this REXX code.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Rewrite the snippet below in Python so it works the same as the original REXX code.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Write the same code in VB as shown below in REXX.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Produce a functionally identical VB code for the snippet given in REXX.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Convert this REXX block to Go, preserving its control flow and logic.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Transform the following REXX implementation into Go, maintaining the same output and logic.
numeric digits 10000 Ao = '+-0++0+' ; Abt = Ao Bo = '-436' ; Bbt = d2bt(Bo); @ = "(decimal)" Co = '+-++-' ; Cbt = Co ; @@ = "balanced ternary =" call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) call btShow '[a*(b-c)]', $bt exit 0 d2bt: procedure; parse arg x 1; x= x / 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= do until x==0; _= (x // (3** (p+1) ) ) % 3**p if _== 2 then _= -1 else if _== -2 then _= 1 x= x - _ * (3**p); p= p + 1; #= $._ || # end bt2d: procedure; parse arg x; r= reverse(x); $.= -1; $.0= 0; #= 0; _= '+'; $._= 1 do j=1 for length(x); _= substr(r, j, 1); #= # + $._ * 3 ** (j-1) end btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 @.= 0; _= '-'; @._= -1; _= "+"; @._= 1; $.= '-'; $.0= 0; $.1= "+"; #= do j=1 for max( length(x), length(y) ) x_= substr(rx, j, 1); xn= @.x_ y_= substr(ry, j, 1); yn= @.y_ s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end #= $.s || # end if carry\==0 then #= $.carry || #; return btNorm(#) btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0; S= 1; P=0 x= btNorm(x); y= btNorm(y); Lx= length(x); Ly= length(y) if x1=='-' then do; x= btNeg(x); S= -S; end if y1=='-' then do; y= btNeg(y); S= -S; end if Ly>Lx then parse value x y with y x do until y==0 P= btAdd(P, x ) y= btSub(y, '+') end if S==-1 then P= btNeg(P); return P btNeg: return translate( arg(1), '-+', "+-") btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ btSub: return btAdd( arg(1), btNeg( arg(2) ) ) btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Produce a functionally identical C code for the snippet given in Ruby.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Write a version of this Ruby function in C with identical behavior.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Ensure the translated C# code behaves exactly like the original Ruby snippet.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Convert this Ruby block to C++, preserving its control flow and logic.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Keep all operations the same but rewrite the snippet in C++.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Preserve the algorithm and functionality while converting the code from Ruby to Java.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Port the following code from Ruby to Java with equivalent syntax and logic.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Transform the following Ruby implementation into Python, maintaining the same output and logic.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Write a version of this Ruby function in Python with identical behavior.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Transform the following Ruby implementation into VB, maintaining the same output and logic.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Ensure the translated VB code behaves exactly like the original Ruby snippet.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Generate an equivalent Go version of this Ruby code.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Write the same algorithm in Go as shown in this Ruby implementation.
class BalancedTernary include Comparable def initialize(str = "") if str =~ /[^-+0]+/ raise ArgumentError, "invalid BalancedTernary number: end @digits = trim0(str) end I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]} def self.from_int(value) n = value.to_i digits = "" while n != 0 quo, rem = n.divmod(3) bt, carry = I2BT[rem] digits = bt + digits n = quo + carry end new(digits) end BT2I = {"-" => -1, "0" => 0, "+" => 1} def to_int @digits.chars.inject(0) do |sum, char| sum = 3 * sum + BT2I[char] end end alias :to_i :to_int def to_s @digits.dup end alias :inspect :to_s def <=>(other) to_i <=> other.to_i end ADDITION_TABLE = { "---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"], "-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"], "-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"], "0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"], "00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"], "0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"], "+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"], "+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"], "++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"], } def +(other) maxl = [to_s.length, other.to_s.length].max a = pad0_reverse(to_s, maxl) b = pad0_reverse(other.to_s, maxl) carry = "0" sum = a.zip( b ).inject("") do |sum, (c1, c2)| carry, digit = ADDITION_TABLE[carry + c1 + c2] sum = digit + sum end self.class.new(carry + sum) end MULTIPLICATION_TABLE = { "-" => "+0-", "0" => "000", "+" => "-0+", } def *(other) product = self.class.new other.to_s.each_char do |bdigit| row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit]) product += self.class.new(row) product << 1 end product >> 1 end def -@() self.class.new(@digits.tr('-+','+-')) end def -(other) self + (-other) end def <<(count) @digits = trim0(@digits + "0"*count) self end def >>(count) @digits[-count..-1] = "" if count > 0 @digits = trim0(@digits) self end private def trim0(str) str = str.sub(/^0+/, "") str = "0" if str.empty? str end def pad0_reverse(str, len) str.rjust(len, "0").reverse.chars end end a = BalancedTernary.new("+-0++0+") b = BalancedTernary.from_int(-436) c = BalancedTernary.new("+-++-") %w[a b c a*(b-c)].each do |exp| val = eval(exp) puts "%8s :%13s,%8d" % [exp, val, val.to_i] end
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Write the same algorithm in C as shown in this Scala implementation.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Write the same code in C as shown below in Scala.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Translate the given Scala code snippet into C# without altering its behavior.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Translate this program into C# but keep the logic exactly as in Scala.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Preserve the algorithm and functionality while converting the code from Scala to C++.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Produce a functionally identical C++ code for the snippet given in Scala.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Produce a language-to-language conversion: from Scala to Java, same semantics.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Convert this Scala snippet to Java and keep its semantics consistent.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Maintain the same structure and functionality when rewriting this code in Python.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Maintain the same structure and functionality when rewriting this code in Python.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Generate a VB translation of this Scala snippet without changing its computational steps.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Rewrite this program in VB while keeping its functionality equivalent to the Scala version.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Write the same code in Go as shown below in Scala.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Generate a Go translation of this Scala snippet without changing its computational steps.
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Keep all operations the same but rewrite the snippet in C.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Port the following code from Tcl to C with equivalent syntax and logic.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Convert this Tcl block to C#, preserving its control flow and logic.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Write a version of this Tcl function in C# with identical behavior.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Maintain the same structure and functionality when rewriting this code in C++.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Convert the following code from Tcl to C++, ensuring the logic remains intact.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Generate an equivalent Java version of this Tcl code.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Convert this Tcl block to Java, preserving its control flow and logic.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Rewrite this program in Python while keeping its functionality equivalent to the Tcl version.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Can you help me rewrite this code in Python instead of Tcl, keeping it the same logically?
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Change the programming language of this snippet from Tcl to VB without modifying what it does.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Generate an equivalent VB version of this Tcl code.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Keep all operations the same but rewrite the snippet in Go.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Rewrite this program in Go while keeping its functionality equivalent to the Tcl version.
package require Tcl 8.5 proc bt-int b { set n 0 foreach c [split $b ""] { set n [expr {$n * 3}] switch -- $c { + { incr n 1 } - { incr n -1 } } } return $n } proc int-bt n { if {$n == 0} { return "0" } while {$n != 0} { lappend result [lindex {0 + -} [expr {$n % 3}]] set n [expr {$n / 3 + ($n%3 == 2)}] } return [join [lreverse $result] ""] } proc bt-neg b { string map {+ - - +} $b } proc bt-sub {a b} { bt-add $a [bt-neg $b] } proc bt-add-digits {a b c} { if {$a eq ""} {set a 0} if {$b eq ""} {set b 0} if {$a ne 0} {append a 1} if {$b ne 0} {append b 1} lindex {{0 -1} {+ -1} {- 0} {0 0} {+ 0} {- 1} {0 1}} [expr {$a+$b+$c+3}] } proc bt-add {a b} { set c 0 set result {} foreach ca [lreverse [split $a ""]] cb [lreverse [split $b ""]] { lassign [bt-add-digits $ca $cb $c] d c lappend result $d } if {$c ne "0"} {lappend result [lindex {0 + -} $c]} if {![llength $result]} {return "0"} string trimleft [join [lreverse $result] ""] 0 } proc bt-mul {a b} { if {$a eq "0" || $a eq "" || $b eq "0"} {return "0"} set sub [bt-mul [string range $a 0 end-1] $b]0 switch -- [string index $a end] { 0 { return $sub } + { return [bt-add $sub $b] } - { return [bt-sub $sub $b] } } }
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Port the following code from C to Rust with equivalent syntax and logic.
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
Keep all operations the same but rewrite the snippet in Rust.
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
Change the programming language of this snippet from C++ to Rust without modifying what it does.
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
Preserve the algorithm and functionality while converting the code from C++ to Rust.
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
Produce a language-to-language conversion: from Java to Rust, same semantics.
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
Please provide an equivalent version of this Java code in Rust.
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
Convert this Go block to Rust, preserving its control flow and logic.
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
Convert this Go snippet to Rust and keep its semantics consistent.
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
Convert this Rust snippet to Python and keep its semantics consistent.
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Can you help me rewrite this code in VB instead of Rust, keeping it the same logically?
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Rewrite the snippet below in Python so it works the same as the original Rust code.
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Convert this Rust snippet to VB and keep its semantics consistent.
use std::{ cmp::min, convert::{TryFrom, TryInto}, fmt, ops::{Add, Mul, Neg}, str::FromStr, }; fn main() -> Result<(), &'static str> { let a = BalancedTernary::from_str("+-0++0+")?; let b = BalancedTernary::from(-436); let c = BalancedTernary::from_str("+-++-")?; println!("a = {} = {}", a, i128::try_from(a.clone())?); println!("b = {} = {}", b, i128::try_from(b.clone())?); println!("c = {} = {}", c, i128::try_from(c.clone())?); let d = a * (b + -c); println!("a * (b - c) = {} = {}", d, i128::try_from(d.clone())?); let e = BalancedTernary::from_str( "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++", )?; assert_eq!(i128::try_from(e).is_err(), true); Ok(()) } #[derive(Clone, Copy, PartialEq)] enum Trit { Zero, Pos, Neg, } impl TryFrom<char> for Trit { type Error = &'static str; fn try_from(value: char) -> Result<Self, Self::Error> { match value { '0' => Ok(Self::Zero), '+' => Ok(Self::Pos), '-' => Ok(Self::Neg), _ => Err("Invalid character for balanced ternary"), } } } impl From<Trit> for char { fn from(x: Trit) -> Self { match x { Trit::Zero => '0', Trit::Pos => '+', Trit::Neg => '-', } } } impl Add for Trit { type Output = (Self, Self); fn add(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, x) | (x, Zero) => (Zero, x), (Pos, Neg) | (Neg, Pos) => (Zero, Zero), (Pos, Pos) => (Pos, Neg), (Neg, Neg) => (Neg, Pos), } } } impl Mul for Trit { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { use Trit::{Neg, Pos, Zero}; match (self, rhs) { (Zero, _) | (_, Zero) => Zero, (Pos, Pos) | (Neg, Neg) => Pos, (Pos, Neg) | (Neg, Pos) => Neg, } } } impl Neg for Trit { type Output = Self; fn neg(self) -> Self::Output { match self { Trit::Zero => Trit::Zero, Trit::Pos => Trit::Neg, Trit::Neg => Trit::Pos, } } } #[derive(Clone)] struct BalancedTernary(Vec<Trit>); impl fmt::Display for BalancedTernary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", self.0 .iter() .rev() .map(|&d| char::from(d)) .collect::<String>() ) } } impl Add for BalancedTernary { type Output = Self; fn add(self, rhs: Self) -> Self::Output { use Trit::Zero; fn trim(v: &mut Vec<Trit>) { while let Some(last_elem) = v.pop() { if last_elem != Zero { v.push(last_elem); break; } } } if rhs.0.is_empty() { if self.0.is_empty() { return BalancedTernary(vec![Zero]); } return self; } let length = min(self.0.len(), rhs.0.len()); let mut sum = Vec::new(); let mut carry = vec![Zero]; for i in 0..length { let (carry_dig, digit) = self.0[i] + rhs.0[i]; sum.push(digit); carry.push(carry_dig); } for i in length..self.0.len() { sum.push(self.0[i]); } for i in length..rhs.0.len() { sum.push(rhs.0[i]); } trim(&mut sum); trim(&mut carry); BalancedTernary(sum) + BalancedTernary(carry) } } impl Mul for BalancedTernary { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { let mut results = Vec::with_capacity(rhs.0.len()); for i in 0..rhs.0.len() { let mut digits = vec![Trit::Zero; i]; for j in 0..self.0.len() { digits.push(self.0[j] * rhs.0[i]); } results.push(BalancedTernary(digits)); } #[allow(clippy::suspicious_arithmetic_impl)] results .into_iter() .fold(BalancedTernary(vec![Trit::Zero]), |acc, x| acc + x) } } impl Neg for BalancedTernary { type Output = Self; fn neg(self) -> Self::Output { BalancedTernary(self.0.iter().map(|&x| -x).collect()) } } impl FromStr for BalancedTernary { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { s.chars() .rev() .map(|c| c.try_into()) .collect::<Result<_, _>>() .map(BalancedTernary) } } impl From<i128> for BalancedTernary { fn from(x: i128) -> Self { let mut v = Vec::new(); let mut curr = x; loop { let rem = curr % 3; match rem { 0 => v.push(Trit::Zero), 1 | -2 => v.push(Trit::Pos), 2 | -1 => v.push(Trit::Neg), _ => unreachable!(), } let offset = (rem as f64 / 3.0).round() as i128; curr = curr / 3 + offset; if curr == 0 { break; } } BalancedTernary(v) } } impl TryFrom<BalancedTernary> for i128 { type Error = &'static str; fn try_from(value: BalancedTernary) -> Result<Self, Self::Error> { value .0 .iter() .enumerate() .try_fold(0_i128, |acc, (i, character)| { let size_err = "Balanced ternary string is too large to fit into 16 bytes"; let index: u32 = i.try_into().map_err(|_| size_err)?; match character { Trit::Zero => Ok(acc), Trit::Pos => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_add(x)) .ok_or(size_err), Trit::Neg => 3_i128 .checked_pow(index) .and_then(|x| acc.checked_sub(x)) .ok_or(size_err), } }) } }
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Produce a language-to-language conversion: from Ada to C#, same semantics.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RosettaCode.SHA1 { [TestClass] public class SHA1CryptoServiceProviderTest { [TestMethod] public void TestComputeHash() { var input = new UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
Transform the following Ada implementation into C#, maintaining the same output and logic.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RosettaCode.SHA1 { [TestClass] public class SHA1CryptoServiceProviderTest { [TestMethod] public void TestComputeHash() { var input = new UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
Produce a functionally identical C code for the snippet given in Ada.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h> int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code"; SHA1(string, strlen(string), result); for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); return EXIT_SUCCESS; }
Produce a language-to-language conversion: from Ada to C, same semantics.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h> int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code"; SHA1(string, strlen(string), result); for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); return EXIT_SUCCESS; }
Generate a C++ translation of this Ada snippet without changing its computational steps.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
Rewrite this program in C++ while keeping its functionality equivalent to the Ada version.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
Write the same algorithm in Go as shown in this Ada implementation.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
package main import ( "crypto/sha1" "fmt" ) func main() { h := sha1.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
Rewrite the snippet below in Go so it works the same as the original Ada code.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
package main import ( "crypto/sha1" "fmt" ) func main() { h := sha1.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
Write the same code in Python as shown below in Ada.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
import crypto { sha1 } let hash = sha1.hexdigest('Ars longa, vita brevis') print hash
Produce a language-to-language conversion: from Ada to Python, same semantics.
with Ada.Text_IO; with GNAT.SHA1; procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
import crypto { sha1 } let hash = sha1.hexdigest('Ars longa, vita brevis') print hash
Preserve the algorithm and functionality while converting the code from Arturo to C.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h> int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code"; SHA1(string, strlen(string), result); for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); return EXIT_SUCCESS; }
Rewrite the snippet below in C so it works the same as the original Arturo code.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h> int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code"; SHA1(string, strlen(string), result); for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); return EXIT_SUCCESS; }
Please provide an equivalent version of this Arturo code in C#.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RosettaCode.SHA1 { [TestClass] public class SHA1CryptoServiceProviderTest { [TestMethod] public void TestComputeHash() { var input = new UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
Rewrite the snippet below in C# so it works the same as the original Arturo code.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RosettaCode.SHA1 { [TestClass] public class SHA1CryptoServiceProviderTest { [TestMethod] public void TestComputeHash() { var input = new UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
Change the following Arturo code into C++ without altering its purpose.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
Can you help me rewrite this code in C++ instead of Arturo, keeping it the same logically?
print digest.sha "The quick brown fox jumped over the lazy dog's back"
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
Preserve the algorithm and functionality while converting the code from Arturo to Python.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
import crypto { sha1 } let hash = sha1.hexdigest('Ars longa, vita brevis') print hash
Produce a functionally identical Python code for the snippet given in Arturo.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
import crypto { sha1 } let hash = sha1.hexdigest('Ars longa, vita brevis') print hash
Write the same algorithm in Go as shown in this Arturo implementation.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
package main import ( "crypto/sha1" "fmt" ) func main() { h := sha1.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
Rewrite the snippet below in Go so it works the same as the original Arturo code.
print digest.sha "The quick brown fox jumped over the lazy dog's back"
package main import ( "crypto/sha1" "fmt" ) func main() { h := sha1.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
Generate an equivalent C version of this AutoHotKey code.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h> int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code"; SHA1(string, strlen(string), result); for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); return EXIT_SUCCESS; }
Maintain the same structure and functionality when rewriting this code in C.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h> int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code"; SHA1(string, strlen(string), result); for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); return EXIT_SUCCESS; }
Translate this program into C# but keep the logic exactly as in AutoHotKey.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RosettaCode.SHA1 { [TestClass] public class SHA1CryptoServiceProviderTest { [TestMethod] public void TestComputeHash() { var input = new UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
Change the following AutoHotKey code into C# without altering its purpose.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RosettaCode.SHA1 { [TestClass] public class SHA1CryptoServiceProviderTest { [TestMethod] public void TestComputeHash() { var input = new UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
Change the programming language of this snippet from AutoHotKey to C++ without modifying what it does.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
Convert the following code from AutoHotKey to C++, ensuring the logic remains intact.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }
Produce a functionally identical Python code for the snippet given in AutoHotKey.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
import crypto { sha1 } let hash = sha1.hexdigest('Ars longa, vita brevis') print hash
Generate a Python translation of this AutoHotKey snippet without changing its computational steps.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
import crypto { sha1 } let hash = sha1.hexdigest('Ars longa, vita brevis') print hash
Port the following code from AutoHotKey to Go with equivalent syntax and logic.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
package main import ( "crypto/sha1" "fmt" ) func main() { h := sha1.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
Convert this AutoHotKey snippet to Go and keep its semantics consistent.
str := "Rosetta Code" MsgBox, % "String:`n" (str) "`n`nSHA:`n" SHA(str) SHA(string, encoding = "utf-8") { return CalcStringHash(string, 0x8004, encoding) } CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) { static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o } CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) { chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength) }
package main import ( "crypto/sha1" "fmt" ) func main() { h := sha1.New() h.Write([]byte("Rosetta Code")) fmt.Printf("%x\n", h.Sum(nil)) }
Convert the following code from BBC_Basic to C, ensuring the logic remains intact.
PRINT FNsha1("Rosetta Code") END DEF FNsha1(message$) LOCAL buflen%, buffer%, hprov%, hhash%, hash$, i% CALG_SHA1 = &8004 CRYPT_VERIFYCONTEXT = &F0000000 HP_HASHVAL = 2 PROV_RSA_FULL = 1 buflen% = 64 DIM buffer% LOCAL buflen%-1 SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT SYS "CryptCreateHash", hprov%, CALG_SHA1, 0, 0, ^hhash% SYS "CryptHashData", hhash%, message$, LEN(message$), 0 SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 SYS "CryptDestroyHash", hhash% SYS "CryptReleaseContext", hprov% FOR i% = 0 TO buflen%-1 hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) NEXT = hash$
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h> int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code"; SHA1(string, strlen(string), result); for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); return EXIT_SUCCESS; }
Produce a functionally identical C code for the snippet given in BBC_Basic.
PRINT FNsha1("Rosetta Code") END DEF FNsha1(message$) LOCAL buflen%, buffer%, hprov%, hhash%, hash$, i% CALG_SHA1 = &8004 CRYPT_VERIFYCONTEXT = &F0000000 HP_HASHVAL = 2 PROV_RSA_FULL = 1 buflen% = 64 DIM buffer% LOCAL buflen%-1 SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT SYS "CryptCreateHash", hprov%, CALG_SHA1, 0, 0, ^hhash% SYS "CryptHashData", hhash%, message$, LEN(message$), 0 SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 SYS "CryptDestroyHash", hhash% SYS "CryptReleaseContext", hprov% FOR i% = 0 TO buflen%-1 hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) NEXT = hash$
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h> int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code"; SHA1(string, strlen(string), result); for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGEST_LENGTH-1) ? ' ' : '\n'); return EXIT_SUCCESS; }
Write a version of this BBC_Basic function in C# with identical behavior.
PRINT FNsha1("Rosetta Code") END DEF FNsha1(message$) LOCAL buflen%, buffer%, hprov%, hhash%, hash$, i% CALG_SHA1 = &8004 CRYPT_VERIFYCONTEXT = &F0000000 HP_HASHVAL = 2 PROV_RSA_FULL = 1 buflen% = 64 DIM buffer% LOCAL buflen%-1 SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT SYS "CryptCreateHash", hprov%, CALG_SHA1, 0, 0, ^hhash% SYS "CryptHashData", hhash%, message$, LEN(message$), 0 SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 SYS "CryptDestroyHash", hhash% SYS "CryptReleaseContext", hprov% FOR i% = 0 TO buflen%-1 hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) NEXT = hash$
using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RosettaCode.SHA1 { [TestClass] public class SHA1CryptoServiceProviderTest { [TestMethod] public void TestComputeHash() { var input = new UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
Transform the following BBC_Basic implementation into C#, maintaining the same output and logic.
PRINT FNsha1("Rosetta Code") END DEF FNsha1(message$) LOCAL buflen%, buffer%, hprov%, hhash%, hash$, i% CALG_SHA1 = &8004 CRYPT_VERIFYCONTEXT = &F0000000 HP_HASHVAL = 2 PROV_RSA_FULL = 1 buflen% = 64 DIM buffer% LOCAL buflen%-1 SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT SYS "CryptCreateHash", hprov%, CALG_SHA1, 0, 0, ^hhash% SYS "CryptHashData", hhash%, message$, LEN(message$), 0 SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 SYS "CryptDestroyHash", hhash% SYS "CryptReleaseContext", hprov% FOR i% = 0 TO buflen%-1 hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) NEXT = hash$
using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace RosettaCode.SHA1 { [TestClass] public class SHA1CryptoServiceProviderTest { [TestMethod] public void TestComputeHash() { var input = new UTF8Encoding().GetBytes("Rosetta Code"); var output = new SHA1CryptoServiceProvider().ComputeHash(input); Assert.AreEqual( "48-C9-8F-7E-5A-6E-73-6D-79-0A-B7-40-DF-C3-F5-1A-61-AB-E2-B5", BitConverter.ToString(output)); } } }
Please provide an equivalent version of this BBC_Basic code in C++.
PRINT FNsha1("Rosetta Code") END DEF FNsha1(message$) LOCAL buflen%, buffer%, hprov%, hhash%, hash$, i% CALG_SHA1 = &8004 CRYPT_VERIFYCONTEXT = &F0000000 HP_HASHVAL = 2 PROV_RSA_FULL = 1 buflen% = 64 DIM buffer% LOCAL buflen%-1 SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT SYS "CryptCreateHash", hprov%, CALG_SHA1, 0, 0, ^hhash% SYS "CryptHashData", hhash%, message$, LEN(message$), 0 SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 SYS "CryptDestroyHash", hhash% SYS "CryptReleaseContext", hprov% FOR i% = 0 TO buflen%-1 hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) NEXT = hash$
#include <string> #include <iostream> #include "Poco/SHA1Engine.h" #include "Poco/DigestStream.h" using Poco::DigestEngine ; using Poco::SHA1Engine ; using Poco::DigestOutputStream ; int main( ) { std::string myphrase ( "Rosetta Code" ) ; SHA1Engine sha1 ; DigestOutputStream outstr( sha1 ) ; outstr << myphrase ; outstr.flush( ) ; const DigestEngine::Digest& digest = sha1.digest( ) ; std::cout << myphrase << " as a sha1 digest :" << DigestEngine::digestToHex( digest ) << " !" << std::endl ; return 0 ; }