Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a language-to-language conversion: from Common_Lisp to VB, same semantics.
(defun bt-integer (b) (reduce (lambda (x y) (+ x (* 3 y))) b :from-end t :initial-value 0)) (defun integer-bt (n) (if (zerop n) nil (case (mod n 3) (0 (cons 0 (integer-bt (/ n 3)))) (1 (cons 1 (integer-bt (floor n 3)))) (2 (cons -1 (integer-bt (floor (1+ n) 3))))))) (defun string-bt (s) (loop with o = nil for c across s do (setf o (cons (case c (#\+ 1) (#\- -1) (#\0 0)) o)) finally (return o))) (defun bt-string (bt) (if (not bt) "0" (let* ((l (length bt)) (s (make-array l :element-type 'character))) (mapc (lambda (b) (setf (aref s (decf l)) (case b (-1 #\-) (0 #\0) (1 #\+)))) bt) s))) (defun bt-neg (a) (map 'list #'- a)) (defun bt-sub (a b) (bt-add a (bt-neg b))) (let ((tbl #((0 -1) (1 -1) (-1 0) (0 0) (1 0) (-1 1) (0 1)))) (defun bt-add-digits (a b c) (values-list (aref tbl (+ 3 a b c))))) (defun bt-add (a b &optional (c 0)) (if (not (and a b)) (if (zerop c) (or a b) (bt-add (list c) (or a b))) (multiple-value-bind (d c) (bt-add-digits (if a (car a) 0) (if b (car b) 0) c) (let ((res (bt-add (cdr a) (cdr b) c))) (if (or res (not (zerop d))) (cons d res)))))) (defun bt-mul (a b) (if (not (and a b)) nil (bt-add (case (car a) (-1 (bt-neg b)) ( 0 nil) ( 1 b)) (cons 0 (bt-mul (cdr a) b))))) (defun bt-truncate (a b) (let ((n (- (length a) (length b))) (d (car (last b)))) (if (minusp n) (values nil a) (labels ((recur (a b x) (multiple-value-bind (quo rem) (if (plusp x) (recur a (cons 0 b) (1- x)) (values nil a)) (loop with g = (car (last rem)) with quo = (cons 0 quo) while (= (length rem) (length b)) do (cond ((= g d) (setf rem (bt-sub rem b) quo (bt-add '(1) quo))) ((= g (- d)) (setf rem (bt-add rem b) quo (bt-add '(-1) quo)))) (setf x (car (last rem))) finally (return (values quo rem)))))) (recur a b n))))) (let* ((a (string-bt "+-0++0+")) (b (integer-bt -436)) (c (string-bt "+-++-")) (d (bt-mul a (bt-sub b c)))) (format t "a~5d~8t~a~%b~5d~8t~a~%c~5d~8t~a~%a × (b − c) = ~d ~a~%" (bt-integer a) (bt-string a) (bt-integer b) (bt-string b) (bt-integer c) (bt-string c) (bt-integer d) (bt-string 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
Can you help me rewrite this code in VB instead of Common_Lisp, keeping it the same logically?
(defun bt-integer (b) (reduce (lambda (x y) (+ x (* 3 y))) b :from-end t :initial-value 0)) (defun integer-bt (n) (if (zerop n) nil (case (mod n 3) (0 (cons 0 (integer-bt (/ n 3)))) (1 (cons 1 (integer-bt (floor n 3)))) (2 (cons -1 (integer-bt (floor (1+ n) 3))))))) (defun string-bt (s) (loop with o = nil for c across s do (setf o (cons (case c (#\+ 1) (#\- -1) (#\0 0)) o)) finally (return o))) (defun bt-string (bt) (if (not bt) "0" (let* ((l (length bt)) (s (make-array l :element-type 'character))) (mapc (lambda (b) (setf (aref s (decf l)) (case b (-1 #\-) (0 #\0) (1 #\+)))) bt) s))) (defun bt-neg (a) (map 'list #'- a)) (defun bt-sub (a b) (bt-add a (bt-neg b))) (let ((tbl #((0 -1) (1 -1) (-1 0) (0 0) (1 0) (-1 1) (0 1)))) (defun bt-add-digits (a b c) (values-list (aref tbl (+ 3 a b c))))) (defun bt-add (a b &optional (c 0)) (if (not (and a b)) (if (zerop c) (or a b) (bt-add (list c) (or a b))) (multiple-value-bind (d c) (bt-add-digits (if a (car a) 0) (if b (car b) 0) c) (let ((res (bt-add (cdr a) (cdr b) c))) (if (or res (not (zerop d))) (cons d res)))))) (defun bt-mul (a b) (if (not (and a b)) nil (bt-add (case (car a) (-1 (bt-neg b)) ( 0 nil) ( 1 b)) (cons 0 (bt-mul (cdr a) b))))) (defun bt-truncate (a b) (let ((n (- (length a) (length b))) (d (car (last b)))) (if (minusp n) (values nil a) (labels ((recur (a b x) (multiple-value-bind (quo rem) (if (plusp x) (recur a (cons 0 b) (1- x)) (values nil a)) (loop with g = (car (last rem)) with quo = (cons 0 quo) while (= (length rem) (length b)) do (cond ((= g d) (setf rem (bt-sub rem b) quo (bt-add '(1) quo))) ((= g (- d)) (setf rem (bt-add rem b) quo (bt-add '(-1) quo)))) (setf x (car (last rem))) finally (return (values quo rem)))))) (recur a b n))))) (let* ((a (string-bt "+-0++0+")) (b (integer-bt -436)) (c (string-bt "+-++-")) (d (bt-mul a (bt-sub b c)))) (format t "a~5d~8t~a~%b~5d~8t~a~%c~5d~8t~a~%a × (b − c) = ~d ~a~%" (bt-integer a) (bt-string a) (bt-integer b) (bt-string b) (bt-integer c) (bt-string c) (bt-integer d) (bt-string 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
Write the same algorithm in Go as shown in this Common_Lisp implementation.
(defun bt-integer (b) (reduce (lambda (x y) (+ x (* 3 y))) b :from-end t :initial-value 0)) (defun integer-bt (n) (if (zerop n) nil (case (mod n 3) (0 (cons 0 (integer-bt (/ n 3)))) (1 (cons 1 (integer-bt (floor n 3)))) (2 (cons -1 (integer-bt (floor (1+ n) 3))))))) (defun string-bt (s) (loop with o = nil for c across s do (setf o (cons (case c (#\+ 1) (#\- -1) (#\0 0)) o)) finally (return o))) (defun bt-string (bt) (if (not bt) "0" (let* ((l (length bt)) (s (make-array l :element-type 'character))) (mapc (lambda (b) (setf (aref s (decf l)) (case b (-1 #\-) (0 #\0) (1 #\+)))) bt) s))) (defun bt-neg (a) (map 'list #'- a)) (defun bt-sub (a b) (bt-add a (bt-neg b))) (let ((tbl #((0 -1) (1 -1) (-1 0) (0 0) (1 0) (-1 1) (0 1)))) (defun bt-add-digits (a b c) (values-list (aref tbl (+ 3 a b c))))) (defun bt-add (a b &optional (c 0)) (if (not (and a b)) (if (zerop c) (or a b) (bt-add (list c) (or a b))) (multiple-value-bind (d c) (bt-add-digits (if a (car a) 0) (if b (car b) 0) c) (let ((res (bt-add (cdr a) (cdr b) c))) (if (or res (not (zerop d))) (cons d res)))))) (defun bt-mul (a b) (if (not (and a b)) nil (bt-add (case (car a) (-1 (bt-neg b)) ( 0 nil) ( 1 b)) (cons 0 (bt-mul (cdr a) b))))) (defun bt-truncate (a b) (let ((n (- (length a) (length b))) (d (car (last b)))) (if (minusp n) (values nil a) (labels ((recur (a b x) (multiple-value-bind (quo rem) (if (plusp x) (recur a (cons 0 b) (1- x)) (values nil a)) (loop with g = (car (last rem)) with quo = (cons 0 quo) while (= (length rem) (length b)) do (cond ((= g d) (setf rem (bt-sub rem b) quo (bt-add '(1) quo))) ((= g (- d)) (setf rem (bt-add rem b) quo (bt-add '(-1) quo)))) (setf x (car (last rem))) finally (return (values quo rem)))))) (recur a b n))))) (let* ((a (string-bt "+-0++0+")) (b (integer-bt -436)) (c (string-bt "+-++-")) (d (bt-mul a (bt-sub b c)))) (format t "a~5d~8t~a~%b~5d~8t~a~%c~5d~8t~a~%a × (b − c) = ~d ~a~%" (bt-integer a) (bt-string a) (bt-integer b) (bt-string b) (bt-integer c) (bt-string c) (bt-integer d) (bt-string 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") } }
Convert this Common_Lisp block to Go, preserving its control flow and logic.
(defun bt-integer (b) (reduce (lambda (x y) (+ x (* 3 y))) b :from-end t :initial-value 0)) (defun integer-bt (n) (if (zerop n) nil (case (mod n 3) (0 (cons 0 (integer-bt (/ n 3)))) (1 (cons 1 (integer-bt (floor n 3)))) (2 (cons -1 (integer-bt (floor (1+ n) 3))))))) (defun string-bt (s) (loop with o = nil for c across s do (setf o (cons (case c (#\+ 1) (#\- -1) (#\0 0)) o)) finally (return o))) (defun bt-string (bt) (if (not bt) "0" (let* ((l (length bt)) (s (make-array l :element-type 'character))) (mapc (lambda (b) (setf (aref s (decf l)) (case b (-1 #\-) (0 #\0) (1 #\+)))) bt) s))) (defun bt-neg (a) (map 'list #'- a)) (defun bt-sub (a b) (bt-add a (bt-neg b))) (let ((tbl #((0 -1) (1 -1) (-1 0) (0 0) (1 0) (-1 1) (0 1)))) (defun bt-add-digits (a b c) (values-list (aref tbl (+ 3 a b c))))) (defun bt-add (a b &optional (c 0)) (if (not (and a b)) (if (zerop c) (or a b) (bt-add (list c) (or a b))) (multiple-value-bind (d c) (bt-add-digits (if a (car a) 0) (if b (car b) 0) c) (let ((res (bt-add (cdr a) (cdr b) c))) (if (or res (not (zerop d))) (cons d res)))))) (defun bt-mul (a b) (if (not (and a b)) nil (bt-add (case (car a) (-1 (bt-neg b)) ( 0 nil) ( 1 b)) (cons 0 (bt-mul (cdr a) b))))) (defun bt-truncate (a b) (let ((n (- (length a) (length b))) (d (car (last b)))) (if (minusp n) (values nil a) (labels ((recur (a b x) (multiple-value-bind (quo rem) (if (plusp x) (recur a (cons 0 b) (1- x)) (values nil a)) (loop with g = (car (last rem)) with quo = (cons 0 quo) while (= (length rem) (length b)) do (cond ((= g d) (setf rem (bt-sub rem b) quo (bt-add '(1) quo))) ((= g (- d)) (setf rem (bt-add rem b) quo (bt-add '(-1) quo)))) (setf x (car (last rem))) finally (return (values quo rem)))))) (recur a b n))))) (let* ((a (string-bt "+-0++0+")) (b (integer-bt -436)) (c (string-bt "+-++-")) (d (bt-mul a (bt-sub b c)))) (format t "a~5d~8t~a~%b~5d~8t~a~%c~5d~8t~a~%a × (b − c) = ~d ~a~%" (bt-integer a) (bt-string a) (bt-integer b) (bt-string b) (bt-integer c) (bt-string c) (bt-integer d) (bt-string 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") } }
Convert this D block to C, preserving its control flow and logic.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
#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; }
Transform the following D implementation into C, maintaining the same output and logic.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
#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 a C# translation of this D snippet without changing its computational steps.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
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; } }
Rewrite the snippet below in C# so it works the same as the original D code.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
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 D to C++ without modifying what it does.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
#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 D function in C++ with identical behavior.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Generate a Java translation of this D snippet without changing its computational steps.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
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 Java version of this D code.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
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 D to Python.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Can you help me rewrite this code in Python instead of D, keeping it the same logically?
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
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 D snippet without changing its computational steps.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
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
Transform the following D implementation into VB, maintaining the same output and logic.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
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 Go instead of D, keeping it the same logically?
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
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") } }
Please provide an equivalent version of this D code in Go.
import std.stdio, std.bigint, std.range, std.algorithm; struct BalancedTernary { enum Dig : byte { N=-1, Z=0, P=+1 } const Dig[] digits; static immutable string dig2str = "-0+"; immutable static Dig[dchar] str2dig; nothrow static this() { str2dig = ['+': Dig.P, '-': Dig.N, '0': Dig.Z]; } immutable pure nothrow static Dig[2][] table = [[Dig.Z, Dig.N], [Dig.P, Dig.N], [Dig.N, Dig.Z], [Dig.Z, Dig.Z], [Dig.P, Dig.Z], [Dig.N, Dig.P], [Dig.Z, Dig.P]]; this(in string inp) const pure { this.digits = inp.retro.map!(c => str2dig[c]).array; } this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } this(in BalancedTernary inp) const pure nothrow { this.digits = inp.digits; } private this(in Dig[] inp) pure nothrow { this.digits = inp; } static Dig[] _bint2ternary(in BigInt n) pure nothrow { static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : -(-a / b) - (-a % b != 0 ? 1 : 0); } else { return (b < 0) ? -(a / -b) - (a % -b != 0 ? 1 : 0) : a / b; } } if (n == 0) return []; final switch (((n % 3) + 3) % 3) { case 0: return Dig.Z ~ _bint2ternary(py_div(n, 3)); case 1: return Dig.P ~ _bint2ternary(py_div(n, 3)); case 2: return Dig.N ~ _bint2ternary(py_div(n + 1, 3)); } } @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } string toString() const pure nothrow { if (digits.empty) return "0"; return digits.retro.map!(d => dig2str[d + 1]).array; } static const(Dig)[] neg_(in Dig[] digs) pure nothrow { return digs.map!(a => -a).array; } BalancedTernary opUnary(string op:"-")() const pure nothrow { return BalancedTernary(neg_(this.digits)); } static const(Dig)[] add_(in Dig[] a, in Dig[] b, in Dig c=Dig.Z) pure nothrow { const a_or_b = a.length ? a : b; if (a.empty || b.empty) { if (c == Dig.Z) return a_or_b; else return BalancedTernary.add_([c], a_or_b); } else { const dc = table[3 + (a.length ? a[0] : 0) + (b.length ? b[0] : 0) + c]; const res = add_(a[1 .. $], b[1 .. $], dc[1]); if (res.length || dc[0] != Dig.Z) return [dc[0]] ~ res; else return res; } } BalancedTernary opBinary(string op:"+")(in BalancedTernary b) const pure nothrow { return BalancedTernary(add_(this.digits, b.digits)); } BalancedTernary opBinary(string op:"-")(in BalancedTernary b) const pure nothrow { return this + (-b); } static const(Dig)[] mul_(in Dig[] a, in Dig[] b) pure nothrow { if (a.empty || b.empty) { return []; } else { const y = Dig.Z ~ mul_(a[1 .. $], b); final switch (a[0]) { case Dig.N: return add_(neg_(b), y); case Dig.Z: return add_([], y); case Dig.P: return add_(b, y); } } } BalancedTernary opBinary(string op:"*")(in BalancedTernary b) const pure nothrow { return BalancedTernary(mul_(this.digits, b.digits)); } } void main() { immutable a = BalancedTernary("+-0++0+"); writeln("a: ", a.toBint, ' ', a); immutable b = BalancedTernary(-436); writeln("b: ", b.toBint, ' ', b); immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); const r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); }
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 Elixir code into C without altering its purpose.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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; }
Translate this program into C but keep the logic exactly as in Elixir.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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; }
Convert this Elixir snippet to C# and keep its semantics consistent.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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; } }
Generate a C++ translation of this Elixir snippet without changing its computational steps.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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; }
Generate an equivalent C++ version of this Elixir code.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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; }
Convert this Elixir snippet to Java and keep its semantics consistent.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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; } } }
Please provide an equivalent version of this Elixir code in Java.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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 Elixir block to Python, preserving its control flow and logic.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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()
Produce a functionally identical Python code for the snippet given in Elixir.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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()
Generate a VB translation of this Elixir snippet without changing its computational steps.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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
Preserve the algorithm and functionality while converting the code from Elixir to VB.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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
Produce a language-to-language conversion: from Elixir to Go, same semantics.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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") } }
Translate the given Elixir code snippet into Go without altering its behavior.
defmodule Ternary do def to_string(t), do: ( for x <- t, do: to_char(x) ) |> List.to_string def from_string(s), do: ( for x <- to_char_list(s), do: from_char(x) ) defp to_char(-1), do: ?- defp to_char(0), do: ?0 defp to_char(1), do: ?+ defp from_char(?-), do: -1 defp from_char(?0), do: 0 defp from_char(?+), do: 1 def to_ternary(n) when n > 0, do: to_ternary(n,[]) def to_ternary(n), do: neg(to_ternary(-n)) defp to_ternary(0,acc), do: acc defp to_ternary(n,acc) when rem(n, 3) == 0, do: to_ternary(div(n, 3), [0|acc]) defp to_ternary(n,acc) when rem(n, 3) == 1, do: to_ternary(div(n, 3), [1|acc]) defp to_ternary(n,acc), do: to_ternary(div((n+1), 3), [-1|acc]) def from_ternary(t), do: from_ternary(t,0) defp from_ternary([],acc), do: acc defp from_ternary([h|t],acc), do: from_ternary(t, acc*3 + h) def mul(a,b), do: mul(b,a,[]) defp mul(_,[],acc), do: acc defp mul(b,[a|as],acc) do bp = case a do -1 -> neg(b) 0 -> [0] 1 -> b end a = add(bp, acc ++ [0]) mul(b,as,a) end defp neg(t), do: ( for h <- t, do: -h ) def sub(a,b), do: add(a,neg(b)) def add(a,b) when length(a) < length(b), do: add(List.duplicate(0, length(b)-length(a)) ++ a, b) def add(a,b) when length(a) > length(b), do: add(b,a) def add(a,b), do: add(Enum.reverse(a), Enum.reverse(b), 0, []) defp add([],[],0,acc), do: acc defp add([],[],c,acc), do: [c|acc] defp add([a|as],[b|bs],c,acc) do [c1,d] = add_util(a+b+c) add(as,bs,c1,[d|acc]) end defp add_util(-3), do: [-1,0] defp add_util(-2), do: [-1,1] defp add_util(-1), do: [0,-1] defp add_util(3), do: [1,0] defp add_util(2), do: [1,-1] defp add_util(1), do: [0,1] defp add_util(0), do: [0,0] end as = "+-0++0+"; at = Ternary.from_string(as); a = Ternary.from_ternary(at) b = -436; bt = Ternary.to_ternary(b); bs = Ternary.to_string(bt) cs = "+-++-"; ct = Ternary.from_string(cs); c = Ternary.from_ternary(ct) rt = Ternary.mul(at,Ternary.sub(bt,ct)) r = Ternary.from_ternary(rt) rs = Ternary.to_string(rt) IO.puts "a = IO.puts "b = IO.puts "c = IO.puts "a x (b - 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 Erlang to C without modifying what it does.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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 Erlang code.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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; }
Please provide an equivalent version of this Erlang code in C#.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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; } }
Can you help me rewrite this code in C# instead of Erlang, keeping it the same logically?
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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; } }
Translate this program into C++ but keep the logic exactly as in Erlang.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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 the given Erlang code snippet into C++ without altering its behavior.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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; }
Ensure the translated Java code behaves exactly like the original Erlang snippet.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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; } } }
Transform the following Erlang implementation into Java, maintaining the same output and logic.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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; } } }
Convert this Erlang block to Python, preserving its control flow and logic.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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()
Translate this program into Python but keep the logic exactly as in Erlang.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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()
Generate an equivalent VB version of this Erlang code.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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
Rewrite this program in VB while keeping its functionality equivalent to the Erlang version.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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
Convert this Erlang block to Go, preserving its control flow and logic.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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") } }
Write the same algorithm in Go as shown in this Erlang implementation.
-module(ternary). -compile(export_all). test() -> AS = "+-0++0+", AT = from_string(AS), A = from_ternary(AT), B = -436, BT = to_ternary(B), BS = to_string(BT), CS = "+-++-", CT = from_string(CS), C = from_ternary(CT), RT = mul(AT,sub(BT,CT)), R = from_ternary(RT), RS = to_string(RT), io:fwrite("A = ~s -> ~b~n",[AS, A]), io:fwrite("B = ~s -> ~b~n",[BS, B]), io:fwrite("C = ~s -> ~b~n",[CS, C]), io:fwrite("A x (B - C) = ~s -> ~b~n", [RS, R]). to_string(T) -> [to_char(X) || X <- T]. from_string(S) -> [from_char(X) || X <- S]. to_char(-1) -> $-; to_char(0) -> $0; to_char(1) -> $+. from_char($-) -> -1; from_char($0) -> 0; from_char($+) -> 1. to_ternary(N) when N > 0 -> to_ternary(N,[]); to_ternary(N) -> neg(to_ternary(-N)). to_ternary(0,Acc) -> Acc; to_ternary(N,Acc) when N rem 3 == 0 -> to_ternary(N div 3, [0|Acc]); to_ternary(N,Acc) when N rem 3 == 1 -> to_ternary(N div 3, [1|Acc]); to_ternary(N,Acc) -> to_ternary((N+1) div 3, [-1|Acc]). from_ternary(T) -> from_ternary(T,0). from_ternary([],Acc) -> Acc; from_ternary([H|T],Acc) -> from_ternary(T,Acc*3 + H). mul(A,B) -> mul(B,A,[]). mul(_,[],Acc) -> Acc; mul(B,[A|As],Acc) -> BP = case A of -1 -> neg(B); 0 -> [0]; 1 -> B end, A1 = Acc++[0], A2=add(BP,A1), mul(B,As,A2). neg(T) -> [ -H || H <- T]. sub(A,B) -> add(A,neg(B)). add(A,B) when length(A) < length(B) -> add(lists:duplicate(length(B)-length(A),0)++A,B); add(A,B) when length(A) > length(B) -> add(B,A); add(A,B) -> add(lists:reverse(A),lists:reverse(B),0,[]). add([],[],0,Acc) -> Acc; add([],[],C,Acc) -> [C|Acc]; add([A|As],[B|Bs],C,Acc) -> [C1,D] = add_util(A+B+C), add(As,Bs,C1,[D|Acc]). add_util(-3) -> [-1,0]; add_util(-2) -> [-1,1]; add_util(-1) -> [0,-1]; add_util(3) -> [1,0]; add_util(2) -> [1,-1]; add_util(1) -> [0,1]; add_util(0) -> [0,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") } }
Generate a C translation of this Factor snippet without changing its computational steps.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
#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 Factor code.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Convert this Factor block to C#, preserving its control flow and logic.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Write the same code in C# as shown below in Factor.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
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 Factor implementation into C++, maintaining the same output and logic.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
#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; }
Maintain the same structure and functionality when rewriting this code in C++.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
#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 Factor block to Java, preserving its control flow and logic.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
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; } } }
Write the same algorithm in Python as shown in this Factor implementation.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
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 Python while keeping its functionality equivalent to the Factor version.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
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 functionally identical VB code for the snippet given in Factor.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
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
Transform the following Factor implementation into VB, maintaining the same output and logic.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Generate an equivalent Go version of this Factor code.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
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 an equivalent Go version of this Factor code.
USING: kernel combinators locals formatting lint literals sequences assocs strings arrays math math.functions math.order ; IN: rosetta-code.bt CONSTANT: addlookup { { 0 CHAR: 0 } { 1 CHAR: + } { -1 CHAR: - } } <PRIVATE : bt-add-digits ( a b c -- d e ) + + 3 + { { 0 -1 } { 1 -1 } { -1 0 } { 0 0 } { 1 0 } { -1 1 } { 0 1 } } nth first2 ; PRIVATE> : bt>integer ( seq -- x ) 0 [ swap 3 * + ] reduce ; : integer>bt ( x -- x ) [ dup zero? not ] [ dup 3 rem { { 0 [ 3 / 0 ] } { 1 [ 3 / round 1 ] } { 2 [ 1 + 3 / round -1 ] } } case ] produce nip reverse ; : bt>string ( seq -- str ) [ addlookup at ] map >string ; : string>bt ( str -- seq ) [ addlookup value-at ] { } map-as ; : bt-neg ( a -- -a ) [ neg ] map ; :: bt-add ( u v -- w ) u v max-length :> maxl u v [ maxl 0 pad-head reverse ] bi@ :> ( u v ) 0 :> carry u v { } [ carry bt-add-digits carry carry prefix [ zero? ] trim-head ; : bt-sub ( u v -- w ) bt-neg bt-add ; :: bt-mul ( u v -- w ) u { } [ { { -1 [ v bt-neg ] } { 0 [ { } ] } { 1 [ v ] } } case bt-add 0 suffix ] reduce 1 head* ; [let "+-0++0+" string>bt :> a -436 integer>bt :> b "+-++-" string>bt :> c b c bt-sub a bt-mul :> d "a" a bt>integer a bt>string "%s: %d, %s\n" printf "b" b bt>integer b bt>string "%s: %d, %s\n" printf "c" c bt>integer c bt>string "%s: %d, %s\n" printf "a*(b-c)" d bt>integer d bt>string "%s: %d, %s\n" printf ]
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 code in C as shown below in Groovy.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
#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; }
Please provide an equivalent version of this Groovy code in C.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
#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; }
Preserve the algorithm and functionality while converting the code from Groovy to C#.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
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; } }
Generate an equivalent C# version of this Groovy code.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
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 language-to-language conversion: from Groovy to C++, same semantics.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
#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 Groovy code snippet into C++ without altering its behavior.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
#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 programming language of this snippet from Groovy to Java without modifying what it does.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Generate a Java translation of this Groovy snippet without changing its computational steps.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
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; } } }
Keep all operations the same but rewrite the snippet in Python.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
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 functionally identical Python code for the snippet given in Groovy.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Change the programming language of this snippet from Groovy to VB without modifying what it does.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
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 Groovy block to VB, preserving its control flow and logic.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
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.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
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 the snippet below in Go so it works the same as the original Groovy code.
enum T { m('-', -1), z('0', 0), p('+', 1) final String symbol final int value private T(String symbol, int value) { this.symbol = symbol this.value = value } static T get(Object key) { switch (key) { case [m.value, m.symbol] : return m case [z.value, z.symbol] : return z case [p.value, p.symbol] : return p default: return null } } T negative() { T.get(-this.value) } String toString() { this.symbol } } class BalancedTernaryInteger { static final MINUS = new BalancedTernaryInteger(T.m) static final ZERO = new BalancedTernaryInteger(T.z) static final PLUS = new BalancedTernaryInteger(T.p) private static final LEADING_ZEROES = /^0+/ final String value BalancedTernaryInteger(String bt) { assert bt && bt.toSet().every { T.get(it) } value = bt ==~ LEADING_ZEROES ? T.z : bt.replaceAll(LEADING_ZEROES, ''); } BalancedTernaryInteger(BigInteger i) { this(i == 0 ? T.z.symbol : valueFromInt(i)); } BalancedTernaryInteger(T...tArray) { this(tArray.sum{ it.symbol }); } BalancedTernaryInteger(List<T> tList) { this(tList.sum{ it.symbol }); } private static String valueFromInt(BigInteger i) { assert i != null if (i < 0) return negate(valueFromInt(-i)) if (i == 0) return '' int bRem = (((i % 3) - 2) ?: -3) + 2 valueFromInt((i - bRem).intdiv(3)) + T.get(bRem) } private static String negate(String bt) { bt.collect{ T.get(it) }.inject('') { str, t -> str + (-t) } } private static final Map INITIAL_SUM_PARTS = [carry:T.z, sum:[]] private static final prepValueLen = { int len, String s -> s.padLeft(len + 1, T.z.symbol).collect{ T.get(it) } } private static final partCarrySum = { partialSum, carry, trit -> [carry: carry, sum: [trit] + partialSum] } private static final partSum = { parts, trits -> def carrySum = partCarrySum.curry(parts.sum) switch ((trits + parts.carry).sort()) { case [[T.m, T.m, T.m]]: return carrySum(T.m, T.z) case [[T.m, T.m, T.z]]: return carrySum(T.m, T.p) case [[T.m, T.z, T.z], [T.m, T.m, T.p]]: return carrySum(T.z, T.m) case [[T.z, T.z, T.z], [T.m, T.z, T.p]]: return carrySum(T.z, T.z) case [[T.z, T.z, T.p], [T.m, T.p, T.p]]: return carrySum(T.z, T.p) case [[T.z, T.p, T.p]]: return carrySum(T.p, T.m) case [[T.p, T.p, T.p]]: default: return carrySum(T.p, T.z) } } BalancedTernaryInteger plus(BalancedTernaryInteger that) { assert that != null if (this == ZERO) return that if (that == ZERO) return this def prep = prepValueLen.curry([value.size(), that.value.size()].max()) List values = [prep(value), prep(that.value)].transpose() new BalancedTernaryInteger(values[-1..(-values.size())].inject(INITIAL_SUM_PARTS, partSum).sum) } BalancedTernaryInteger negative() { !this ? this : new BalancedTernaryInteger(negate(value)) } BalancedTernaryInteger minus(BalancedTernaryInteger that) { assert that != null this + -that } private static final INITIAL_PRODUCT_PARTS = [sum:ZERO, pad:''] private static final sigTritCount = { it.value.replaceAll(T.z.symbol,'').size() } private BalancedTernaryInteger paddedValue(String pad) { new BalancedTernaryInteger(value + pad) } private BalancedTernaryInteger partialProduct(T multiplier, String pad){ switch (multiplier) { case T.z: return ZERO case T.m: return -paddedValue(pad) case T.p: default: return paddedValue(pad) } } BalancedTernaryInteger multiply(BalancedTernaryInteger that) { assert that != null if (that == ZERO) return ZERO if (that == PLUS) return this if (that == MINUS) return -this if (this.value.size() == 1 || sigTritCount(this) < sigTritCount(that)) { return that.multiply(this) } that.value.collect{ T.get(it) }[-1..(-value.size())].inject(INITIAL_PRODUCT_PARTS) { parts, multiplier -> [sum: parts.sum + partialProduct(multiplier, parts.pad), pad: parts.pad + T.z] }.sum } BigInteger asBigInteger() { value.collect{ T.get(it) }.inject(0) { i, trit -> i * 3 + trit.value } } def asType(Class c) { switch (c) { case Integer: return asBigInteger() as Integer case Long: return asBigInteger() as Long case [BigInteger, Number]: return asBigInteger() case Boolean: return this != ZERO case String: return toString() default: return super.asType(c) } } boolean equals(Object that) { switch (that) { case BalancedTernaryInteger: return this.value == that?.value default: return super.equals(that) } } int hashCode() { this.value.hashCode() } String toString() { value } }
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Keep all operations the same but rewrite the snippet in C.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
#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; }
Preserve the algorithm and functionality while converting the code from Haskell to C.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Convert this Haskell snippet to C# and keep its semantics consistent.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
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 Haskell to C++ without modifying what it does.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
#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 Haskell.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
#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; }
Can you help me rewrite this code in Java instead of Haskell, keeping it the same logically?
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
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 the given Haskell code snippet into Java without altering its behavior.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Port the following code from Haskell to Python with equivalent syntax and logic.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
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 Haskell to Python, same semantics.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
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 Haskell code into VB without altering its purpose.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
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 the following code from Haskell to VB, ensuring the logic remains intact.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
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 Go instead of Haskell, keeping it the same logically?
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
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 an equivalent Go version of this Haskell code.
data BalancedTernary = Bt [Int] zeroTrim a = if null s then [0] else s where s = fst $ foldl f ([],[]) a f (x,y) 0 = (x, y++[0]) f (x,y) z = (x++y++[z], []) btList (Bt a) = a instance Eq BalancedTernary where (==) a b = btList a == btList b btNormalize = listBt . _carry 0 where _carry c [] = if c == 0 then [] else [c] _carry c (a:as) = r:_carry cc as where (cc, r) = f $ (a+c) `quotRem` 3 where f (x, 2) = (x + 1, -1) f (x, -2) = (x - 1, 1) f x = x listBt = Bt . zeroTrim instance Show BalancedTernary where show = reverse . map (\d->case d of -1->'-'; 0->'0'; 1->'+') . btList strBt = Bt . zeroTrim.reverse.map (\c -> case c of '-' -> -1; '0' -> 0; '+' -> 1) intBt :: Integral a => a -> BalancedTernary intBt = fromIntegral . toInteger btInt = foldr (\a z -> a + 3 * z) 0 . btList listAdd a b = take (max (length a) (length b)) $ zipWith (+) (a++[0,0..]) (b++[0,0..]) instance Num BalancedTernary where negate = Bt . map negate . btList (+) x y = btNormalize $ listAdd (btList x) (btList y) (*) x y = btNormalize $ mul_ (btList x) (btList y) where mul_ _ [] = [] mul_ as b = foldr (\a z -> listAdd (map (a*) b) (0:z)) [] as signum (Bt a) = if a == [0] then 0 else Bt [last a] abs x = if signum x == Bt [-1] then negate x else x fromInteger = btNormalize . f where f 0 = [] f x = fromInteger (rem x 3) : f (quot x 3) main = let (a,b,c) = (strBt "+-0++0+", intBt (-436), strBt "+-++-") r = a * (b - c) in do print $ map btInt [a,b,c] print $ r print $ btInt r
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 the snippet below in C so it works the same as the original J code.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
#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 J code.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
#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#.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
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 J code in C#.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
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 J to C++ with equivalent syntax and logic.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
#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 J code into C++ while preserving the original functionality.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
#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 the same code in Java as shown below in J.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
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 Java so it works the same as the original J code.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
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; } } }
Write the same algorithm in Python as shown in this J implementation.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Maintain the same structure and functionality when rewriting this code in Python.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
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()
Please provide an equivalent version of this J code in VB.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
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 the following code from J to VB, ensuring the logic remains intact.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
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.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
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 the snippet below in Go so it works the same as the original J code.
trigits=: 1+3 <.@^. 2 * 1&>.@| trinOfN=: |.@((_1 + ] #: #.&1@] + [) #&3@trigits) :. nOfTrin nOfTrin=: p.&3 :. trinOfN trinOfStr=: 0 1 _1 {~ '0+-'&i.@|. :. strOfTrin strOfTrin=: {&'0+-'@|. :. trinOfStr carry=: +//.@:(trinOfN"0)^:_ trimLead0=: (}.~ i.&1@:~:&0)&.|. add=: carry@(+/@,:) neg=: - mul=: trimLead0@carry@(+//.@(*/))
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 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))
#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; }