Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: convert script from perl to tcl

by atcroft (Abbot)
on Aug 08, 2019 at 03:55 UTC ( [id://11104130]=note: print w/replies, xml ) Need Help??


in reply to convert script from perl to tcl

The problem I saw (from printing the values just after proc entry) was that $output was not being updated. Since I've only had to use TCL a few times (and consider myself still a beginner at it), I just did something that worked-I removed the output variable from the parameter list and used 'upvar #0 output outp' to access it as a global variable.

WARNING: If this is some form of homework, the use of a global variable may result in a low or failing grade.

TCL Code:

#!/usr/bin/tclsh # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: set output [ ] proc combinationSum { sum sofar want numbers } { upvar #0 output outp # puts "\t$sum | $sofar | $want | $numbers | $output" if { $sum == $want } { lappend outp $sofar return TRUE } else { if { ( $sum < $want ) && ( [ lindex $numbers 0 ] > 0 ) && ( [ llength $numbers ] > 0 ) } { combinationSum \ [ expr $sum + [ lindex $numbers 0 ] ] \ [ concat $sofar [ lindex $numbers 0 ] ] \ $want $numbers combinationSum $sum $sofar $want [ lrange $numbers 1 end ] } return TRUE } } set test_input [ list 2 3 5 ] set test_target 20 set test_output [ combinationSum 0 [] $test_target $test_input ] # puts "> $output" # puts [ llength $output ] foreach l $output { puts $l }

Verification:

Output from OP-provided perl script (target: 20; input: [ 2, 3, 5, ]):

$ ./11104071-perl.pl 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 2 2 2 2 2 2 3 5 2 2 2 2 2 5 5 2 2 2 2 3 3 3 3 2 2 2 3 3 3 5 2 2 3 3 5 5 2 3 3 3 3 3 3 2 3 5 5 5 3 3 3 3 3 5 5 5 5 5

Output from above TCL script (target: 20; input: [ 2, 3, 5, ]):

$ ./11104071-tcl.tcl 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 2 2 2 2 2 2 3 5 2 2 2 2 2 5 5 2 2 2 2 3 3 3 3 2 2 2 3 3 3 5 2 2 3 3 5 5 2 3 3 3 3 3 3 2 3 5 5 5 3 3 3 3 3 5 5 5 5 5

(As an aside, the lack of formatting made both pieces of code hard to follow (although other things may have my focus off tonight as well). I ran the perl code through Perltidy, and the TCL code through the code listed as "reformat2.tcl" here, but I still had to run it with different values to determine what your actual goal was (all combinations of @input that sum to $target).)

Hope that helps.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11104130]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2024-04-25 14:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found