Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from Julia to C with equivalent syntax and logic.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
#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; }
Produce a language-to-language conversion: from Julia to C#, same semantics.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
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; } }
Change the programming language of this snippet from Julia to C# without modifying what it does.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
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 Julia snippet to C++ and keep its semantics consistent.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
#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 Julia code into C++ while preserving the original functionality.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
#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; }
Write a version of this Julia function in Java with identical behavior.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
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 Java while keeping its functionality equivalent to the Julia version.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
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 Julia block to Python, preserving its control flow and logic.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
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()
Ensure the translated Python code behaves exactly like the original Julia snippet.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
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 this program in VB while keeping its functionality equivalent to the Julia version.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
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 algorithm in VB as shown in this Julia implementation.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
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
Port the provided Julia code into Go while preserving the original functionality.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
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 language-to-language conversion: from Julia to Go, same semantics.
struct BalancedTernary <: Signed digits::Vector{Int8} end BalancedTernary() = zero(BalancedTernary) BalancedTernary(n) = convert(BalancedTernary, n) const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) function Base.convert(::Type{BalancedTernary}, n::Signed) r = BalancedTernary(Int8[]) if iszero(n) push!(r.digits, 0) end while n != 0 if mod(n, 3) == 0 push!(r.digits, 0) n = fld(n, 3) elseif mod(n, 3) == 1 push!(r.digits, 1) n = fld(n, 3) else push!(r.digits, -1) n = fld(n + 1, 3) end end return r end const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) function Base.convert(::Type{BalancedTernary}, s::AbstractString) return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) end macro bt_str(s) convert(BalancedTernary, s) end const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) if isempty(a) || isempty(b) if c == 0 return isempty(a) ? b : a end return _add([c], isempty(a) ? b : a) else d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] r = _add(a[2:end], b[2:end], c) if !isempty(r) || d != 0 return unshift!(r, d) else return r end end end function Base.:+(a::BalancedTernary, b::BalancedTernary) v = _add(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) function _mul(a::Vector{Int8}, b::Vector{Int8}) if isempty(a) || isempty(b) return Int8[] else if a[1] == -1 x = (-BalancedTernary(b)).digits elseif a[1] == 0 x = Int8[] elseif a[1] == 1 x = b end y = append!(Int8[0], _mul(a[2:end], b)) return _add(x, y) end end function Base.:*(a::BalancedTernary, b::BalancedTernary) v = _mul(a.digits, b.digits) return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) end a = bt"+-0++0+" println("a: $(Int(a)), $a") b = BalancedTernary(-436) println("b: $(Int(b)), $b") c = BalancedTernary("+-++-") println("c: $(Int(c)), $c") r = a * (b - c) println("a * (b - c): $(Int(r)), $r") @assert Int(r) == Int(a) * (Int(b) - Int(c))
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") } }
Change the programming language of this snippet from Lua to C without modifying what it does.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
#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; }
Rewrite this program in C while keeping its functionality equivalent to the Lua version.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
#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 the following code from Lua to C#, ensuring the logic remains intact.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
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; } }
Transform the following Lua implementation into C#, maintaining the same output and logic.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
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; } }
Keep all operations the same but rewrite the snippet in C++.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
#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 this Lua snippet to C++ and keep its semantics consistent.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
#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; }
Rewrite the snippet below in Java so it works the same as the original Lua code.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
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 Lua block to Java, preserving its control flow and logic.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
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 the following code from Lua to Python, ensuring the logic remains intact.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
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 Lua implementation into Python, maintaining the same output and logic.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
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 VB so it works the same as the original Lua code.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
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
Translate this program into VB but keep the logic exactly as in Lua.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
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 Lua snippet to Go and keep its semantics consistent.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
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") } }
Change the programming language of this snippet from Lua to Go without modifying what it does.
function to_bt(n) local d = { '0', '+', '-' } local v = { 0, 1, -1 } local b = "" while n ~= 0 do local r = n % 3 if r < 0 then r = r + 3 end b = b .. d[r + 1] n = n - v[r + 1] n = math.floor(n / 3) end return b:reverse() end function from_bt(s) local n = 0 for i=1,s:len() do local c = s:sub(i,i) n = n * 3 if c == '+' then n = n + 1 elseif c == '-' then n = n - 1 end end return n end function last_char(s) return s:sub(-1,-1) end function add(b1,b2) local out = "oops" if b1 ~= "" and b2 ~= "" then local d = "" local L1 = last_char(b1) local c1 = b1:sub(1,-2) local L2 = last_char(b2) local c2 = b2:sub(1,-2) if L2 < L1 then L2, L1 = L1, L2 end if L1 == '-' then if L2 == '0' then d = "-" end if L2 == '-' then d = "+-" end elseif L1 == '+' then if L2 == '0' then d = "+" elseif L2 == '-' then d = "0" elseif L2 == '+' then d = "-+" end elseif L1 == '0' then if L2 == '0' then d = "0" end end local ob1 = add(c1,d:sub(2,2)) local ob2 = add(ob1,c2) out = ob2 .. d:sub(1,1) elseif b1 ~= "" then out = b1 elseif b2 ~= "" then out = b2 else out = "" end return out end function unary_minus(b) local out = "" for i=1, b:len() do local c = b:sub(i,i) if c == '-' then out = out .. '+' elseif c == '+' then out = out .. '-' else out = out .. c end end return out end function subtract(b1,b2) return add(b1, unary_minus(b2)) end function mult(b1,b2) local r = "0" local c1 = b1 local c2 = b2:reverse() for i=1,c2:len() do local c = c2:sub(i,i) if c == '+' then r = add(r, c1) elseif c == '-' then r = subtract(r, c1) end c1 = c1 .. '0' end while r:sub(1,1) == '0' do r = r:sub(2) end return r end function main() local a = "+-0++0+" local b = to_bt(-436) local c = "+-++-" local d = mult(a, subtract(b, c)) print(string.format(" a: %14s %10d", a, from_bt(a))) print(string.format(" b: %14s %10d", b, from_bt(b))) print(string.format(" c: %14s %10d", c, from_bt(c))) print(string.format("a*(b-c): %14s %10d", d, from_bt(d))) end main()
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 Mathematica implementation into C, maintaining the same output and logic.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
#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; }
Generate an equivalent C version of this Mathematica code.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
#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; }
Can you help me rewrite this code in C# instead of Mathematica, keeping it the same logically?
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
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; } }
Transform the following Mathematica implementation into C#, maintaining the same output and logic.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
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 Mathematica to C++.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
#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; }
Translate this program into C++ but keep the logic exactly as in Mathematica.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
#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 Mathematica to Java, ensuring the logic remains intact.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
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; } } }
Produce a language-to-language conversion: from Mathematica to Java, same semantics.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
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; } } }
Can you help me rewrite this code in Python instead of Mathematica, keeping it the same logically?
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
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 Mathematica implementation into Python, maintaining the same output and logic.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
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 following Mathematica code into VB without altering its purpose.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
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
Port the following code from Mathematica to VB with equivalent syntax and logic.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
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 Mathematica.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
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 Mathematica to Go with equivalent syntax and logic.
frombt = FromDigits[StringCases[#, {"+" -> 1, "-" -> -1, "0" -> 0}], 3] &; tobt = If[Quotient[#, 3, -1] == 0, "", #0@Quotient[#, 3, -1]] <> (Mod[#, 3, -1] /. {1 -> "+", -1 -> "-", 0 -> "0"}) &; btnegate = StringReplace[#, {"+" -> "-", "-" -> "+"}] &; btadd = StringReplace[ StringJoin[ Fold[Sort@{#1[[1]], Sequence @@ #2} /. {{x_, x_, x_} :> {x, "0" <> #1[[2]]}, {"-", "+", x_} | {x_, "-", "+"} | {x_, "0", "0"} :> {"0", x <> #1[[2]]}, {"+", "+", "0"} -> {"+", "-" <> #1[[2]]}, {"-", "-", "0"} -> {"-", "+" <> #1[[2]]}} &, {"0", ""}, Reverse@Transpose@PadLeft[Characters /@ {#1, #2}] /. {0 -> "0"}]], StartOfString ~~ "0" .. ~~ x__ :> x] &; btsubtract = btadd[#1, btnegate@#2] &; btmultiply = btadd[Switch[StringTake[#2, -1], "0", "0", "+", #1, "-", btnegate@#1], If[StringLength@#2 == 1, "0", #0[#1, StringDrop[#2, -1]] <> "0"]] &;
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") } }
Maintain the same structure and functionality when rewriting this code in C.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
#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 Nim.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
#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 Nim code snippet into C# without altering its behavior.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
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#.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
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; } }
Please provide an equivalent version of this Nim code in C++.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
#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; }
Translate this program into C++ but keep the logic exactly as in Nim.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
#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; }
Translate the given Nim code snippet into Java without altering its behavior.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
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; } } }
Change the programming language of this snippet from Nim to Java without modifying what it does.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
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; } } }
Translate this program into Python but keep the logic exactly as in Nim.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
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 algorithm in Python as shown in this Nim implementation.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
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 VB.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
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
Translate the given Nim code snippet into VB without altering its behavior.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
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.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
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") } }
Change the following Nim code into Go without altering its purpose.
import strformat import tables type Trit = range[-1'i8..1'i8] BTernary = seq[Trit] const Trits: array[Trit, char] = ['-', '0', '+'] TN = Trit(-1) TZ = Trit(0) TP = Trit(1) AddTable = {-2: @[TP, TN], -1: @[TN], 0: @[TZ], 1: @[TP], 2: @[TN, TP]}.toTable() ModTrits: array[-2..2, Trit] = [TP, TN, TZ, TP, TN] func normalize(bt: var BTernary) = var i = bt.high while i >= 0 and bt[i] == 0: dec i bt.setlen(if i < 0: 1 else: i + 1) func `+`*(a, b: BTernary): BTernary = var (a, b) = (a, b) if a.len < b.len: a.setLen(b.len) else: b.setLen(a.len) var carry = TZ for i in 0..<a.len: var s = AddTable[a[i] + b[i]] if carry != TZ: s = s + @[carry] carry = if s.len > 1: s[1] else: TZ result.add(s[0]) if carry != TZ: result.add(carry) func `+=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + b func `-`(a: BTernary): BTernary = result.setLen(a.len) for i, t in a: result[i] = -t func `-`*(a, b: BTernary): BTernary {.inline.} = a + -b func `-=`*(a: var BTernary; b: BTernary) {.inline.} = a = a + -b func `*`*(a, b: BTernary): BTernary = var start: BTernary let na = -a for t in b: case t of TP: result += start & a of TZ: discard of TN: result += start & na start.add(TZ) result.normalize() func toTrit*(c: char): Trit = case c of '-': -1 of '0': 0 of '+': 1 else: raise newException(ValueError, fmt"Invalid trit: '{c}'") func `$`*(bt: BTernary): string = result.setLen(bt.len) for i, t in bt: result[^(i + 1)] = Trits[t] func toBTernary*(s: string): BTernary = result.setLen(s.len) for i, c in s: result[^(i + 1)] = c.toTrit() func toInt*(bt: BTernary): int = var m = 1 for t in bt: result += m * t m *= 3 func toBTernary(val: int): BTernary = var val = val while true: let trit = ModTrits[val mod 3] result.add(trit) val = (val - trit) div 3 if val == 0: break when isMainModule: let a = "+-0++0+".toBTernary let b = -436.toBTernary let c = "+-++-".toBTernary echo "Balanced ternary numbers:" echo fmt"a = {a}" echo fmt"b = {b}" echo fmt"c = {c}" echo "" echo "Their decimal representation:" echo fmt"a = {a.toInt: 4d}" echo fmt"b = {b.toInt: 4d}" echo fmt"c = {c.toInt: 4d}" echo "" let x = a * (b - c) echo "a × (b - c):" echo fmt"– in ternary: {x}" echo fmt"– in decimal: {x.toInt}"
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 language-to-language conversion: from OCaml to C, same semantics.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
#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; }
Keep all operations the same but rewrite the snippet in C.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
#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; }
Change the programming language of this snippet from OCaml to C# without modifying what it does.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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 OCaml to C#.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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; } }
Port the following code from OCaml to C++ with equivalent syntax and logic.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
#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 this OCaml snippet to C++ and keep its semantics consistent.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
#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; }
Change the following OCaml code into Java without altering its purpose.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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; } } }
Can you help me rewrite this code in Java instead of OCaml, keeping it the same logically?
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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 the snippet below in Python so it works the same as the original OCaml code.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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 algorithm in Python as shown in this OCaml implementation.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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 OCaml snippet without changing its computational steps.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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 OCaml code.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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
Please provide an equivalent version of this OCaml code in Go.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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 Go code for the snippet given in OCaml.
type btdigit = Pos | Zero | Neg type btern = btdigit list let to_string n = String.concat "" (List.rev_map (function Pos -> "+" | Zero -> "0" | Neg -> "-") n) let from_string s = let sl = ref [] in let digit = function '+' -> Pos | '-' -> Neg | '0' -> Zero | _ -> failwith "invalid digit" in String.iter (fun c -> sl := (digit c) :: !sl) s; !sl let rec to_int = function | [Zero] | [] -> 0 | Pos :: t -> 1 + 3 * to_int t | Neg :: t -> -1 + 3 * to_int t | Zero :: t -> 3 * to_int t let rec from_int n = if n = 0 then [] else match n mod 3 with | 0 -> Zero :: from_int (n/3) | 1 | -2 -> Pos :: from_int ((n-1)/3) | 2 | -1 -> Neg :: from_int ((n+1)/3) let rec (+~) n1 n2 = match (n1,n2) with | ([], a) | (a,[]) -> a | (Pos::t1, Neg::t2) | (Neg::t1, Pos::t2) | (Zero::t1, Zero::t2) -> let sum = t1 +~ t2 in if sum = [] then [] else Zero :: sum | (Pos::t1, Pos::t2) -> Neg :: t1 +~ t2 +~ [Pos] | (Neg::t1, Neg::t2) -> Pos :: t1 +~ t2 +~ [Neg] | (Zero::t1, h::t2) | (h::t1, Zero::t2) -> h :: t1 +~ t2 let neg = List.map (function Pos -> Neg | Neg -> Pos | Zero -> Zero) let (-~) a b = a +~ (neg b) let rec ( *~) n1 = function | [] -> [] | [Pos] -> n1 | [Neg] -> neg n1 | Pos::t -> (Zero :: t *~ n1) +~ n1 | Neg::t -> (Zero :: t *~ n1) -~ n1 | Zero::t -> Zero :: t *~ n1 let a = from_string "+-0++0+" let b = from_int (-436) let c = from_string "+-++-" let d = a *~ (b -~ c) let _ = Printf.printf "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" (to_int a) (to_int b) (to_int c) (to_string d) (to_int d);
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 C while keeping its functionality equivalent to the Perl version.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
#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 Perl.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
#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 provided Perl code into C# while preserving the original functionality.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
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; } }
Produce a functionally identical C# code for the snippet given in Perl.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
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; } }
Port the provided Perl code into C++ while preserving the original functionality.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
#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; }
Translate this program into C++ but keep the logic exactly as in Perl.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
#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 this Perl block to Java, preserving its control flow and logic.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
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; } } }
Please provide an equivalent version of this Perl code in Java.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
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 Perl code.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
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()
Port the following code from Perl to Python with equivalent syntax and logic.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
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 Perl snippet to VB and keep its semantics consistent.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
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
Change the programming language of this snippet from Perl to VB without modifying what it does.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
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 Go code behaves exactly like the original Perl snippet.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
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 Perl version.
use strict; use warnings; my @d = qw( 0 + - ); my @v = qw( 0 1 -1 ); sub to_bt { my $n = shift; my $b = ''; while( $n ) { my $r = $n%3; $b .= $d[$r]; $n -= $v[$r]; $n /= 3; } return scalar reverse $b; } sub from_bt { my $n = 0; for( split //, shift ) { $n *= 3; $n += "${_}1" if $_; } return $n; } my %addtable = ( '-0' => [ '-', '' ], '+0' => [ '+', '' ], '+-' => [ '0', '' ], '00' => [ '0', '' ], '--' => [ '+', '-' ], '++' => [ '-', '+' ], ); sub add { my ($b1, $b2) = @_; return ($b1 or $b2 ) unless ($b1 and $b2); my $d = $addtable{ join '', sort substr( $b1, -1, 1, '' ), substr( $b2, -1, 1, '' ) }; return add( add($b1, $d->[1]), $b2 ).$d->[0]; } sub unary_minus { my $b = shift; $b =~ tr/-+/+-/; return $b; } sub subtract { my ($b1, $b2) = @_; return add( $b1, unary_minus $b2 ); } sub mult { my ($b1, $b2) = @_; my $r = '0'; for( reverse split //, $b2 ){ $r = add $r, $b1 if $_ eq '+'; $r = subtract $r, $b1 if $_ eq '-'; $b1 .= '0'; } $r =~ s/^0+//; return $r; } my $a = "+-0++0+"; my $b = to_bt( -436 ); my $c = "+-++-"; my $d = mult( $a, subtract( $b, $c ) ); 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 );
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 C translation of this Racket snippet without changing its computational steps.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
#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; }
Rewrite the snippet below in C so it works the same as the original Racket code.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
#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; }
Change the following Racket code into C# without altering its purpose.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
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; } }
Produce a functionally identical C# code for the snippet given in Racket.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
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; } }
Produce a functionally identical C++ code for the snippet given in Racket.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
#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 Racket to C++ with equivalent syntax and logic.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
#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 Racket to Java, same semantics.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
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; } } }
Produce a language-to-language conversion: from Racket to Java, same semantics.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
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; } } }
Preserve the algorithm and functionality while converting the code from Racket to Python.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
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()
Produce a language-to-language conversion: from Racket to Python, same semantics.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
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()
Port the provided Racket code into VB while preserving the original functionality.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
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
Can you help me rewrite this code in VB instead of Racket, keeping it the same logically?
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
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
Change the programming language of this snippet from Racket to Go without modifying what it does.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
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 Racket implementation.
#lang racket (define (bt->integer t) (if (null? t) 0 (+ (first t) (* 3 (bt->integer (rest t)))))) (define (integer->bt n) (letrec ([recur (λ (b r) (cons b (convert (floor (/ r 3)))))] [convert (λ (n) (if (zero? n) null (case (modulo n 3) [(0) (recur 0 n)] [(1) (recur 1 n)] [(2) (recur -1 (add1 n))])))]) (convert n))) (define (bt->string t) (define (strip-leading-zeroes a) (if (or (null? a) (not (= (first a) 0))) a (strip-leading-zeroes (rest a)))) (string-join (map (λ (u) (case u [(1) "+"] [(-1) "-"] [(0) "0"])) (strip-leading-zeroes (reverse t))) "")) (define (string->bt s) (reverse (map (λ (c) (case c [(#\+) 1] [(#\-) -1] [(#\0) 0])) (string->list s)))) (define (bt-negate t) (map (λ (u) (- u)) t)) (define (bt-add a b [c 0]) (cond [(and (null? a) (null? b)) (if (zero? c) null (list c))] [(null? b) (if (zero? c) a (bt-add a (list c)))] [(null? a) (bt-add b a c)] [else (let* ([t (+ (first a) (first b) c)] [carry (if (> (abs t) 1) (sgn t) 0)] [v (case (abs t) [(3) 0] [(2) (- (sgn t))] [else t])]) (cons v (bt-add (rest a) (rest b) carry)))])) (define (bt-multiply a b) (cond [(null? a) null] [(null? b) null] [else (bt-add (case (first a) [(-1) (bt-negate b)] [(0) null] [(1) b]) (cons 0 (bt-multiply (rest a) b)))])) (let* ([a (string->bt "+-0++0+")] [b (integer->bt -436)] [c (string->bt "+-++-")] [d (bt-multiply a (bt-add b (bt-negate c)))]) (for ([bt (list a b c d)] [description (list 'a 'b 'c "a×(b−c)")]) (printf "~a = ~a or ~a\n" description (bt->integer bt) (bt->string bt))))
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 C 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
#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; }
Produce a language-to-language conversion: from REXX to C, same semantics.
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 <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#.
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; } }