Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert the following code from R to Python, ensuring the logic remains intact.
exists("x")
try: name except NameError: print "name is undefined at first check" name = "Chocolate" try: name except NameError: print "name is undefined at second check" del name try: name except NameError: print "name is undefined at third check" name = 42 try: name except NameError: print "name is undefined at fourth check" print "Done"
Convert the following code from R to Go, ensuring the logic remains intact.
exists("x")
package main import "fmt" var ( s []int p *int f func() i interface{} m map[int]int c chan int ) func main() { fmt.Println("Exercise nil objects:") status() s = make([]int, 1) p = &s[0] f = func() { fmt.Println("function call") } i = user(0) m = make(map[int]int) c = make(chan int, 1) fmt.Println("\nExercise objects after initialization:") status() } type user int func (user) m() { fmt.Println("method call") } func status() { trySlice() tryPointer() tryFunction() tryInterface() tryMap() tryChannel() } func reportPanic() { if x := recover(); x != nil { fmt.Println("panic:", x) } } func trySlice() { defer reportPanic() fmt.Println("s[0] =", s[0]) } func tryPointer() { defer reportPanic() fmt.Println("*p =", *p) } func tryFunction() { defer reportPanic() f() } func tryInterface() { defer reportPanic() switch i.(type) { case nil: fmt.Println("i is nil interface") case interface { m() }: fmt.Println("i has method m") } i.(interface { m() }).m() } func tryMap() { defer reportPanic() m[0] = 0 fmt.Println("m[0] =", m[0]) } func tryChannel() { defer reportPanic() close(c) fmt.Println("channel closed") }
Change the programming language of this snippet from Racket to C without modifying what it does.
-> (letrec ([x x]) x) #<undefined>
#include <stdio.h> #include <stdlib.h> int main() { int junk, *junkp; printf("junk: %d\n", junk); junkp = malloc(sizeof *junkp); if (junkp) printf("*junkp: %d\n", *junkp); return 0; }
Change the programming language of this snippet from Racket to C++ without modifying what it does.
-> (letrec ([x x]) x) #<undefined>
#include <iostream> int main() { int undefined; if (undefined == 42) { std::cout << "42"; } if (undefined != 42) { std::cout << "not 42"; } }
Write a version of this Racket function in Java with identical behavior.
-> (letrec ([x x]) x) #<undefined>
String string = null; System.out.println(string); System.out.println(string.length());
Change the following Racket code into Python without altering its purpose.
-> (letrec ([x x]) x) #<undefined>
try: name except NameError: print "name is undefined at first check" name = "Chocolate" try: name except NameError: print "name is undefined at second check" del name try: name except NameError: print "name is undefined at third check" name = 42 try: name except NameError: print "name is undefined at fourth check" print "Done"
Please provide an equivalent version of this Racket code in Go.
-> (letrec ([x x]) x) #<undefined>
package main import "fmt" var ( s []int p *int f func() i interface{} m map[int]int c chan int ) func main() { fmt.Println("Exercise nil objects:") status() s = make([]int, 1) p = &s[0] f = func() { fmt.Println("function call") } i = user(0) m = make(map[int]int) c = make(chan int, 1) fmt.Println("\nExercise objects after initialization:") status() } type user int func (user) m() { fmt.Println("method call") } func status() { trySlice() tryPointer() tryFunction() tryInterface() tryMap() tryChannel() } func reportPanic() { if x := recover(); x != nil { fmt.Println("panic:", x) } } func trySlice() { defer reportPanic() fmt.Println("s[0] =", s[0]) } func tryPointer() { defer reportPanic() fmt.Println("*p =", *p) } func tryFunction() { defer reportPanic() f() } func tryInterface() { defer reportPanic() switch i.(type) { case nil: fmt.Println("i is nil interface") case interface { m() }: fmt.Println("i has method m") } i.(interface { m() }).m() } func tryMap() { defer reportPanic() m[0] = 0 fmt.Println("m[0] =", m[0]) } func tryChannel() { defer reportPanic() close(c) fmt.Println("channel closed") }
Translate this program into C but keep the logic exactly as in REXX.
tlaloc = "rain god of the Aztecs." y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." y= 'xiuhtecuhtli' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." drop tlaloc y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined."
#include <stdio.h> #include <stdlib.h> int main() { int junk, *junkp; printf("junk: %d\n", junk); junkp = malloc(sizeof *junkp); if (junkp) printf("*junkp: %d\n", *junkp); return 0; }
Please provide an equivalent version of this REXX code in C#.
tlaloc = "rain god of the Aztecs." y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." y= 'xiuhtecuhtli' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." drop tlaloc y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined."
string foo = null;
Can you help me rewrite this code in C++ instead of REXX, keeping it the same logically?
tlaloc = "rain god of the Aztecs." y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." y= 'xiuhtecuhtli' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." drop tlaloc y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined."
#include <iostream> int main() { int undefined; if (undefined == 42) { std::cout << "42"; } if (undefined != 42) { std::cout << "not 42"; } }
Convert this REXX block to Java, preserving its control flow and logic.
tlaloc = "rain god of the Aztecs." y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." y= 'xiuhtecuhtli' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." drop tlaloc y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined."
String string = null; System.out.println(string); System.out.println(string.length());
Transform the following REXX implementation into Python, maintaining the same output and logic.
tlaloc = "rain god of the Aztecs." y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." y= 'xiuhtecuhtli' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." drop tlaloc y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined."
try: name except NameError: print "name is undefined at first check" name = "Chocolate" try: name except NameError: print "name is undefined at second check" del name try: name except NameError: print "name is undefined at third check" name = 42 try: name except NameError: print "name is undefined at fourth check" print "Done"
Maintain the same structure and functionality when rewriting this code in Go.
tlaloc = "rain god of the Aztecs." y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." y= 'xiuhtecuhtli' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." drop tlaloc y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined."
package main import "fmt" var ( s []int p *int f func() i interface{} m map[int]int c chan int ) func main() { fmt.Println("Exercise nil objects:") status() s = make([]int, 1) p = &s[0] f = func() { fmt.Println("function call") } i = user(0) m = make(map[int]int) c = make(chan int, 1) fmt.Println("\nExercise objects after initialization:") status() } type user int func (user) m() { fmt.Println("method call") } func status() { trySlice() tryPointer() tryFunction() tryInterface() tryMap() tryChannel() } func reportPanic() { if x := recover(); x != nil { fmt.Println("panic:", x) } } func trySlice() { defer reportPanic() fmt.Println("s[0] =", s[0]) } func tryPointer() { defer reportPanic() fmt.Println("*p =", *p) } func tryFunction() { defer reportPanic() f() } func tryInterface() { defer reportPanic() switch i.(type) { case nil: fmt.Println("i is nil interface") case interface { m() }: fmt.Println("i has method m") } i.(interface { m() }).m() } func tryMap() { defer reportPanic() m[0] = 0 fmt.Println("m[0] =", m[0]) } func tryChannel() { defer reportPanic() close(c) fmt.Println("channel closed") }
Rewrite this program in C while keeping its functionality equivalent to the Ruby version.
puts "var is undefined at first check" unless defined? var var = "Chocolate" puts "var is undefined at second check" unless defined? var puts "Done"
#include <stdio.h> #include <stdlib.h> int main() { int junk, *junkp; printf("junk: %d\n", junk); junkp = malloc(sizeof *junkp); if (junkp) printf("*junkp: %d\n", *junkp); return 0; }
Produce a functionally identical C# code for the snippet given in Ruby.
puts "var is undefined at first check" unless defined? var var = "Chocolate" puts "var is undefined at second check" unless defined? var puts "Done"
string foo = null;
Rewrite the snippet below in C++ so it works the same as the original Ruby code.
puts "var is undefined at first check" unless defined? var var = "Chocolate" puts "var is undefined at second check" unless defined? var puts "Done"
#include <iostream> int main() { int undefined; if (undefined == 42) { std::cout << "42"; } if (undefined != 42) { std::cout << "not 42"; } }
Can you help me rewrite this code in Java instead of Ruby, keeping it the same logically?
puts "var is undefined at first check" unless defined? var var = "Chocolate" puts "var is undefined at second check" unless defined? var puts "Done"
String string = null; System.out.println(string); System.out.println(string.length());
Ensure the translated Python code behaves exactly like the original Ruby snippet.
puts "var is undefined at first check" unless defined? var var = "Chocolate" puts "var is undefined at second check" unless defined? var puts "Done"
try: name except NameError: print "name is undefined at first check" name = "Chocolate" try: name except NameError: print "name is undefined at second check" del name try: name except NameError: print "name is undefined at third check" name = 42 try: name except NameError: print "name is undefined at fourth check" print "Done"
Generate a Go translation of this Ruby snippet without changing its computational steps.
puts "var is undefined at first check" unless defined? var var = "Chocolate" puts "var is undefined at second check" unless defined? var puts "Done"
package main import "fmt" var ( s []int p *int f func() i interface{} m map[int]int c chan int ) func main() { fmt.Println("Exercise nil objects:") status() s = make([]int, 1) p = &s[0] f = func() { fmt.Println("function call") } i = user(0) m = make(map[int]int) c = make(chan int, 1) fmt.Println("\nExercise objects after initialization:") status() } type user int func (user) m() { fmt.Println("method call") } func status() { trySlice() tryPointer() tryFunction() tryInterface() tryMap() tryChannel() } func reportPanic() { if x := recover(); x != nil { fmt.Println("panic:", x) } } func trySlice() { defer reportPanic() fmt.Println("s[0] =", s[0]) } func tryPointer() { defer reportPanic() fmt.Println("*p =", *p) } func tryFunction() { defer reportPanic() f() } func tryInterface() { defer reportPanic() switch i.(type) { case nil: fmt.Println("i is nil interface") case interface { m() }: fmt.Println("i has method m") } i.(interface { m() }).m() } func tryMap() { defer reportPanic() m[0] = 0 fmt.Println("m[0] =", m[0]) } func tryChannel() { defer reportPanic() close(c) fmt.Println("channel closed") }
Port the following code from Scala to C with equivalent syntax and logic.
class SomeClass class SomeOtherClass { lateinit var sc: SomeClass fun initialize() { sc = SomeClass() } fun printSomething() { println(sc) } fun someFunc(): String { TODO("someFunc not yet implemented") } } fun main(args: Array<String>) { val soc = SomeOtherClass() try { soc.printSomething() } catch (ex: Exception) { println(ex) } try { soc.someFunc() } catch (e: Error) { println(e) } }
#include <stdio.h> #include <stdlib.h> int main() { int junk, *junkp; printf("junk: %d\n", junk); junkp = malloc(sizeof *junkp); if (junkp) printf("*junkp: %d\n", *junkp); return 0; }
Generate an equivalent C# version of this Scala code.
class SomeClass class SomeOtherClass { lateinit var sc: SomeClass fun initialize() { sc = SomeClass() } fun printSomething() { println(sc) } fun someFunc(): String { TODO("someFunc not yet implemented") } } fun main(args: Array<String>) { val soc = SomeOtherClass() try { soc.printSomething() } catch (ex: Exception) { println(ex) } try { soc.someFunc() } catch (e: Error) { println(e) } }
string foo = null;
Please provide an equivalent version of this Scala code in C++.
class SomeClass class SomeOtherClass { lateinit var sc: SomeClass fun initialize() { sc = SomeClass() } fun printSomething() { println(sc) } fun someFunc(): String { TODO("someFunc not yet implemented") } } fun main(args: Array<String>) { val soc = SomeOtherClass() try { soc.printSomething() } catch (ex: Exception) { println(ex) } try { soc.someFunc() } catch (e: Error) { println(e) } }
#include <iostream> int main() { int undefined; if (undefined == 42) { std::cout << "42"; } if (undefined != 42) { std::cout << "not 42"; } }
Preserve the algorithm and functionality while converting the code from Scala to Java.
class SomeClass class SomeOtherClass { lateinit var sc: SomeClass fun initialize() { sc = SomeClass() } fun printSomething() { println(sc) } fun someFunc(): String { TODO("someFunc not yet implemented") } } fun main(args: Array<String>) { val soc = SomeOtherClass() try { soc.printSomething() } catch (ex: Exception) { println(ex) } try { soc.someFunc() } catch (e: Error) { println(e) } }
String string = null; System.out.println(string); System.out.println(string.length());
Change the following Scala code into Python without altering its purpose.
class SomeClass class SomeOtherClass { lateinit var sc: SomeClass fun initialize() { sc = SomeClass() } fun printSomething() { println(sc) } fun someFunc(): String { TODO("someFunc not yet implemented") } } fun main(args: Array<String>) { val soc = SomeOtherClass() try { soc.printSomething() } catch (ex: Exception) { println(ex) } try { soc.someFunc() } catch (e: Error) { println(e) } }
try: name except NameError: print "name is undefined at first check" name = "Chocolate" try: name except NameError: print "name is undefined at second check" del name try: name except NameError: print "name is undefined at third check" name = 42 try: name except NameError: print "name is undefined at fourth check" print "Done"
Preserve the algorithm and functionality while converting the code from Scala to Go.
class SomeClass class SomeOtherClass { lateinit var sc: SomeClass fun initialize() { sc = SomeClass() } fun printSomething() { println(sc) } fun someFunc(): String { TODO("someFunc not yet implemented") } } fun main(args: Array<String>) { val soc = SomeOtherClass() try { soc.printSomething() } catch (ex: Exception) { println(ex) } try { soc.someFunc() } catch (e: Error) { println(e) } }
package main import "fmt" var ( s []int p *int f func() i interface{} m map[int]int c chan int ) func main() { fmt.Println("Exercise nil objects:") status() s = make([]int, 1) p = &s[0] f = func() { fmt.Println("function call") } i = user(0) m = make(map[int]int) c = make(chan int, 1) fmt.Println("\nExercise objects after initialization:") status() } type user int func (user) m() { fmt.Println("method call") } func status() { trySlice() tryPointer() tryFunction() tryInterface() tryMap() tryChannel() } func reportPanic() { if x := recover(); x != nil { fmt.Println("panic:", x) } } func trySlice() { defer reportPanic() fmt.Println("s[0] =", s[0]) } func tryPointer() { defer reportPanic() fmt.Println("*p =", *p) } func tryFunction() { defer reportPanic() f() } func tryInterface() { defer reportPanic() switch i.(type) { case nil: fmt.Println("i is nil interface") case interface { m() }: fmt.Println("i has method m") } i.(interface { m() }).m() } func tryMap() { defer reportPanic() m[0] = 0 fmt.Println("m[0] =", m[0]) } func tryChannel() { defer reportPanic() close(c) fmt.Println("channel closed") }
Translate the given Tcl code snippet into C without altering its behavior.
if {![info exists var]} {puts "var is undefind at first check"} set var "Screwy Squirrel" if {![info exists var]} {puts "var is undefind at second check"} unset var if {![info exists var]} {puts "var is undefind at third check"} set var 12345 if {![info exists var]} {puts "var is undefind at fourth check"} puts "Done"
#include <stdio.h> #include <stdlib.h> int main() { int junk, *junkp; printf("junk: %d\n", junk); junkp = malloc(sizeof *junkp); if (junkp) printf("*junkp: %d\n", *junkp); return 0; }
Write a version of this Tcl function in C# with identical behavior.
if {![info exists var]} {puts "var is undefind at first check"} set var "Screwy Squirrel" if {![info exists var]} {puts "var is undefind at second check"} unset var if {![info exists var]} {puts "var is undefind at third check"} set var 12345 if {![info exists var]} {puts "var is undefind at fourth check"} puts "Done"
string foo = null;
Preserve the algorithm and functionality while converting the code from Tcl to C++.
if {![info exists var]} {puts "var is undefind at first check"} set var "Screwy Squirrel" if {![info exists var]} {puts "var is undefind at second check"} unset var if {![info exists var]} {puts "var is undefind at third check"} set var 12345 if {![info exists var]} {puts "var is undefind at fourth check"} puts "Done"
#include <iostream> int main() { int undefined; if (undefined == 42) { std::cout << "42"; } if (undefined != 42) { std::cout << "not 42"; } }
Generate an equivalent Java version of this Tcl code.
if {![info exists var]} {puts "var is undefind at first check"} set var "Screwy Squirrel" if {![info exists var]} {puts "var is undefind at second check"} unset var if {![info exists var]} {puts "var is undefind at third check"} set var 12345 if {![info exists var]} {puts "var is undefind at fourth check"} puts "Done"
String string = null; System.out.println(string); System.out.println(string.length());
Write the same code in Python as shown below in Tcl.
if {![info exists var]} {puts "var is undefind at first check"} set var "Screwy Squirrel" if {![info exists var]} {puts "var is undefind at second check"} unset var if {![info exists var]} {puts "var is undefind at third check"} set var 12345 if {![info exists var]} {puts "var is undefind at fourth check"} puts "Done"
try: name except NameError: print "name is undefined at first check" name = "Chocolate" try: name except NameError: print "name is undefined at second check" del name try: name except NameError: print "name is undefined at third check" name = 42 try: name except NameError: print "name is undefined at fourth check" print "Done"
Can you help me rewrite this code in Go instead of Tcl, keeping it the same logically?
if {![info exists var]} {puts "var is undefind at first check"} set var "Screwy Squirrel" if {![info exists var]} {puts "var is undefind at second check"} unset var if {![info exists var]} {puts "var is undefind at third check"} set var 12345 if {![info exists var]} {puts "var is undefind at fourth check"} puts "Done"
package main import "fmt" var ( s []int p *int f func() i interface{} m map[int]int c chan int ) func main() { fmt.Println("Exercise nil objects:") status() s = make([]int, 1) p = &s[0] f = func() { fmt.Println("function call") } i = user(0) m = make(map[int]int) c = make(chan int, 1) fmt.Println("\nExercise objects after initialization:") status() } type user int func (user) m() { fmt.Println("method call") } func status() { trySlice() tryPointer() tryFunction() tryInterface() tryMap() tryChannel() } func reportPanic() { if x := recover(); x != nil { fmt.Println("panic:", x) } } func trySlice() { defer reportPanic() fmt.Println("s[0] =", s[0]) } func tryPointer() { defer reportPanic() fmt.Println("*p =", *p) } func tryFunction() { defer reportPanic() f() } func tryInterface() { defer reportPanic() switch i.(type) { case nil: fmt.Println("i is nil interface") case interface { m() }: fmt.Println("i has method m") } i.(interface { m() }).m() } func tryMap() { defer reportPanic() m[0] = 0 fmt.Println("m[0] =", m[0]) } func tryChannel() { defer reportPanic() close(c) fmt.Println("channel closed") }
Please provide an equivalent version of this Rust code in PHP.
use std::ptr; let p: *const i32 = ptr::null(); assert!(p.is_null());
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Can you help me rewrite this code in PHP instead of Ada, keeping it the same logically?
pragma Initialize_Scalars; with Ada.Text_IO; use Ada.Text_IO; procedure Invalid_Value is type Color is (Red, Green, Blue); X : Float; Y : Color; begin if not X'Valid then Put_Line ("X is not valid"); end if; X := 1.0; if X'Valid then Put_Line ("X is" & Float'Image (X)); end if; if not Y'Valid then Put_Line ("Y is not valid"); end if; Y := Green; if Y'Valid then Put_Line ("Y is " & Color'Image (Y)); end if; end Invalid_Value;
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Change the following Arturo code into PHP without altering its purpose.
undef: null print undef
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Rewrite this program in PHP while keeping its functionality equivalent to the BBC_Basic version.
ok% = TRUE ON ERROR LOCAL IF ERR<>26 REPORT : END ELSE ok% = FALSE IF ok% THEN PRINT variable$ ELSE PRINT "Not defined" ENDIF RESTORE ERROR
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Translate this program into PHP but keep the logic exactly as in Common_Lisp.
(defvar *x*) (defvar *y* 42) (special-variable-p '*x*) -> T (boundp '*x*) -> NIL (boundp '*y*) -> T (special-variable-p '*z*) -> NIL
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Convert the following code from D to PHP, ensuring the logic remains intact.
void main() { int a = 5; double b = 5.0; char c = 'f'; int[] d = [1, 2, 3]; int aa; double bb; char cc; int[] dd; int[3] ee; int aaa = void; double[] bbb = void; int[3] eee = void; }
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Transform the following Delphi implementation into PHP, maintaining the same output and logic.
var P: PInteger; begin New(P); try If Assigned(P) Then begin P^ := 42; end; finally Dispose(P); end; end;
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Change the following Erlang code into PHP without altering its purpose.
-module( undefined_values ). -export( [task/0] ). -record( a_record, {member_1, member_2} ). task() -> Record = #a_record{member_1=a_value}, io:fwrite( "Record member_1 ~p, member_2 ~p~n", [Record#a_record.member_1, Record#a_record.member_2] ), io:fwrite( "Member_2 is undefined ~p~n", [Record#a_record.member_2 =:= undefined] ).
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Generate a PHP translation of this Factor snippet without changing its computational steps.
42 .
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Preserve the algorithm and functionality while converting the code from Fortran to PHP.
IsNaN(x)
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Write the same algorithm in PHP as shown in this Haskell implementation.
main = print $ "Incoming error
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Convert the following code from J to PHP, ensuring the logic remains intact.
foo=: 3 nc;:'foo bar' 0 _1
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Translate this program into PHP but keep the logic exactly as in Julia.
julia> arr = [1, 2, nothing, 3] 4-element Array{Union{Nothing, Int64},1}: 1 2 nothing 3 julia> x = arr .+ 5 ERROR: MethodError: no method matching +(::Nothing, ::Int64) Closest candidates are: +(::Any, ::Any, ::Any, ::Any...) at operators.jl:502 +(::Complex{Bool}, ::Real) at complex.jl:292 +(::Missing, ::Number) at missing.jl:93 ... julia> arr = [1, 2, missing, 3] 4-element Array{Union{Missing, Int64},1}: 1 2 missing 3 julia> x = arr .+ 5 4-element Array{Union{Missing, Int64},1}: 6 7 missing 8
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Transform the following Lua implementation into PHP, maintaining the same output and logic.
print( a ) local b print( b ) if b == nil then b = 5 end print( b )
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Transform the following Mathematica implementation into PHP, maintaining the same output and logic.
a -> a a + a -> 2 a ValueQ[a] -> False a = 5 -> 5 ValueQ[a] -> True
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Port the following code from MATLAB to PHP with equivalent syntax and logic.
global var;
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Preserve the algorithm and functionality while converting the code from Nim to PHP.
var a {.noInit.}: array[1_000_000, int] proc p(): array[1000, int] {.noInit.} = for i in 0..999: result[i] = i
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Keep all operations the same but rewrite the snippet in PHP.
let inc = function Some n -> Some (n+1) | None -> failwith "Undefined argument";; inc (Some 0);; inc None;;
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Preserve the algorithm and functionality while converting the code from Perl to PHP.
use strict; our $var; print "var contains an undefined value at first check\n" unless defined $var; $var = "Chocolate"; print "var contains an undefined value at second check\n" unless defined $var; $var = undef; undef($var); print "var contains an undefined value at third check\n" unless defined $var; $var = 42; print "var contains an undefined value at fourth check\n" unless defined $var; print "Done\n";
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Produce a functionally identical PHP code for the snippet given in PowerShell.
if (Get-Variable -Name noSuchVariable -ErrorAction SilentlyContinue) { $true } else { $false }
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Produce a language-to-language conversion: from R to PHP, same semantics.
exists("x")
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Ensure the translated PHP code behaves exactly like the original Racket snippet.
-> (letrec ([x x]) x) #<undefined>
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Rewrite this program in PHP while keeping its functionality equivalent to the REXX version.
tlaloc = "rain god of the Aztecs." y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." y= 'xiuhtecuhtli' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined." drop tlaloc y= 'tlaloc' if symbol(y)=="VAR" then say y ' is defined.' else say y "isn't defined."
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Please provide an equivalent version of this Ruby code in PHP.
puts "var is undefined at first check" unless defined? var var = "Chocolate" puts "var is undefined at second check" unless defined? var puts "Done"
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Preserve the algorithm and functionality while converting the code from Scala to PHP.
class SomeClass class SomeOtherClass { lateinit var sc: SomeClass fun initialize() { sc = SomeClass() } fun printSomething() { println(sc) } fun someFunc(): String { TODO("someFunc not yet implemented") } } fun main(args: Array<String>) { val soc = SomeOtherClass() try { soc.printSomething() } catch (ex: Exception) { println(ex) } try { soc.someFunc() } catch (e: Error) { println(e) } }
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Rewrite the snippet below in PHP so it works the same as the original Tcl code.
if {![info exists var]} {puts "var is undefind at first check"} set var "Screwy Squirrel" if {![info exists var]} {puts "var is undefind at second check"} unset var if {![info exists var]} {puts "var is undefind at third check"} set var 12345 if {![info exists var]} {puts "var is undefind at fourth check"} puts "Done"
<?php if (!isset($var)) echo "var is undefined at first check\n"; $var = "Chocolate"; if (!isset($var)) echo "var is undefined at second check\n"; unset($var); if (!isset($var)) echo "var is undefined at third check\n"; $var = 42; if (!isset($var)) echo "var is undefined at fourth check\n"; echo "Done\n"; ?>
Write the same algorithm in Rust as shown in this Java implementation.
String string = null; System.out.println(string); System.out.println(string.length());
use std::ptr; let p: *const i32 = ptr::null(); assert!(p.is_null());
Produce a functionally identical Rust code for the snippet given in Go.
package main import "fmt" var ( s []int p *int f func() i interface{} m map[int]int c chan int ) func main() { fmt.Println("Exercise nil objects:") status() s = make([]int, 1) p = &s[0] f = func() { fmt.Println("function call") } i = user(0) m = make(map[int]int) c = make(chan int, 1) fmt.Println("\nExercise objects after initialization:") status() } type user int func (user) m() { fmt.Println("method call") } func status() { trySlice() tryPointer() tryFunction() tryInterface() tryMap() tryChannel() } func reportPanic() { if x := recover(); x != nil { fmt.Println("panic:", x) } } func trySlice() { defer reportPanic() fmt.Println("s[0] =", s[0]) } func tryPointer() { defer reportPanic() fmt.Println("*p =", *p) } func tryFunction() { defer reportPanic() f() } func tryInterface() { defer reportPanic() switch i.(type) { case nil: fmt.Println("i is nil interface") case interface { m() }: fmt.Println("i has method m") } i.(interface { m() }).m() } func tryMap() { defer reportPanic() m[0] = 0 fmt.Println("m[0] =", m[0]) } func tryChannel() { defer reportPanic() close(c) fmt.Println("channel closed") }
use std::ptr; let p: *const i32 = ptr::null(); assert!(p.is_null());
Translate the given Rust code snippet into Python without altering its behavior.
use std::ptr; let p: *const i32 = ptr::null(); assert!(p.is_null());
try: name except NameError: print "name is undefined at first check" name = "Chocolate" try: name except NameError: print "name is undefined at second check" del name try: name except NameError: print "name is undefined at third check" name = 42 try: name except NameError: print "name is undefined at fourth check" print "Done"
Change the programming language of this snippet from C to Rust without modifying what it does.
#include <stdio.h> #include <stdlib.h> int main() { int junk, *junkp; printf("junk: %d\n", junk); junkp = malloc(sizeof *junkp); if (junkp) printf("*junkp: %d\n", *junkp); return 0; }
use std::ptr; let p: *const i32 = ptr::null(); assert!(p.is_null());
Keep all operations the same but rewrite the snippet in Rust.
#include <iostream> int main() { int undefined; if (undefined == 42) { std::cout << "42"; } if (undefined != 42) { std::cout << "not 42"; } }
use std::ptr; let p: *const i32 = ptr::null(); assert!(p.is_null());
Convert the following code from Ada to C#, ensuring the logic remains intact.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Can you help me rewrite this code in C# instead of Ada, keeping it the same logically?
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Port the following code from Ada to C with equivalent syntax and logic.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Transform the following Ada implementation into C, maintaining the same output and logic.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Generate an equivalent C++ version of this Ada code.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Maintain the same structure and functionality when rewriting this code in C++.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
#include <iostream> #include <string> #include <climits> using namespace std; class BalancedTernary { protected: string value; int charToInt(char c) const { if (c == '0') return 0; return 44 - c; } string negate(string s) const { for (int i = 0; i < s.length(); ++i) { if (s[i] == '+') s[i] = '-'; else if (s[i] == '-') s[i] = '+'; } return s; } public: BalancedTernary() { value = "0"; } BalancedTernary(string s) { value = string(s.rbegin(), s.rend()); } BalancedTernary(long long n) { if (n == 0) { value = "0"; return; } bool neg = n < 0; if (neg) n = -n; value = ""; while (n != 0) { int r = n % 3; if (r == 0) value += "0"; else if (r == 1) value += "+"; else { value += "-"; ++n; } n /= 3; } if (neg) value = negate(value); } BalancedTernary(const BalancedTernary &n) { value = n.value; } BalancedTernary operator+(BalancedTernary n) const { n += *this; return n; } BalancedTernary& operator+=(const BalancedTernary &n) { static char *add = "0+-0+-0"; static char *carry = "--000++"; int lastNonZero = 0; char c = '0'; for (int i = 0; i < value.length() || i < n.value.length(); ++i) { char a = i < value.length() ? value[i] : '0'; char b = i < n.value.length() ? n.value[i] : '0'; int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3; c = carry[sum]; if (i < value.length()) value[i] = add[sum]; else value += add[sum]; if (add[sum] != '0') lastNonZero = i; } if (c != '0') value += c; else value = value.substr(0, lastNonZero + 1); return *this; } BalancedTernary operator-() const { BalancedTernary result; result.value = negate(value); return result; } BalancedTernary operator-(const BalancedTernary &n) const { return operator+(-n); } BalancedTernary& operator-=(const BalancedTernary &n) { return operator+=(-n); } BalancedTernary operator*(BalancedTernary n) const { n *= *this; return n; } BalancedTernary& operator*=(const BalancedTernary &n) { BalancedTernary pos = *this; BalancedTernary neg = -pos; value = "0"; for (int i = 0; i < n.value.length(); ++i) { if (n.value[i] == '+') operator+=(pos); else if (n.value[i] == '-') operator+=(neg); pos.value = '0' + pos.value; neg.value = '0' + neg.value; } return *this; } friend ostream& operator<<(ostream &out, const BalancedTernary &n) { out << n.toString(); return out; } string toString() const { return string(value.rbegin(), value.rend()); } long long toInt() const { long long result = 0; for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3) result += pow * charToInt(value[i]); return result; } bool tryInt(long long &out) const { long long result = 0; bool ok = true; for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) { if (value[i] == '+') { ok &= LLONG_MAX - pow >= result; result += pow; } else if (value[i] == '-') { ok &= LLONG_MIN + pow <= result; result -= pow; } } if (ok) out = result; return ok; } }; int main() { BalancedTernary a("+-0++0+"); BalancedTernary b(-436); BalancedTernary c("+-++-"); cout << "a = " << a << " = " << a.toInt() << endl; cout << "b = " << b << " = " << b.toInt() << endl; cout << "c = " << c << " = " << c.toInt() << endl; BalancedTernary d = a * (b - c); cout << "a * (b - c) = " << d << " = " << d.toInt() << endl; BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++"); long long n; if (e.tryInt(n)) cout << "e = " << e << " = " << n << endl; else cout << "e = " << e << " is too big to fit in a long long" << endl; return 0; }
Translate this program into Go but keep the logic exactly as in Ada.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Convert this Ada snippet to Go and keep its semantics consistent.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
package main import ( "fmt" "strings" ) type bt []int8 func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Change the programming language of this snippet from Ada to Java without modifying what it does.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Convert this Ada snippet to Java and keep its semantics consistent.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Produce a language-to-language conversion: from Ada to Python, same semantics.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Preserve the algorithm and functionality while converting the code from Ada to Python.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Write the same algorithm in VB as shown in this Ada implementation.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Convert the following code from Ada to VB, ensuring the logic remains intact.
with Ada.Finalization; package BT is type Balanced_Ternary is private; function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; function To_Balanced_Ternary (Str : String) return Balanced_Ternary; function To_Integer (Num : Balanced_Ternary) return Integer; function To_string (Num : Balanced_Ternary) return String; function "-" (Left : in Balanced_Ternary) return Balanced_Ternary; function "-" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "+" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; function "*" (Left, Right : in Balanced_Ternary) return Balanced_Ternary; private type Trit is range -1..1; type Trit_Array is array (Positive range <>) of Trit; pragma Pack(Trit_Array); type Trit_Access is access Trit_Array; type Balanced_Ternary is new Ada.Finalization.Controlled with record Ref : Trit_access; end record; procedure Initialize (Object : in out Balanced_Ternary); procedure Adjust (Object : in out Balanced_Ternary); procedure Finalize (Object : in out Balanced_Ternary); end BT;
Imports System.Text Module Module1 Sub Main() Dim a As New BalancedTernary("+-0++0+") Console.WriteLine("a: {0} = {1}", a, a.ToLong) Dim b As New BalancedTernary(-436) Console.WriteLine("b: {0} = {1}", b, b.ToLong) Dim c As New BalancedTernary("+-++-") Console.WriteLine("c: {0} = {1}", c, c.ToLong) Dim d = a * (b - c) Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) End Sub Class BalancedTernary Private Enum BalancedTernaryDigit MINUS = -1 ZERO = 0 PLUS = 1 End Enum Private ReadOnly value() As BalancedTernaryDigit Public Sub New() ReDim value(-1) End Sub Public Sub New(str As String) ReDim value(str.Length - 1) For i = 1 To str.Length If str(i - 1) = "-" Then value(i - 1) = BalancedTernaryDigit.MINUS ElseIf str(i - 1) = "0" Then value(i - 1) = BalancedTernaryDigit.ZERO ElseIf str(i - 1) = "+" Then value(i - 1) = BalancedTernaryDigit.PLUS Else Throw New ArgumentException("Unknown Digit: " + str(i - 1)) End If Next Array.Reverse(value) End Sub Public Sub New(l As Long) Dim value As New List(Of BalancedTernaryDigit) Dim sign = Math.Sign(l) l = Math.Abs(l) While l <> 0 Dim remainder = CType(l Mod 3, Byte) If remainder = 0 OrElse remainder = 1 Then value.Add(remainder) l /= 3 ElseIf remainder = 2 Then value.Add(BalancedTernaryDigit.MINUS) l = (l + 1) / 3 End If End While Me.value = value.ToArray If sign < 0 Then Invert() End If End Sub Public Sub New(origin As BalancedTernary) ReDim value(origin.value.Length - 1) Array.Copy(origin.value, value, origin.value.Length) End Sub Private Sub New(value() As BalancedTernaryDigit) Dim endi = value.Length - 1 While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO endi -= 1 End While ReDim Me.value(endi) Array.Copy(value, Me.value, endi + 1) End Sub Private Sub Invert() For i = 1 To value.Length value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) Next End Sub Public Overrides Function ToString() As String Dim result As New StringBuilder Dim i = value.Length - 1 While i >= 0 If value(i) = BalancedTernaryDigit.MINUS Then result.Append("-") ElseIf value(i) = BalancedTernaryDigit.ZERO Then result.Append("0") ElseIf value(i) = BalancedTernaryDigit.PLUS Then result.Append("+") End If i -= 1 End While Return result.ToString End Function Public Function ToLong() As Long Dim result = 0L For i = 1 To value.Length result += value(i - 1) * Math.Pow(3.0, i - 1) Next Return result End Function Public Shared Operator -(origin As BalancedTernary) As BalancedTernary Dim result As New BalancedTernary(origin) result.Invert() Return result End Operator Private Shared carry = BalancedTernaryDigit.ZERO Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit If a <> b Then carry = BalancedTernaryDigit.ZERO Return a + b Else carry = a Return -CType(b, Integer) End If End Function Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim maxLength = Math.Max(a.value.Length, b.value.Length) Dim resultValue(maxLength) As BalancedTernaryDigit For i = 1 To maxLength If i - 1 < a.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) resultValue(i) = carry Else carry = BalancedTernaryDigit.ZERO End If If i - 1 < b.value.Length Then resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) resultValue(i) = Add(resultValue(i), carry) End If Next Return New BalancedTernary(resultValue) End Operator Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Return a + (-b) End Operator Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary Dim longValue = a.value Dim shortValue = b.value Dim result As New BalancedTernary If a.value.Length < b.value.Length Then longValue = b.value shortValue = a.value End If For i = 1 To shortValue.Length If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit For j = 1 To longValue.Length temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) Next result += New BalancedTernary(temp) End If Next Return result End Operator End Class End Module
Translate this program into C but keep the logic exactly as in AutoHotKey.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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 an equivalent C version of this AutoHotKey code.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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; }
Change the programming language of this snippet from AutoHotKey to C# without modifying what it does.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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; } }
Write the same algorithm in C# as shown in this AutoHotKey implementation.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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 AutoHotKey to C++ without modifying what it does.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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 C++ translation of this AutoHotKey snippet without changing its computational steps.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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 the same algorithm in Java as shown in this AutoHotKey implementation.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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; } } }
Convert this AutoHotKey block to Java, preserving its control flow and logic.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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; } } }
Convert this AutoHotKey block to Python, preserving its control flow and logic.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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()
Write the same algorithm in Python as shown in this AutoHotKey implementation.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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()
Transform the following AutoHotKey implementation into VB, maintaining the same output and logic.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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
Write the same code in VB as shown below in AutoHotKey.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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
Change the following AutoHotKey code into Go without altering its purpose.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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") } }
Ensure the translated Go code behaves exactly like the original AutoHotKey snippet.
BalancedTernary(n){ k = 0 if abs(n)<2 return n=1?"+":n=0?"0":"-" if n<1 negative := true, n:= -1*n while !break { d := Mod(n, 3**(k+1)) / 3**k d := d=2?-1:d n := n - (d * 3**k) r := (d=-1?"-":d=1?"+":0) . r k++ if (n = 3**k) r := "+" . r , break := true } if negative { StringReplace, r, r, -,n, all StringReplace, r, r, `+,-, all StringReplace, r, r, n,+, all } return 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") } }
Transform the following Common_Lisp implementation into C, maintaining the same output 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)))
#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 Common_Lisp code in C.
(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)))
#include <stdio.h> #include <string.h> void reverse(char *p) { size_t len = strlen(p); char *r = p + len - 1; while (p < r) { *p ^= *r; *r ^= *p; *p++ ^= *r--; } } void to_bt(int n, char *b) { static char d[] = { '0', '+', '-' }; static int v[] = { 0, 1, -1 }; char *ptr = b; *ptr = 0; while (n) { int r = n % 3; if (r < 0) { r += 3; } *ptr = d[r]; *(++ptr) = 0; n -= v[r]; n /= 3; } reverse(b); } int from_bt(const char *a) { int n = 0; while (*a != '\0') { n *= 3; if (*a == '+') { n++; } else if (*a == '-') { n--; } a++; } return n; } char last_char(char *ptr) { char c; if (ptr == NULL || *ptr == '\0') { return '\0'; } while (*ptr != '\0') { ptr++; } ptr--; c = *ptr; *ptr = 0; return c; } void add(const char *b1, const char *b2, char *out) { if (*b1 != '\0' && *b2 != '\0') { char c1[16]; char c2[16]; char ob1[16]; char ob2[16]; char d[3] = { 0, 0, 0 }; char L1, L2; strcpy(c1, b1); strcpy(c2, b2); L1 = last_char(c1); L2 = last_char(c2); if (L2 < L1) { L2 ^= L1; L1 ^= L2; L2 ^= L1; } if (L1 == '-') { if (L2 == '0') { d[0] = '-'; } if (L2 == '-') { d[0] = '+'; d[1] = '-'; } } if (L1 == '+') { if (L2 == '0') { d[0] = '+'; } if (L2 == '-') { d[0] = '0'; } if (L2 == '+') { d[0] = '-'; d[1] = '+'; } } if (L1 == '0') { if (L2 == '0') { d[0] = '0'; } } add(c1, &d[1], ob1); add(ob1, c2, ob2); strcpy(out, ob2); d[1] = 0; strcat(out, d); } else if (*b1 != '\0') { strcpy(out, b1); } else if (*b2 != '\0') { strcpy(out, b2); } else { *out = '\0'; } } void unary_minus(const char *b, char *out) { while (*b != '\0') { if (*b == '-') { *out++ = '+'; b++; } else if (*b == '+') { *out++ = '-'; b++; } else { *out++ = *b++; } } *out = '\0'; } void subtract(const char *b1, const char *b2, char *out) { char buf[16]; unary_minus(b2, buf); add(b1, buf, out); } void mult(const char *b1, const char *b2, char *out) { char r[16] = "0"; char t[16]; char c1[16]; char c2[16]; char *ptr = c2; strcpy(c1, b1); strcpy(c2, b2); reverse(c2); while (*ptr != '\0') { if (*ptr == '+') { add(r, c1, t); strcpy(r, t); } if (*ptr == '-') { subtract(r, c1, t); strcpy(r, t); } strcat(c1, "0"); ptr++; } ptr = r; while (*ptr == '0') { ptr++; } strcpy(out, ptr); } int main() { const char *a = "+-0++0+"; char b[16]; const char *c = "+-++-"; char t[16]; char d[16]; to_bt(-436, b); subtract(b, c, t); mult(a, t, d); printf(" a: %14s %10d\n", a, from_bt(a)); printf(" b: %14s %10d\n", b, from_bt(b)); printf(" c: %14s %10d\n", c, from_bt(c)); printf("a*(b-c): %14s %10d\n", d, from_bt(d)); return 0; }
Change the following Common_Lisp code into C# without altering its purpose.
(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)))
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 the given Common_Lisp code snippet into C# without altering its behavior.
(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)))
using System; using System.Text; using System.Collections.Generic; public class BalancedTernary { public static void Main() { BalancedTernary a = new BalancedTernary("+-0++0+"); System.Console.WriteLine("a: " + a + " = " + a.ToLong()); BalancedTernary b = new BalancedTernary(-436); System.Console.WriteLine("b: " + b + " = " + b.ToLong()); BalancedTernary c = new BalancedTernary("+-++-"); System.Console.WriteLine("c: " + c + " = " + c.ToLong()); BalancedTernary d = a * (b - c); System.Console.WriteLine("a * (b - c): " + d + " = " + d.ToLong()); } private enum BalancedTernaryDigit { MINUS = -1, ZERO = 0, PLUS = 1 } private BalancedTernaryDigit[] value; public BalancedTernary() { this.value = new BalancedTernaryDigit[0]; } public BalancedTernary(String str) { this.value = new BalancedTernaryDigit[str.Length]; for (int i = 0; i < str.Length; ++i) { switch (str[i]) { case '-': this.value[i] = BalancedTernaryDigit.MINUS; break; case '0': this.value[i] = BalancedTernaryDigit.ZERO; break; case '+': this.value[i] = BalancedTernaryDigit.PLUS; break; default: throw new ArgumentException("Unknown Digit: " + str[i]); } } Array.Reverse(this.value); } public BalancedTernary(long l) { List<BalancedTernaryDigit> value = new List<BalancedTernaryDigit>(); int sign = Math.Sign(l); l = Math.Abs(l); while (l != 0) { byte rem = (byte)(l % 3); switch (rem) { case 0: case 1: value.Add((BalancedTernaryDigit)rem); l /= 3; break; case 2: value.Add(BalancedTernaryDigit.MINUS); l = (l + 1) / 3; break; } } this.value = value.ToArray(); if (sign < 0) { this.Invert(); } } public BalancedTernary(BalancedTernary origin) { this.value = new BalancedTernaryDigit[origin.value.Length]; Array.Copy(origin.value, this.value, origin.value.Length); } private BalancedTernary(BalancedTernaryDigit[] value) { int end = value.Length - 1; while (value[end] == BalancedTernaryDigit.ZERO) --end; this.value = new BalancedTernaryDigit[end + 1]; Array.Copy(value, this.value, end + 1); } private void Invert() { for (int i=0; i < this.value.Length; ++i) { this.value[i] = (BalancedTernaryDigit)(-(int)this.value[i]); } } override public String ToString() { StringBuilder result = new StringBuilder(); for (int i = this.value.Length - 1; i >= 0; --i) { switch (this.value[i]) { case BalancedTernaryDigit.MINUS: result.Append('-'); break; case BalancedTernaryDigit.ZERO: result.Append('0'); break; case BalancedTernaryDigit.PLUS: result.Append('+'); break; } } return result.ToString(); } public long ToLong() { long result = 0; int digit; for (int i = 0; i < this.value.Length; ++i) { result += (long)this.value[i] * (long)Math.Pow(3.0, (double)i); } return result; } public static BalancedTernary operator -(BalancedTernary origin) { BalancedTernary result = new BalancedTernary(origin); result.Invert(); return result; } private static BalancedTernaryDigit carry = BalancedTernaryDigit.ZERO; private static BalancedTernaryDigit Add(BalancedTernaryDigit a, BalancedTernaryDigit b) { if (a != b) { carry = BalancedTernaryDigit.ZERO; return (BalancedTernaryDigit)((int)a + (int)b); } else { carry = a; return (BalancedTernaryDigit)(-(int)b); } } public static BalancedTernary operator +(BalancedTernary a, BalancedTernary b) { int maxLength = Math.Max(a.value.Length, b.value.Length); BalancedTernaryDigit[] resultValue = new BalancedTernaryDigit[maxLength + 1]; for (int i=0; i < maxLength; ++i) { if (i < a.value.Length) { resultValue[i] = Add(resultValue[i], a.value[i]); resultValue[i+1] = carry; } else { carry = BalancedTernaryDigit.ZERO; } if (i < b.value.Length) { resultValue[i] = Add(resultValue[i], b.value[i]); resultValue[i+1] = Add(resultValue[i+1], carry); } } return new BalancedTernary(resultValue); } public static BalancedTernary operator -(BalancedTernary a, BalancedTernary b) { return a + (-b); } public static BalancedTernary operator *(BalancedTernary a, BalancedTernary b) { BalancedTernaryDigit[] longValue = a.value; BalancedTernaryDigit[] shortValue = b.value; BalancedTernary result = new BalancedTernary(); if (a.value.Length < b.value.Length) { longValue = b.value; shortValue = a.value; } for (int i = 0; i < shortValue.Length; ++i) { if (shortValue[i] != BalancedTernaryDigit.ZERO) { BalancedTernaryDigit[] temp = new BalancedTernaryDigit[i + longValue.Length]; for (int j = 0; j < longValue.Length; ++j) { temp[i+j] = (BalancedTernaryDigit)((int)shortValue[i] * (int)longValue[j]); } result = result + new BalancedTernary(temp); } } return result; } }
Produce a functionally identical C++ code for the snippet given in Common_Lisp.
(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)))
#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 algorithm in C++ 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)))
#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 Common_Lisp.
(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)))
public class BalancedTernary { public static void main(String[] args) { BTernary a=new BTernary("+-0++0+"); BTernary b=new BTernary(-436); BTernary c=new BTernary("+-++-"); System.out.println("a="+a.intValue()); System.out.println("b="+b.intValue()); System.out.println("c="+c.intValue()); System.out.println(); BTernary result=a.mul(b.sub(c)); System.out.println("result= "+result+" "+result.intValue()); } public static class BTernary { String value; public BTernary(String s) { int i=0; while(s.charAt(i)=='0') i++; this.value=s.substring(i); } public BTernary(int v) { this.value=""; this.value=convertToBT(v); } private String convertToBT(int v) { if(v<0) return flip(convertToBT(-v)); if(v==0) return ""; int rem=mod3(v); if(rem==0) return convertToBT(v/3)+"0"; if(rem==1) return convertToBT(v/3)+"+"; if(rem==2) return convertToBT((v+1)/3)+"-"; return "You can't see me"; } private String flip(String s) { String flip=""; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='+') flip+='-'; else if(s.charAt(i)=='-') flip+='+'; else flip+='0'; } return flip; } private int mod3(int v) { if(v>0) return v%3; v=v%3; return (v+3)%3; } public int intValue() { int sum=0; String s=this.value; for(int i=0;i<s.length();i++) { char c=s.charAt(s.length()-i-1); int dig=0; if(c=='+') dig=1; else if(c=='-') dig=-1; sum+=dig*Math.pow(3, i); } return sum; } public BTernary add(BTernary that) { String a=this.value; String b=that.value; String longer=a.length()>b.length()?a:b; String shorter=a.length()>b.length()?b:a; while(shorter.length()<longer.length()) shorter=0+shorter; a=longer; b=shorter; char carry='0'; String sum=""; for(int i=0;i<a.length();i++) { int place=a.length()-i-1; String digisum=addDigits(a.charAt(place),b.charAt(place),carry); if(digisum.length()!=1) carry=digisum.charAt(0); else carry='0'; sum=digisum.charAt(digisum.length()-1)+sum; } sum=carry+sum; return new BTernary(sum); } private String addDigits(char a,char b,char carry) { String sum1=addDigits(a,b); String sum2=addDigits(sum1.charAt(sum1.length()-1),carry); if(sum1.length()==1) return sum2; if(sum2.length()==1) return sum1.charAt(0)+sum2; return sum1.charAt(0)+""; } private String addDigits(char a,char b) { String sum=""; if(a=='0') sum=b+""; else if (b=='0') sum=a+""; else if(a=='+') { if(b=='+') sum="+-"; else sum="0"; } else { if(b=='+') sum="0"; else sum="-+"; } return sum; } public BTernary neg() { return new BTernary(flip(this.value)); } public BTernary sub(BTernary that) { return this.add(that.neg()); } public BTernary mul(BTernary that) { BTernary one=new BTernary(1); BTernary zero=new BTernary(0); BTernary mul=new BTernary(0); int flipflag=0; if(that.compareTo(zero)==-1) { that=that.neg(); flipflag=1; } for(BTernary i=new BTernary(1);i.compareTo(that)<1;i=i.add(one)) mul=mul.add(this); if(flipflag==1) mul=mul.neg(); return mul; } public boolean equals(BTernary that) { return this.value.equals(that.value); } public int compareTo(BTernary that) { if(this.intValue()>that.intValue()) return 1; else if(this.equals(that)) return 0; return -1; } public String toString() { return value; } } }
Convert the following code from Common_Lisp to Java, ensuring the logic remains intact.
(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)))
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 code in Python as shown below in Common_Lisp.
(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)))
class BalancedTernary: str2dig = {'+': 1, '-': -1, '0': 0} dig2str = {1: '+', -1: '-', 0: '0'} table = ((0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)) def __init__(self, inp): if isinstance(inp, str): self.digits = [BalancedTernary.str2dig[c] for c in reversed(inp)] elif isinstance(inp, int): self.digits = self._int2ternary(inp) elif isinstance(inp, BalancedTernary): self.digits = list(inp.digits) elif isinstance(inp, list): if all(d in (0, 1, -1) for d in inp): self.digits = list(inp) else: raise ValueError("BalancedTernary: Wrong input digits.") else: raise TypeError("BalancedTernary: Wrong constructor input.") @staticmethod def _int2ternary(n): if n == 0: return [] if (n % 3) == 0: return [0] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 1: return [1] + BalancedTernary._int2ternary(n // 3) if (n % 3) == 2: return [-1] + BalancedTernary._int2ternary((n + 1) // 3) def to_int(self): return reduce(lambda y,x: x + 3 * y, reversed(self.digits), 0) def __repr__(self): if not self.digits: return "0" return "".join(BalancedTernary.dig2str[d] for d in reversed(self.digits)) @staticmethod def _neg(digs): return [-d for d in digs] def __neg__(self): return BalancedTernary(BalancedTernary._neg(self.digits)) @staticmethod def _add(a, b, c=0): if not (a and b): if c == 0: return a or b else: return BalancedTernary._add([c], a or b) else: (d, c) = BalancedTernary.table[3 + (a[0] if a else 0) + (b[0] if b else 0) + c] res = BalancedTernary._add(a[1:], b[1:], c) if res or d != 0: return [d] + res else: return res def __add__(self, b): return BalancedTernary(BalancedTernary._add(self.digits, b.digits)) def __sub__(self, b): return self + (-b) @staticmethod def _mul(a, b): if not (a and b): return [] else: if a[0] == -1: x = BalancedTernary._neg(b) elif a[0] == 0: x = [] elif a[0] == 1: x = b else: assert False y = [0] + BalancedTernary._mul(a[1:], b) return BalancedTernary._add(x, y) def __mul__(self, b): return BalancedTernary(BalancedTernary._mul(self.digits, b.digits)) def main(): a = BalancedTernary("+-0++0+") print "a:", a.to_int(), a b = BalancedTernary(-436) print "b:", b.to_int(), b c = BalancedTernary("+-++-") print "c:", c.to_int(), c r = a * (b - c) print "a * (b - c):", r.to_int(), r main()
Rewrite the snippet below in Python so it works the same as the original Common_Lisp code.
(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)))
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()