Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a language-to-language conversion: from Go to Tcl, same semantics.
package main import ( "fmt" "runtime" "ex" ) func main() { f := func() { pc, _, _, _ := runtime.Caller(0) fmt.Println(runtime.FuncForPC(pc).Name(), "here!") } ex.X(f) }
doFoo 1 2 3; proc doFoo {a b c} { puts [expr {$a + $b*$c}] } doFoo 1 2 3;
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1) p := uint64(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true ...
proc isSquarefree {n} { for {set d 2} {($d * $d) <= $n} {set d [expr {($d+1)|1}]} { if {0 == ($n % $d)} { set n [expr {$n / $d}] if {0 == ($n % $d)} { return 0 ; } } } ...
Change the programming language of this snippet from Go to Tcl without modifying what it does.
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { units := []string{ "tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer", } convs := []float32{ 0.025...
package require units set russian_units { arshin 1.40607 centimeter 100 diuym 39.3701 fut 3.28084 kilometer 0.001 liniya 393.701 meter 1 milia 0.000133912 piad 5.6243 sazhen 0.468691 tochka 3937.01 vershok 22.4972 versta 0.00093...
Keep all operations the same but rewrite the snippet in Tcl.
package main import ( "fmt" "math" "math/big" "reflect" "strings" "unsafe" ) func Float64IsInt(f float64) bool { _, frac := math.Modf(f) return frac == 0 } func Float32IsInt(f float32) bool { return Float64IsInt(float64(f)) } func Complex128IsInt(c complex128) bool { return imag(c) == 0 && Float6...
proc isNumberIntegral {x} { expr {$x == entier($x)} } foreach x {1e100 3.14 7 1.000000000000001 1000000000000000000000 -22.7 -123.000} { puts [format "%s: %s" $x [expr {[isNumberIntegral $x] ? "yes" : "no"}]] }
Convert this Go block to Tcl, preserving its control flow and logic.
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" "time" ) func main() { fmt.Println("CPU usage % at 1 second intervals:\n") var prevIdleTime, prevTotalTime uint64 for i := 0; i < 10; i++ { file, err := os.Open("/proc/stat") if err != nil { ...
proc stat {} { set fd [open /proc/stat r] set prevtotal 0 set previdle 0 while {1} { set line [gets $fd] seek $fd 0 set line [lrange $line 1 end] set total [::tcl::mathop::+ {*}$line] lassign $line user nice system idle iowa...
Can you help me rewrite this code in Tcl instead of Go, keeping it the same logically?
package main import "fmt" var ( a [17][17]int idx [4]int ) func findGroup(ctype, min, max, depth int) bool { if depth == 4 { cs := "" if ctype == 0 { cs = "un" } fmt.Printf("Totally %sconnected group:", cs) for i := 0; i < 4; i++ { fmt.Pri...
package require Tcl 8.6 set init [split [format -%b 53643] ""] set matrix {} for {set r $init} {$r ni $matrix} {set r [concat [lindex $r end] [lrange $r 0 end-1]]} { lappend matrix $r } proc ramseyCheck4 {matrix} { set N [llength $matrix] set connectivity [lrepeat 6 -] for {set a 0} {$a < $N} {incr...
Generate an equivalent Tcl version of this Go code.
package main import "fmt" func main() { tableA := []struct { value int key string }{ {27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"}, {28, "Alan"}, } tableB := []struct { key string value string }{ {"Jonah", "Whales"}, {"Jonah"...
package require Tcl 8.6 proc joinTables {tableA a tableB b} { if {[llength $tableB] < [llength $tableA]} { return [lmap pair [joinTables $tableB $b $tableA $a] { lreverse $pair }] } foreach value $tableA { lappend hashmap([lindex $value $a]) [lreplace $value $a $a] } set result {} ...
Generate an equivalent Tcl version of this Go code.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { ...
proc permutate {values size offset} { set count [llength $values] set arr [list] for {set i 0} {$i < $size} {incr i} { set selector [expr [round [expr $offset / [pow $count $i]]] % $count]; lappend arr [lindex $values $selector] } return $arr } proc permutations {values siz...
Rewrite this program in Tcl while keeping its functionality equivalent to the Go version.
package main import "fmt" var ( n = 3 values = []string{"A", "B", "C", "D"} k = len(values) decide = func(p []string) bool { return p[0] == "B" && p[1] == "C" } ) func main() { pn := make([]int, n) p := make([]string, n) for { for i, x := range pn { ...
proc permutate {values size offset} { set count [llength $values] set arr [list] for {set i 0} {$i < $size} {incr i} { set selector [expr [round [expr $offset / [pow $count $i]]] % $count]; lappend arr [lindex $values $selector] } return $arr } proc permutations {values siz...
Maintain the same structure and functionality when rewriting this code in Tcl.
package main import ( "fmt" "go/ast" "go/parser" "strings" "unicode" ) func isValidIdentifier(identifier string) bool { node, err := parser.ParseExpr(identifier) if err != nil { return false } ident, ok := node.(*ast.Ident) return ok && ident.Name == identifier } type runeRanges struct { ranges []stri...
for {set c 0;set printed 0;set special {}} {$c <= 0xffff} {incr c} { set ch [format "%c" $c] set v "_${ch}_" if {[catch {set $v $c; set $v} msg] || $msg ne $c} { puts [format "\\u%04x illegal in names" $c] incr printed } elseif {[catch {subst $$v} msg] == 0 && $msg eq $c} { lappend special $ch ...
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" "time" ) func main() { scanner := bufio.NewScanner(os.Stdin) number := 0 for number < 1 { fmt.Print("Enter number of seconds delay > 0 : ") scanner.Scan() input := scanner.Text() ...
package require sound fconfigure stdout -buffering none puts -nonewline "How long to wait for (seconds): " gets stdin delay puts -nonewline "What file to play: " gets stdin soundFile snack::sound snd snd read $soundFile after [expr {$delay * 1000}] {snd play -command {set done 1}} vwait done catch {snd stop} snd des...
Please provide an equivalent version of this Go code in Tcl.
package main import ( "fmt" "time" ) func main() { fmt.Print("\033[?1049h\033[H") fmt.Println("Alternate screen buffer\n") s := "s" for i := 5; i > 0; i-- { if i == 1 { s = "" } fmt.Printf("\rgoing back in %d second%s...", i, s) time.Sleep(time.Secon...
proc terminal {args} { exec /usr/bin/tput {*}$args >/dev/tty } terminal smcup puts "This is the top of a blank screen. Press Return/Enter to continue..." gets stdin terminal rmcup
Convert this Go block to Tcl, preserving its control flow and logic.
package main import ( "fmt" "math/big" ) var smallPrimes = [...]int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} const maxStack = 128 var ( tens, values [maxStack]big.Int bigTemp, answer = new(big.Int), new(big.Int) base, seenDepth int ) func addDigit(i int) { for d := 1; d < base; d++ { ...
package require Tcl 8.5 proc tcl::mathfunc::modexp {a b n} { for {set c 1} {$b} {set a [expr {$a*$a%$n}]} { if {$b & 1} { set c [expr {$c*$a%$n}] } set b [expr {$b >> 1}] } return $c } proc is_prime {n {count 10}} { foreach p { 2 3 5 7 11 13 17 19 23 29 31 37...
Translate this program into Tcl but keep the logic exactly as in Go.
package main import ( "go/build" "log" "path/filepath" "github.com/unixpickle/gospeech" "github.com/unixpickle/wav" ) const pkgPath = "github.com/unixpickle/gospeech" const input = "This is an example of speech synthesis." func main() { p, err := build.Import(pkgPath, ".", build.FindOnly) ...
exec festival --tts << "This is an example of speech synthesis."
Produce a language-to-language conversion: from Go to Tcl, same semantics.
package main import ( "log" "math/rand" "testing" "time" "github.com/gonum/plot" "github.com/gonum/plot/plotter" "github.com/gonum/plot/plotutil" "github.com/gonum/plot/vg" ) func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false ...
package require Tk package require struct::list namespace path ::tcl::mathfunc proc create_log10_plot {title xlabel ylabel xs ys labels shapes colours} { set w [toplevel .[clock clicks]] wm title $w $title pack [canvas $w.c -background white] pack [canvas $w.legend -background white] update p...
Translate this program into Tcl but keep the logic exactly as in Go.
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op...
package require struct::list set patterns { {((A x B) y C) z D} {(A x (B y C)) z D} {(A x B) y (C z D)} {A x ((B y C) z D)} {A x (B y (C z D))} } set permutations [struct::list map [struct::list permutations {a b c d}] \ {apply {v {lassign $v a b c d; list A $a B $b C $c D $d}}}] se...
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op...
package require struct::list set patterns { {((A x B) y C) z D} {(A x (B y C)) z D} {(A x B) y (C z D)} {A x ((B y C) z D)} {A x (B y (C z D))} } set permutations [struct::list map [struct::list permutations {a b c d}] \ {apply {v {lassign $v a b c d; list A $a B $b C $c D $d}}}] se...
Port the following code from Go to Tcl with equivalent syntax and logic.
package main import "fmt" type sBox [8][16]byte type gost struct { k87, k65, k43, k21 [256]byte enc []byte } func newGost(s *sBox) *gost { var g gost for i := range g.k87 { g.k87[i] = s[7][i>>4]<<4 | s[6][i&15] g.k65[i] = s[5][i>>4]<<4 | s[4][i&15] g.k43[i] = s...
namespace eval ::GOST { proc tcl::mathfunc::k {a b} { variable ::GOST::replacementTable lindex $replacementTable $a $b } proc mainStep {textBlock idx key} { variable replacementTable lassign [lindex $textBlock $idx] N0 N1 set S [expr {($N0 + $key) & 0xFFFFFFFF}] set newS 0 for {set i 0} {$i < 4} {in...
Write the same code in Tcl as shown below in Go.
package main import "fmt" const jobs = 12 type environment struct{ seq, cnt int } var ( env [jobs]environment seq, cnt *int ) func hail() { fmt.Printf("% 4d", *seq) if *seq == 1 { return } (*cnt)++ if *seq&1 != 0 { *seq = 3*(*seq) + 1 } else { *seq /= 2 ...
package require Tcl 8.5 for {set i 1} {$i <= 12} {incr i} { dict set hailenv hail$i [dict create num $i steps 0] } while 1 { set loopagain false foreach k [dict keys $hailenv] { dict with hailenv $k { puts -nonewline [format %4d $num] if {$num == 1} { continue } elseif {$num & 1} { set ...
Generate an equivalent Tcl version of this Go code.
type dlNode struct { int next, prev *dlNode } type dlList struct { members map[*dlNode]int head, tail **dlNode }
package require Tcl 8.4 proc dl {_name cmd {where error} {value ""}} { upvar 1 $_name N switch -- $cmd { insert { if ![info exists N()] {set N() {"" "" 0}} set id [lindex $N() 2] lset N() 2 [incr id] switch -- $where { head { ...
Rewrite the snippet below in Tcl so it works the same as the original Go code.
package main import ( "bufio" "errors" "fmt" "go/ast" "go/parser" "go/token" "os" "reflect" ) func main() { in := bufio.NewScanner(os.Stdin) for { fmt.Print("Expr: ") in.Scan() if err := in.Err(); err != nil { fmt.Println(err) re...
package require Tcl 8.5 puts -nonewline "Enter a boolean expression: " flush stdout set exp [gets stdin] set vars [lsort -unique [regexp -inline -all {\$\w+} $exp]] set cmd [list format [string repeat "%s\t" [llength $vars]]%s] append cmd " {*}\[[list subst $vars]\] \[[list expr $exp]\]" set cmd "puts \[$cmd\]" fore...
Change the programming language of this snippet from Go to Tcl without modifying what it does.
package main import ( "bufio" "errors" "fmt" "go/ast" "go/parser" "go/token" "os" "reflect" ) func main() { in := bufio.NewScanner(os.Stdin) for { fmt.Print("Expr: ") in.Scan() if err := in.Err(); err != nil { fmt.Println(err) re...
package require Tcl 8.5 puts -nonewline "Enter a boolean expression: " flush stdout set exp [gets stdin] set vars [lsort -unique [regexp -inline -all {\$\w+} $exp]] set cmd [list format [string repeat "%s\t" [llength $vars]]%s] append cmd " {*}\[[list subst $vars]\] \[[list expr $exp]\]" set cmd "puts \[$cmd\]" fore...
Convert this Go block to Tcl, preserving its control flow and logic.
package main import "fmt" type Set func(float64) bool func Union(a, b Set) Set { return func(x float64) bool { return a(x) || b(x) } } func Inter(a, b Set) Set { return func(x float64) bool { return a(x) && b(x) } } func Diff(a, b Set) Set { return func(x float64) bool { return a(x) && !b(x) } } func...
package require Tcl 8.5 proc inRange {x range} { lassign $range a aClosed b bClosed expr {($aClosed ? $a<=$x : $a<$x) && ($bClosed ? $x<=$b : $x<$b)} } proc normalize {A} { set A [lsort -index 0 -real [lsort -index 1 -integer -decreasing $A]] for {set i 0} {$i < [llength $A]} {incr i} { lassign [linde...
Ensure the translated Tcl code behaves exactly like the original Go snippet.
package main import "fmt" type Set func(float64) bool func Union(a, b Set) Set { return func(x float64) bool { return a(x) || b(x) } } func Inter(a, b Set) Set { return func(x float64) bool { return a(x) && b(x) } } func Diff(a, b Set) Set { return func(x float64) bool { return a(x) && !b(x) } } func...
package require Tcl 8.5 proc inRange {x range} { lassign $range a aClosed b bClosed expr {($aClosed ? $a<=$x : $a<$x) && ($bClosed ? $x<=$b : $x<$b)} } proc normalize {A} { set A [lsort -index 0 -real [lsort -index 1 -integer -decreasing $A]] for {set i 0} {$i < [llength $A]} {incr i} { lassign [linde...
Transform the following Go implementation into Tcl, maintaining the same output and logic.
package main import ( "fmt" "unicode" ) var states = []string{"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland",...
package require Tcl 8.5 proc goedel s { set primes { 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 } set n 1 foreach c [split [string toupper $s] ""] { if {![string is alpha $c]} continue set n [expr {$n * [lindex $primes [expr {[scan $c %c] - 65}]]}] } return $...
Rewrite the snippet below in Tcl so it works the same as the original Go code.
package main import ( "bufio" "flag" "fmt" "io" "log" "os" "strings" "unicode" ) func main() { log.SetFlags(0) log.SetPrefix("textonyms: ") wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } t ...
set keymap { 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -> WXYZ } set url http://www.puzzlers.org/pub/wordlists/unixdict.txt set report { There are %1$s words in %2$s which can be represented by the digit key mapping. They require %3$s digit combinations to rep...
Keep all operations the same but rewrite the snippet in Tcl.
package main import ( "bufio" "fmt" "math" "math/rand" "os" "strconv" "strings" "time" ) type cell struct { isMine bool display byte } const lMargin = 4 var ( grid [][]cell mineCount int minesMarked int isGameOver bool ) var scanner = bufio.NewSca...
package require Tcl 8.5 fconfigure stdout -buffering none proc makeGrid {n m} { global grid mine unset -nocomplain grid mine set grid(size) [list $n $m] set grid(shown) 0 set grid(marked) 0 for {set j 1} {$j <= $m} {incr j} { for {set i 1} {$i <= $n} {incr i} { set grid($i,$j) . } }...
Transform the following Go implementation into Tcl, maintaining the same output and logic.
package main import ( "fmt" "image" "reflect" ) type t int func (r t) Twice() t { return r * 2 } func (r t) Half() t { return r / 2 } func (r t) Less(r2 t) bool { return r < r2 } func (r t) privateMethod() {} func main() { report(t(0)) report(image.Point{}) } func report(x interface{}) { v := ...
% info object methods ::oo::class -all -private <cloned> create createWithNamespace destroy eval new unknown variable varname
Port the following code from Go to Tcl with equivalent syntax and logic.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func main() { var e example m := reflect.ValueOf(e).MethodByName("Foo") r := m.Call(nil) fmt.Println(r[0].Int()) }
package require Tcl 8.6 oo::class create Example { method foo {} {return 42} method 1 {s} {puts "fee$s"} method 2 {s} {puts "fie$s"} method 3 {s} {puts "foe$s"} method 4 {s} {puts "fum$s"} } set eg [Example new] set mthd [format "%c%c%c" 102 111 111]; puts [$eg $mthd] for {set i 1} {$i <= 4} {in...
Convert this Go block to Tcl, preserving its control flow and logic.
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _,...
package require ripemd160 package require sha256 proc base58encode data { set digits "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" for {set zeroes 0} {[string index $data 0] eq "\x00"} {incr zeroes} { set data [string range $data 1 end] } binary scan $data "H*" hex scan $hex "%llx"...
Port the provided Go code into Tcl while preserving the original functionality.
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _,...
package require ripemd160 package require sha256 proc base58encode data { set digits "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" for {set zeroes 0} {[string index $data 0] eq "\x00"} {incr zeroes} { set data [string range $data 1 end] } binary scan $data "H*" hex scan $hex "%llx"...
Change the programming language of this snippet from Go to Tcl without modifying what it does.
package main import ( "fmt" "math/big" ) func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10; n ...
proc tcl::mathfunc::P {n k} { set t 1 for {set i $n} {$i > $n-$k} {incr i -1} { set t [expr {$t * $i}] } return $t } proc tcl::mathfunc::C {n k} { set t [P $n $k] for {set i $k} {$i > 1} {incr i -1} { set t [expr {$t / $i}] } return $t } package require math proc tcl::mathfunc::lnGa...
Produce a language-to-language conversion: from Go to Tcl, same semantics.
package main import ( "fmt" "math/big" ) func main() { one := big.NewFloat(1) two := big.NewFloat(2) four := big.NewFloat(4) prec := uint(768) a := big.NewFloat(1).SetPrec(prec) g := new(big.Float).SetPrec(prec) t := new(big.Float).SetPrec(prec) u := new(big.Float).SetP...
package require math::bigfloat namespace import math::bigfloat::* proc agm/π {N {precision 8192}} { set 1 [int2float 1 $precision] set 2 [int2float 2 $precision] set n 1 set a $1 set g [div $1 [sqrt $2]] set z [div $1 [int2float 4 $precision]] for {set i 0} {$i <= $N} {incr i} { set x0 [di...
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func main() { one := big.NewFloat(1) two := big.NewFloat(2) four := big.NewFloat(4) prec := uint(768) a := big.NewFloat(1).SetPrec(prec) g := new(big.Float).SetPrec(prec) t := new(big.Float).SetPrec(prec) u := new(big.Float).SetP...
package require math::bigfloat namespace import math::bigfloat::* proc agm/π {N {precision 8192}} { set 1 [int2float 1 $precision] set 2 [int2float 2 $precision] set n 1 set a $1 set g [div $1 [sqrt $2]] set z [div $1 [int2float 4 $precision]] for {set i 0} {$i <= $N} {incr i} { set x0 [di...
Convert this Go block to Tcl, preserving its control flow and logic.
package main import ( "log" "github.com/jezek/xgb" "github.com/jezek/xgb/xproto" ) func main() { X, err := xgb.NewConn() if err != nil { log.Fatal(err) } points := []xproto.Point{ {10, 10}, {10, 20}, {20, 10}, {20, 20}}; ...
package provide xlib 1 package require critcl critcl::clibraries -L/usr/X11/lib -lX11 critcl::ccode { static Display *d; static GC gc; } critcl::cproc XOpenDisplay {Tcl_Interp* interp char* name} ok { d = XOpenDisplay(name[0] ? name : NULL); if (d == NULL) { Tcl_AppendResult(interp, "cannot ope...
Can you help me rewrite this code in Tcl instead of Go, keeping it the same logically?
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and f...
set today [clock format [clock seconds] -format %Y-%m-%d ] proc main [list birthday [list target $today]] { set day [days-between $birthday $target] array set cycles { Physical {23 red} Emotional {28 green} Mental {33 blue} } set pi [expr atan2(0,-1)] canvas .c -width 306 -height 350 -bg...
Ensure the translated Tcl code behaves exactly like the original Go snippet.
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and f...
set today [clock format [clock seconds] -format %Y-%m-%d ] proc main [list birthday [list target $today]] { set day [days-between $birthday $target] array set cycles { Physical {23 red} Emotional {28 green} Mental {33 blue} } set pi [expr atan2(0,-1)] canvas .c -width 306 -height 350 -bg...
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import ( "fmt" "math/big" "strings" ) var zero = new(big.Int) var one = big.NewInt(1) func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat { if br.Num().Cmp(zero) == 0 { return fracs } iquo := new(big.Int) irem := new(big.Int) iquo.QuoRem(br.Denom(),...
proc egyptian {num denom} { set result {} while {$num} { set term [expr {$denom / $num + ($denom/$num*$num < $denom)}] lappend result $term set num [expr {-$denom % $num}] set denom [expr {$denom * $term}] } return $result }
Change the programming language of this snippet from Go to Tcl without modifying what it does.
package main import ( "fmt" "math/big" "strings" ) var zero = new(big.Int) var one = big.NewInt(1) func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat { if br.Num().Cmp(zero) == 0 { return fracs } iquo := new(big.Int) irem := new(big.Int) iquo.QuoRem(br.Denom(),...
proc egyptian {num denom} { set result {} while {$num} { set term [expr {$denom / $num + ($denom/$num*$num < $denom)}] lappend result $term set num [expr {-$denom % $num}] set denom [expr {$denom * $term}] } return $result }
Preserve the algorithm and functionality while converting the code from Go to Tcl.
package main import ( "fmt" "math" ) type cFunc func(float64) float64 func main() { fmt.Println("integral:", glq(math.Exp, -3, 3, 5)) } func glq(f cFunc, a, b float64, n int) float64 { x, w := glqNodes(n, f) show := func(label string, vs []float64) { fmt.Printf("%8s: ", label) ...
package require Tcl 8.5 package require math::special package require math::polynomials package require math::constants math::constants::constants pi proc guess {n i} { global pi expr { cos($pi * ($i - 0.25) / ($n + 0.5)) } } proc legpoly {n x} { math::polynomials::evalPolyn [math::special::legendre $n]...
Translate the given Go code snippet into Tcl without altering its behavior.
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt poi...
package require TclOO oo::class create KDTree { variable t dim constructor {points} { set t [my Build 0 $points 0 end] set dim [llength [lindex $points 0]] } method Build {split exset from to} { set exset [lsort -index $split -real [lrange $exset $from $to]] if {![llength $exset]} {return 0} set m...
Produce a functionally identical Tcl code for the snippet given in Go.
package main import ( "fmt" "math" "math/rand" "sort" "time" ) type point []float64 func (p point) sqd(q point) float64 { var sum float64 for dim, pCoord := range p { d := pCoord - q[dim] sum += d * d } return sum } type kdNode struct { domElt poi...
package require TclOO oo::class create KDTree { variable t dim constructor {points} { set t [my Build 0 $points 0 end] set dim [llength [lindex $points 0]] } method Build {split exset from to} { set exset [lsort -index $split -real [lrange $exset $from $to]] if {![llength $exset]} {return 0} set m...
Write the same algorithm in Tcl as shown in this Go implementation.
package main import ( "container/heap" "image" "image/color" "image/png" "log" "math" "os" "sort" ) func main() { f, err := os.Open("Quantum_frog.png") if err != nil { log.Fatal(err) } img, err := png.Decode(f) if ec := f.Close(); err != nil { log.Fa...
package require Tcl 8.6 package require Tk proc makeCluster {pixels} { set rmin [set rmax [lindex $pixels 0 0]] set gmin [set gmax [lindex $pixels 0 1]] set bmin [set bmax [lindex $pixels 0 2]] set rsum [set gsum [set bsum 0]] foreach p $pixels { lassign $p r g b if {$r<$rmin} {set rmin $r} elsei...
Generate an equivalent Tcl version of this Go code.
package main import "fmt" var grid []byte var w, h, last int var cnt int var next [4]int var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func walk(y, x int) { if y == 0 || y == h || x == 0 || x == w { cnt += 2 return } t := y*(w+1) + x grid[t]++ grid[last-t]++ for i, d :...
package require Tcl 8.5 proc walk {y x} { global w ww h cnt grid len if {!$y || $y==$h || !$x || $x==$w} { incr cnt 2 return } set t [expr {$y*$ww + $x}] set m [expr {$len - $t}] lset grid $t [expr {[lindex $grid $t] + 1}] lset grid $m [expr {[lindex $grid $m] + 1}] if {![lindex $grid...
Produce a language-to-language conversion: from Go to Tcl, same semantics.
package main import "fmt" var grid []byte var w, h, last int var cnt int var next [4]int var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} func walk(y, x int) { if y == 0 || y == h || x == 0 || x == w { cnt += 2 return } t := y*(w+1) + x grid[t]++ grid[last-t]++ for i, d :...
package require Tcl 8.5 proc walk {y x} { global w ww h cnt grid len if {!$y || $y==$h || !$x || $x==$w} { incr cnt 2 return } set t [expr {$y*$ww + $x}] set m [expr {$len - $t}] lset grid $t [expr {[lindex $grid $t] + 1}] lset grid $m [expr {[lindex $grid $m] + 1}] if {![lindex $grid...
Preserve the algorithm and functionality while converting the code from Go to Tcl.
package main import ( "fmt" "sort" "strconv" ) var games = [6]string{"12", "13", "14", "23", "24", "34"} var results = "000000" func nextResult() bool { if results == "222222" { return false } res, _ := strconv.ParseUint(results, 3, 32) results = fmt.Sprintf("%06s", strconv.Format...
package require Tcl 8.6 proc groupStage {} { foreach n {0 1 2 3} { set points($n) {0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0} } set results 0 set games {0 1 0 2 0 3 1 2 1 3 2 3} while true { set R {0 0 1 0 2 0 3 0} foreach r [split [format %06d $results] ""] {A B} $games { switch $r { 2 {dic...
Rewrite the snippet below in Tcl so it works the same as the original Go code.
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) f...
package require Tcl 8.5 proc tokenize {str} { regexp -all -inline {[\d.]+|[-*^+/()]} $str } proc precedence op { dict get {^ 4 * 3 / 3 + 2 - 2} $op } proc associativity op { if {$op eq "^"} {return "right"} else {return "left"} } proc shunting {expression} { set stack {} foreach token [tokenize $...
Keep all operations the same but rewrite the snippet in Tcl.
package main import ( "fmt" "math" ) func main() { fmt.Println(noise(3.14, 42, 7)) } func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(z) u := fa...
namespace eval perlin { proc noise {x y z} { set X [expr {int(floor($x)) & 255}] set Y [expr {int(floor($y)) & 255}] set Z [expr {int(floor($z)) & 255}] set x [expr {$x - floor($x)}] set y [expr {$y - floor($y)}] set z [expr {$z - floor($z)}] set u [expr {fade($x)}] set v [expr {fade($y)}] set w [e...
Port the provided Go code into Tcl while preserving the original functionality.
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
proc pal? {n} { expr {$n eq [string reverse $n]} } proc step {n} { set n_ [string reverse $n] set n_ [string trimleft $n_ 0] expr {$n + $n_} } proc lychrels {{max 10000} {iters 500}} { set lychrels {} ; set visited {} ; set nRelated 0 ; set pals {} ; puts "S...
Transform the following Go implementation into Tcl, maintaining the same output and logic.
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
proc pal? {n} { expr {$n eq [string reverse $n]} } proc step {n} { set n_ [string reverse $n] set n_ [string trimleft $n_ 0] expr {$n + $n_} } proc lychrels {{max 10000} {iters 500}} { set lychrels {} ; set visited {} ; set nRelated 0 ; set pals {} ; puts "S...
Maintain the same structure and functionality when rewriting this code in Tcl.
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
package require Tcl 8.5 proc tadd {p q} { lassign $p pp pq lassign $q qp qq set topp [expr {$pp*$qq + $qp*$pq}] set topq [expr {$pq*$qq}] set prodp [expr {$pp*$qp}] set prodq [expr {$pq*$qq}] set lowp [expr {$prodq - $prodp}] set resultp [set gcd1 [expr {$topp * $prodq}]] set resul...
Transform the following Go implementation into Tcl, maintaining the same output and logic.
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
package require Tcl 8.5 proc tadd {p q} { lassign $p pp pq lassign $q qp qq set topp [expr {$pp*$qq + $qp*$pq}] set topq [expr {$pq*$qq}] set prodp [expr {$pp*$qp}] set prodq [expr {$pq*$qq}] set lowp [expr {$prodq - $prodp}] set resultp [set gcd1 [expr {$topp * $prodq}]] set resul...
Change the programming language of this snippet from Go to Tcl without modifying what it does.
package main import ( "fmt" "math" "regexp" "strings" ) var names = map[string]int64{ "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": ...
package require Tcl 8.6 proc name2num name { set words [regexp -all -inline {[a-z]+} [string tolower $name]] set tokens { "zero" 0 "one" 1 "two" 2 "three" 3 "four" 4 "five" 5 "six" 6 "seven" 7 "eight" 8 "nine" 9 "ten" 10 "eleven" 11 "twelve" 12 "thirteen" 13 "fourteen" 14 "fifteen" 15 "sixteen" 16 "seventeen...
Generate an equivalent Tcl version of this Go code.
package main import "fmt" type Number struct { pred *Number } type EvenNumber struct { half *Number } type OddNumber struct { half *Number } func zero() *Number { return nil } func isZero(x *Number) bool { return x == nil } func add1(x *Number) *Number { y := new(Number) y.pred = x ...
package require datatype datatype define Int = Zero | Succ val datatype define EO = Even | Odd proc evenOdd val { global environment datatype match $val { case Zero -> { Even } case [Succ [Succ x]] -> { evenOdd $x } case t -> { set term [list evenOdd $t] if {[info exists environment($term)]} { ...
Rewrite the snippet below in Tcl so it works the same as the original Go code.
package main import "fmt" type Number struct { pred *Number } type EvenNumber struct { half *Number } type OddNumber struct { half *Number } func zero() *Number { return nil } func isZero(x *Number) bool { return x == nil } func add1(x *Number) *Number { y := new(Number) y.pred = x ...
package require datatype datatype define Int = Zero | Succ val datatype define EO = Even | Odd proc evenOdd val { global environment datatype match $val { case Zero -> { Even } case [Succ [Succ x]] -> { evenOdd $x } case t -> { set term [list evenOdd $t] if {[info exists environment($term)]} { ...
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import "fmt" const ( msg = "a Top Secret secret" key = "this is my secret key" ) func main() { var z state z.seed(key) fmt.Println("Message: ", msg) fmt.Println("Key  : ", key) fmt.Println("XOR  : ", z.vernam(msg)) } type state struct { aa, bb, cc uint32 mm ...
package require Tcl 8.6 oo::class create ISAAC { variable aa bb cc mm randrsl randcnt constructor {seed} { namespace eval tcl { namespace eval mathfunc { proc mm {idx} { upvar 1 mm list lindex $list [expr {$idx % [llength $list]}] } proc clamp {value} { expr {$value & 0xFFFFFFFF}...
Translate the given Go code snippet into Tcl without altering its behavior.
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } ...
proc swap {v idx1 idx2} { lset v $idx2 [lindex $v $idx1][lset v $idx1 [lindex $v $idx2];subst ""] } proc computePermutation {vecName rank} { upvar 1 $vecName vec if {![info exist vec] || ![llength $vec]} return set N [llength $vec] for {set n 0} {$n < $N} {incr n} {lset vec $n $n} for {set n ...
Change the programming language of this snippet from Go to Tcl without modifying what it does.
package main import ( "fmt" "math/rand" ) func MRPerm(q, n int) []int { p := ident(n) var r int for n > 0 { q, r = q/n, q%n n-- p[n], p[r] = p[r], p[n] } return p } func ident(n int) []int { p := make([]int, n) for i := range p { p[i] = i } ...
proc swap {v idx1 idx2} { lset v $idx2 [lindex $v $idx1][lset v $idx1 [lindex $v $idx2];subst ""] } proc computePermutation {vecName rank} { upvar 1 $vecName vec if {![info exist vec] || ![llength $vec]} return set N [llength $vec] for {set n 0} {$n < $N} {incr n} {lset vec $n $n} for {set n ...
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64...
proc S2 {n k} { set nk [list $n $k] if {[info exists ::S2cache($nk)]} { return $::S2cache($nk) } if {($n > 0 && $k == 0) || ($n == 0 && $k > 0)} { return 0 } if {$n == $k} { return 1 } if {$n < $k} { return 0 } set n1 [expr {$n - 1}] set k...
Rewrite the snippet below in Tcl so it works the same as the original Go code.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64...
proc S2 {n k} { set nk [list $n $k] if {[info exists ::S2cache($nk)]} { return $::S2cache($nk) } if {($n > 0 && $k == 0) || ($n == 0 && $k > 0)} { return 0 } if {$n == $k} { return 1 } if {$n < $k} { return 0 } set n1 [expr {$n - 1}] set k...
Ensure the translated Tcl code behaves exactly like the original Go snippet.
package main import ( "fmt" "strings" ) var ( dig = [3]string{"00", "01", "10"} dig1 = [3]string{"", "1", "10"} ) type Zeckendorf struct{ dVal, dLen int } func NewZeck(x string) *Zeckendorf { z := new(Zeckendorf) if x == "" { x = "0" } q := 1 i := len(x) - 1 z.dLen =...
namespace eval zeckendorf { variable zero "0" variable one "1" proc zincr var { upvar 1 $var a namespace upvar [namespace current] zero 0 one 1 if {![regsub "$0$" $a $1$0 a]} {append a $1} while {[regsub "$0$1$1" $a "$1$0$0" a] || [regsub "^$1$1" $a "$1$0$0" a]} {} regsub ".$" $a "" a ret...
Change the programming language of this snippet from Go to Tcl without modifying what it does.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } ...
proc US1 {n k} { if {$k == 0} { return [expr {$n == 0}] } if {$n < $k} { return 0 } if {$n == $k} { return 1 } set nk [list $n $k] if {[info exists ::US1cache($nk)]} { return $::US1cache($nk) } set n1 [expr {$n - 1}] set k1 [expr {$k - 1}...
Transform the following Go implementation into Tcl, maintaining the same output and logic.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } ...
proc US1 {n k} { if {$k == 0} { return [expr {$n == 0}] } if {$n < $k} { return 0 } if {$n == $k} { return 1 } set nk [list $n $k] if {[info exists ::US1cache($nk)]} { return $::US1cache($nk) } set n1 [expr {$n - 1}] set k1 [expr {$k - 1}...
Maintain the same structure and functionality when rewriting this code in Tcl.
package main import ( "image" "image/color" "image/jpeg" "log" "math" "os" "golang.org/x/image/draw" ) func scale(dst draw.Image, src image.Image) { sr := src.Bounds() dr := dst.Bounds() mx := float64(sr.Dx()-1) / float64(dr.Dx()) my := float64(sr.Dy()-1) / float64(dr.Dy()) for x := dr.Min.X; x < dr.Max....
package require Tk proc pixel {f} { if {$f < 0} { error "why is $f?" } set i [expr {0xff & entier(0xff*$f)}] format } proc bilerp {im O X Y XY} { set w [image width $im] set h [image height $im] set dx [expr {1.0/$w}] set dy [expr {1.0/$h}] set a0 $O set a1 [expr {$X -...
Change the programming language of this snippet from Go to Tcl without modifying what it does.
package main import ( "image" "image/color" "image/jpeg" "log" "math" "os" "golang.org/x/image/draw" ) func scale(dst draw.Image, src image.Image) { sr := src.Bounds() dr := dst.Bounds() mx := float64(sr.Dx()-1) / float64(dr.Dx()) my := float64(sr.Dy()-1) / float64(dr.Dy()) for x := dr.Min.X; x < dr.Max....
package require Tk proc pixel {f} { if {$f < 0} { error "why is $f?" } set i [expr {0xff & entier(0xff*$f)}] format } proc bilerp {im O X Y XY} { set w [image width $im] set h [image height $im] set dx [expr {1.0/$w}] set dy [expr {1.0/$h}] set a0 $O set a1 [expr {$X -...
Produce a functionally identical Tcl code for the snippet given in Go.
package main import "fmt" type vector []float64 func (v vector) add(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi + v2[i] } return r } func (v vector) sub(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi - v...
namespace path ::tcl::mathop proc vec {op a b} { if {[llength $a] == 1 && [llength $b] == 1} { $op $a $b } elseif {[llength $a]==1} { lmap i $b {vec $op $a $i} } elseif {[llength $b]==1} { lmap i $a {vec $op $i $b} } elseif {[llength $a] == [llength $b]} { lmap i $a j $b ...
Convert this Go block to Tcl, preserving its control flow and logic.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { r...
set C 7 set zero {x inf y inf} proc tcl::mathfunc::cuberoot n { expr {$n>=0 ? $n**(1./3) : -((-$n)**(1./3))} } proc iszero p { dict with p {} return [expr {$x > 1e20 || $x<-1e20}] } proc negate p { dict set p y [expr {-[dict get $p y]}] } proc double p { if {[iszero $p]} {return $p} dict wi...
Ensure the translated Tcl code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" ) const bCoeff = 7 type pt struct{ x, y float64 } func zero() pt { return pt{math.Inf(1), math.Inf(1)} } func is_zero(p pt) bool { return p.x > 1e20 || p.x < -1e20 } func neg(p pt) pt { return pt{p.x, -p.y} } func dbl(p pt) pt { if is_zero(p) { r...
set C 7 set zero {x inf y inf} proc tcl::mathfunc::cuberoot n { expr {$n>=0 ? $n**(1./3) : -((-$n)**(1./3))} } proc iszero p { dict with p {} return [expr {$x > 1e20 || $x<-1e20}] } proc negate p { dict set p y [expr {-[dict get $p y]}] } proc double p { if {[iszero $p]} {return $p} dict wi...
Maintain the same structure and functionality when rewriting this code in Tcl.
package main import ( "fmt" "math/rand" "time" ) func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func riffle(deck []int, iterations int) []int { le := len(deck) pile := make([]int, le) copy(pile, deck) for i := 0; i < i...
proc riffle deck { set length [llength $deck] for {set i 0} {$i < $length/2} { incr i} { lappend temp [lindex $deck $i] [lindex $deck [expr {$length/2+$i}]]} set temp} proc overhand deck { set cut [expr {[llength $deck] /5}] for {set i $cut} {$i >-1} {incr i -1} { lappend temp [lrange $deck [expr {$i *$cut}] [...
Maintain the same structure and functionality when rewriting this code in Tcl.
package main import ( "fmt" "math/rand" "time" ) func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } } func riffle(deck []int, iterations int) []int { le := len(deck) pile := make([]int, le) copy(pile, deck) for i := 0; i < i...
proc riffle deck { set length [llength $deck] for {set i 0} {$i < $length/2} { incr i} { lappend temp [lindex $deck $i] [lindex $deck [expr {$length/2+$i}]]} set temp} proc overhand deck { set cut [expr {[llength $deck] /5}] for {set i $cut} {$i >-1} {incr i -1} { lappend temp [lrange $deck [expr {$i *$cut}] [...
Convert this Go block to Tcl, preserving its control flow and logic.
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
package require Tcl 8.5 set maxN 200 set rooted [lrepeat $maxN 0] lset rooted 0 1; lset rooted 1 1 set unrooted $rooted proc choose {m k} { if {$k == 1} { return $m } for {set r $m; set i 1} {$i < $k} {incr i} { set r [expr {$r * ($m+$i) / ($i+1)}] } return $r } proc tree {br n cnt sum l} { ...
Ensure the translated Tcl code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
package require Tcl 8.5 set maxN 200 set rooted [lrepeat $maxN 0] lset rooted 0 1; lset rooted 1 1 set unrooted $rooted proc choose {m k} { if {$k == 1} { return $m } for {set r $m; set i 1} {$i < $k} {incr i} { set r [expr {$r * ($m+$i) / ($i+1)}] } return $r } proc tree {br n cnt sum l} { ...
Change the following Go code into Tcl without altering its purpose.
package main import ( "fmt" "strings" ) type pair struct{ first, second string } var ( fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}} lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND"...
proc nysiis {name {truncate false}} { set name [regsub -all {[^A-Z]+} [string toupper [regexp -inline {\S+} $name]] ""] foreach {from to} {MAC MCC KN N K C PH FF PF FF SCH SSS} { if {[regsub ^$from $name $to name]} break } foreach {from to} {EE Y IE Y DT D RT D NT D ND D} { if {[regsub ...
Write the same algorithm in Tcl as shown in this Go implementation.
package main import ( "fmt" "strings" ) type pair struct{ first, second string } var ( fStrs = []pair{{"MAC", "MCC"}, {"KN", "N"}, {"K", "C"}, {"PH", "FF"}, {"PF", "FF"}, {"SCH", "SSS"}} lStrs = []pair{{"EE", "Y"}, {"IE", "Y"}, {"DT", "D"}, {"RT", "D"}, {"RD", "D"}, {"NT", "D"}, {"ND"...
proc nysiis {name {truncate false}} { set name [regsub -all {[^A-Z]+} [string toupper [regexp -inline {\S+} $name]] ""] foreach {from to} {MAC MCC KN N K C PH FF PF FF SCH SSS} { if {[regsub ^$from $name $to name]} break } foreach {from to} {EE Y IE Y DT D RT D NT D ND D} { if {[regsub ...
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import ( "log" "github.com/jtblin/go-ldap-client" ) func main() { client := &ldap.LDAPClient{ Base: "dc=example,dc=com", Host: "ldap.example.com", Port: 389, GroupFilter: "(memberUid=%s)", } defer client.Close() err := client.Co...
set Username "TestUser" set Filter "((&objectClass=*)(sAMAccountName=$Username))" set Base "dc=skycityauckland,dc=sceg,dc=com" set Attrs distinguishedName
Preserve the algorithm and functionality while converting the code from Go to Tcl.
package main import "fmt" const n = 64 func pow2(x uint) uint64 { return uint64(1) << x } func evolve(state uint64, rule int) { for p := 0; p < 10; p++ { b := uint64(0) for q := 7; q >= 0; q-- { st := state b |= (st & 1) << uint(q) state = 0 fo...
oo::class create RandomGenerator { superclass ElementaryAutomaton variable s constructor {stateLength} { next 30 set s [split 1[string repeat 0 $stateLength] ""] } method rand {} { set bits {} while {[llength $bits] < 8} { lappend bits [lindex $s 0] set s [my evolve $s] } return [sc...
Transform the following Go implementation into Tcl, maintaining the same output and logic.
package main import ( "fmt" "log" "os" "strconv" "strings" ) const luckySize = 60000 var luckyOdd = make([]int, luckySize) var luckyEven = make([]int, luckySize) func init() { for i := 0; i < luckySize; i++ { luckyOdd[i] = i*2 + 1 luckyEven[i] = i*2 + 2 } } func filterLu...
package require Tcl 8.6 proc lgen {{even false} {nmax 200000}} { coroutine lgen.[incr ::lgen] apply {{start nmax} { set n 1 for {set i $start} {$i <= $nmax+1} {incr i 2} {lappend lst $i} yield [info coroutine] yield [lindex $lst 0] while {$n < [llength $lst] && [lindex $lst $n] < [llength $lst]} { yield...
Ensure the translated Tcl code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" "math/rand" "strings" ) func norm2() (s, c float64) { r := math.Sqrt(-2 * math.Log(rand.Float64())) s, c = math.Sincos(2 * math.Pi * rand.Float64()) return s * r, c * r } func main() { const ( n = 10000 bins = 12 sig =...
package require Tcl 8.5 proc tcl::mathfunc::nrand {mean stddev} { variable savednormalrandom if {[info exists savednormalrandom]} { return [expr {$savednormalrandom*$stddev + $mean}][unset savednormalrandom] } set r [expr {sqrt(-2*log(rand()))}] set theta [expr {2*3.1415927*rand()}] set savedn...
Translate the given Go code snippet into Tcl without altering its behavior.
#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define N_ROWS 5 #define N_COLS 5 typedef int bool; int supply[N_ROWS] = { 461, 277, 356, 488, 393 }; int demand[N_COLS] = { 278, 60, 461, 116, 1060 }; int costs[N_ROWS][N_COLS] = { { 46, 74, 9, 28, 99 }, { 12, 75, 6, 36, 48 }, ...
package require Tcl 8.6 proc sortByFunction {list lambda} { lmap k [lsort -index 1 [lmap k $list { list $k [uplevel 1 [list apply $lambda $k]] }]] {lindex $k 0} } proc minimax {list maxidx minidx} { set max -Inf; set min Inf foreach t $list { if {[set m [lindex $t $maxidx]] > $max} { set best...
Write a version of this Go function in Tcl with identical behavior.
package main import ( "fmt" "github.com/shabbyrobe/go-num" "strings" "time" ) func b10(n int64) { if n == 1 { fmt.Printf("%4d: %28s  %-24d\n", 1, "1", 1) return } n1 := n + 1 pow := make([]int64, n1) val := make([]int64, n1) var count, ten, x int64 = 0, 1, 1 ...
package require Tcl 8.5 proc potmod {expo modval} { if {$expo < 0} { return 0 } if {$modval < 2} { return 0 } ; set r 1 set p [expr {10 % $modval}] while {$expo} { set half [expr {$expo / 2}] set odd [expr {$expo % 2}] if {$expo % 2} { set r [ex...
Can you help me rewrite this code in Tcl instead of Go, keeping it the same logically?
package main import ( "fmt" "log" "math/big" "strings" ) type result struct { name string size int start int end int } func (r result) String() string { return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end) } func validate(diagram string) []string { ...
namespace eval asciipacket { proc assert {expr} { ; if {![uplevel 1 [list expr $expr]]} { raise {ASSERT ERROR} "{$expr} {[subst -noc $expr]}" } } proc b2h {data} { ; binary scan $data H* hex; set hex } proc parse {s} { set result {} ...
Port the provided Go code into Tcl while preserving the original functionality.
package main import ( "fmt" "math" "os" ) type vector struct{ x, y, z float64 } func (v vector) add(w vector) vector { return vector{v.x + w.x, v.y + w.y, v.z + w.z} } func (v vector) sub(w vector) vector { return vector{v.x - w.x, v.y - w.y, v.z - w.z} } func (v vector) scale(m float64) vector...
package require Tcl 8.6 set G 0.01 set epsilon 1e-12 proc acceleration.gravity {positions masses} { global G epsilon set i -1 lmap position $positions mass $masses { incr i set dp2 [lmap p $position {expr 0.0}] set j -1 foreach pj $positions mj $masses { if {[incr j] == $i} continue set dp [...
Convert this Go snippet to Tcl and keep its semantics consistent.
package main import ( "fmt" "io/ioutil" "log" "strconv" "strings" ) type userInput struct{ formFeed, lineFeed, tab, space int } func getUserInput() []userInput { h := "0 18 0 0 0 68 0 1 0 100 0 32 0 114 0 45 0 38 0 26 0 16 0 21 0 17 0 59 0 11 " + "0 29 0 102 0 0 0 10 0 50 0 39 0 42 0 ...
package require Tcl 8.6 oo::class create JustInTimeStreamExtract { variable map counter counters last constructor {{pageSeparator "\f"} {lineSeparator "\n"} {fieldSeparator "\t"}} { dict set map $pageSeparator NextPage dict set map $lineSeparator NextLine dict set map $fieldSeparator NextField set counter ...
Change the following Go code into Tcl without altering its purpose.
package main import ( "fmt" "math/big" "math/rand" "time" ) type mont struct { n uint m *big.Int r2 *big.Int } func newMont(m *big.Int) *mont { if m.Bit(0) != 1 { return nil } n := uint(m.BitLen()) x := big.NewInt(1) x.Sub(x.Lsh(x, n), m) return ...
package require Tcl 8.5 proc montgomeryReduction {m mDash T n {b 2}} { set A $T for {set i 0} {$i < $n} {incr i} { for {set j 0;set a $A} {$j < $i} {incr j} { set a [expr {$a / $b}] } set ui [expr {($a % $b) * $mDash % $b}] incr A [expr {$ui * $m * $b**$i}] } set A [expr {$A / ($b ** $n)}] ...
Write the same code in Tcl as shown below in Go.
package main import ( "bufio" "fmt" "log" "os" "strings" ) type state int const ( ready state = iota waiting exit dispense refunding ) func check(err error) { if err != nil { log.Fatal(err) } } func fsm() { fmt.Println("Please enter your option when promp...
set fsm [dict create \ ready {deposit waiting quit exit} \ waiting {select dispense refund refunding} \ dispense {remove ready} \ refunding {{} ready} \ ] set state ready proc prompt {fsm state} { set choices [dict keys [dict get $fsm $state]] while {1} { puts -nonewline "state: $state, p...
Convert this Go block to Tcl, preserving its control flow and logic.
package main import ( "fmt" "strings" ) func main() { level := ` ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######` fmt.Printf("level:%s\n", level) fmt.Printf("solution:\n%s\n", solve(level)) } func solve(board string) string { buffer = make([]byte, len(board)) width ...
package require Tcl 8.5 proc solveSokoban b { set cols [string length [lindex $b 0]] set dxes [list [expr {-$cols}] $cols -1 1] set i 0 foreach c [split [join $b ""] ""] { switch $c { " " {lappend bdc " "} " "@" {lappend bdc " ";set startplayer $i } "$" {lappend bdc " ";lappend sta...
Preserve the algorithm and functionality while converting the code from Go to Tcl.
package main import ( "fmt" "image" "reflect" ) type t struct { X int next *t } func main() { report(t{}) report(image.Point{}) } func report(x interface{}) { t := reflect.TypeOf(x) n := t.NumField() fmt.Printf("Type %v has %d fields:\n", t, n) fmt.Println("Name Type Exported") for i := 0; i...
% package require Tk 8.6.5 % . configure {-bd -borderwidth} {-borderwidth borderWidth BorderWidth 0 0} {-class class Class Toplevel Tclsh} {-menu menu Menu {} {}} {-relief relief Relief flat flat} {-screen screen Screen {} {}} {-use use Use {} {}} {-background background Background {-container container Container 0...
Rewrite the snippet below in Tcl so it works the same as the original Go code.
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ...
package require TclOO oo::class create Playfair { variable grid lookup excluder constructor {{keyword "PLAYFAIR EXAMPLE"} {exclude "J"}} { if {$exclude eq "J"} { set excluder "J I" } else { set excluder [list $exclude ""] } set keys [m...
Preserve the algorithm and functionality while converting the code from Go to Tcl.
package main import ( "bufio" "fmt" "os" "strings" ) type playfairOption int const ( noQ playfairOption = iota iEqualsJ ) type playfair struct { keyword string pfo playfairOption table [5][5]byte } func (p *playfair) init() { var used [26]bool if p.pfo == noQ...
package require TclOO oo::class create Playfair { variable grid lookup excluder constructor {{keyword "PLAYFAIR EXAMPLE"} {exclude "J"}} { if {$exclude eq "J"} { set excluder "J I" } else { set excluder [list $exclude ""] } set keys [m...
Convert the following code from Go to Tcl, ensuring the logic remains intact.
package main import ( "fmt" "strings" ) func btoi(b bool) int { if b { return 1 } return 0 } func evolve(l, rule int) { fmt.Printf(" Rule #%d:\n", rule) cells := "O" for x := 0; x < l; x++ { cells = addNoCells(cells) width := 40 + (len(cells) >> 1) fmt....
package require Tcl 8.6 oo::class create InfiniteElementaryAutomaton { variable rules constructor {ruleNumber} { set ins {111 110 101 100 011 010 001 000} set bits [split [string range [format %08b $ruleNumber] end-7 end] ""] foreach input {111 110 101 100 011 010 001 000} state $bits { dict ...
Generate a Tcl translation of this Go snippet without changing its computational steps.
package romap type Romap struct{ imap map[byte]int } func New(m map[byte]int) *Romap { if m == nil { return nil } return &Romap{m} } func (rom *Romap) Get(key byte) (int, bool) { i, ok := rom.imap[key] return i, ok } func (rom *Romap) Reset(key byte) { _, ok := rom.imap[key] i...
proc protect _var { upvar 1 $_var var trace add variable var {write unset} [list protect0 $var] } proc protect0 {backup name1 name2 op} { upvar 1 $name1 var trace remove variable var {write unset} [list protect 0 $backup] set var $backup trace add variable var {write unset} [list protect0 $backu...
Translate this program into Tcl but keep the logic exactly as in Go.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "math" "math/rand" "os" "time" ) type r2 struct { x, y float64 } type r2c struct { r2 c int } func kmpp(k int, data []r2c) { kMeans(data, kmppSeeds(k, data)) } func kmppSeeds(k int, da...
package require Tcl 8.5 package require math::constants math::constants::constants pi proc tcl::mathfunc::randf m {expr {$m * rand()}} proc genXY {count radius} { global pi for {set i 0} {$i < $count} {incr i} { set ang [expr {randf(2 * $pi)}] set r [expr {randf($radius)}] lappend pt [list [expr {$r*cos($an...
Translate this program into Tcl but keep the logic exactly as in Go.
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" ...
package require Tcl 8.6 proc dec2bin x { binary scan [binary format R $x] B* x regexp {(.)(.{8})(.{23})} $x -> s e m binary scan [binary format B* $e] cu e if {$e == 0 && ![string match *1* $m]} { set m 0.0 } else { incr e -127 set m 1$m if {$e < 0} { set m [string repeat "0" [expr {-$e...
Preserve the algorithm and functionality while converting the code from Go to Tcl.
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" ...
package require Tcl 8.6 proc dec2bin x { binary scan [binary format R $x] B* x regexp {(.)(.{8})(.{23})} $x -> s e m binary scan [binary format B* $e] cu e if {$e == 0 && ![string match *1* $m]} { set m 0.0 } else { incr e -127 set m 1$m if {$e < 0} { set m [string repeat "0" [expr {-$e...
Generate an equivalent Tcl version of this Go code.
package main import ( "fmt" "regexp" "sort" "strconv" "strings" ) var tests = []struct { descr string list []string }{ {"Ignoring leading spaces", []string{ "ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ...
package require Tcl 8.5 proc sortWithCollationKey {keyBuilder list} { if {![llength $list]} return foreach value $list { lappend toSort [{*}$keyBuilder $value] } foreach idx [lsort -indices $toSort] { lappend result [lindex $list $idx] } return $result } proc normalizeSpaces {str} { regsu...
Change the following Go code into Tcl without altering its purpose.
package main import ( ed "github.com/Ernyoke/Imger/edgedetection" "github.com/Ernyoke/Imger/imgio" "log" ) func main() { img, err := imgio.ImreadRGBA("Valve_original_(1).png") if err != nil { log.Fatal("Could not read image", err) } cny, err := ed.CannyRGBA(img, 15, 45, 5) if ...
package require crimp package require crimp::pgm proc readPGM {filename} { set f [open $filename rb] set data [read $f] close $f return [crimp read pgm $data] } proc writePGM {filename image} { crimp write 2file pgm-raw $filename $image } proc cannyFilterFile {{inputFile "lena.pgm"} {outputFile "l...
Port the following code from Go to Tcl with equivalent syntax and logic.
package main import ( "fmt" "math" "math/cmplx" ) func fft(buf []complex128, n int) { out := make([]complex128, n) copy(out, buf) fft2(buf, out, n, 1) } func fft2(buf, out []complex128, n, step int) { if step < n { fft2(out, buf, n, step*2) fft2(out[step:], buf[step:], n, ...
package require Tcl 8.5 namespace path {::tcl::mathfunc ::tcl::mathop} proc rank m { for {set rank 0} {[llength $m] > 1} {incr rank} { set m [lindex $m 0] } return $rank } proc size m { set r [rank $m] set index {} set size {} for {set i 0} {$i<$r} {incr i} { lappend size [llength [lin...
Ensure the translated Tcl code behaves exactly like the original Go snippet.
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { fileName := "loop.wav" scanner := bufio.NewScanner(os.Stdin) reps := 0 for reps < 1 || reps > 6 { fmt.Print("En...
package require Tk package require snack set filename "sample.wav" set nreps 5 set delay 200 set decay 0.9 snack::sound wav -load sample.wav snack::sound mixed ; snack::sound out ; snack::sound hush -rate [wav cget -rate] -channels [wav cget -channels] hush length [wav length] proc make_gui {} { ...
Please provide an equivalent version of this Go code in Tcl.
package main import ( "bufio" "fmt" "log" "os" "os/exec" "strconv" ) func check(err error) { if err != nil { log.Fatal(err) } } func main() { fileName := "loop.wav" scanner := bufio.NewScanner(os.Stdin) reps := 0 for reps < 1 || reps > 6 { fmt.Print("En...
package require Tk package require snack set filename "sample.wav" set nreps 5 set delay 200 set decay 0.9 snack::sound wav -load sample.wav snack::sound mixed ; snack::sound out ; snack::sound hush -rate [wav cget -rate] -channels [wav cget -channels] hush length [wav length] proc make_gui {} { ...
Rewrite the snippet below in Tcl so it works the same as the original Go code.
package main import ( "fmt" "math/big" ) func div(dividend, divisor []*big.Rat) (quotient, remainder []*big.Rat) { out := make([]*big.Rat, len(dividend)) for i, c := range dividend { out[i] = new(big.Rat).Set(c) } for i := 0; i < len(dividend)-(len(divisor)-1); i++ { out[i].Quo...
proc range {a {b ""}} { if {$b eq ""} { set b $a set a 0 } for {set r {}} {$a<$b} {incr a} { lappend r $a } return $r } proc lincr {_ls args} { upvar 1 $_ls ls set incr [lindex $args end] set idxs [lrange $args 0 end-1] lset ls {*}$idxs [expr {$incr + [l...