Reputation: 5
Please suggest improvements to my program. This program gives a 4 bit binary incremental o/p I am looking for optimizing this where there is unnecessary code.
Please suggest improvements to my program. This program gives a 4 bit binary incremental o/p I am looking for optimizing this where there is unnecessary code. Please suggest improvements to my program. This program gives a 4 bit binary incremental o/p I am looking for optimizing this where there is unnecessary code.
#!/bin/sh
# This
puts "+++++++++++++++++\n"
set ipaddr "0.0.0.0"
set limit 4
set splitip [split $ipaddr "."]
puts "Split ip address = $splitip"
# MAIN ROUTINE
set ilength [llength $splitip]
puts "Length of string is $ilength"
set first [lindex $splitip 0]
set sec [lindex $splitip 1]
set third [lindex $splitip 2]
set four [lindex $splitip 3]
for { set limit 1} { $limit >0} {} {
for { set first $first } { $first <= $limit} {} {
for { set sec $sec } { $sec <= $limit} {} {
for { set third $third } { $third <= $limit} {} {
for { set four $four } { $four <= $limit} {} {
puts " f:$first $sec $third $four"
incr four
}
set four 0
incr third; #puts " t:$four $third $sec $first\n"
}
set third 0
incr sec
}
#puts " f:$four $third $sec $first"
set sec 0
incr first
}
incr limit -1
}
# End Main
puts "\n++++++End Program+++++++++++"
Upvotes: 0
Views: 62
Reputation: 13252
Your program essentially boils down to this, does this do what you intended?
for { set first 0 } { $first <= 1} {incr first} {
for { set sec 0 } { $sec <= 1} {incr sec} {
for { set third 0 } { $third <= 1} {incr third} {
for { set four 0 } { $four <= 1} {incr four} {
puts " f:$first $sec $third $four"
}
}
}
}
Because if so, the primary suggestion is to simply remove everything except this.
Also: [llength $splitip]
does not give you the string length of $splitip
, but the list length. Those are different.
You're using a very roundabout way to assign values to first
et al. Instead, use
lassign $splitip first sec third four
The lassign
was added in Tcl 8.5. If you're using an older version of Tcl, use assignment by foreach
instead:
foreach {first sec third four} $splitip break
The construct
for { set limit 1} { $limit >0} {incr limit -1} { ... }
simply means "execute ... exactly once": it doesn't affect the program's execution in any way. Even if you remove it (keeping the code inside the body argument), the code that was inside it will still execute exactly once.
For clarity, the incr x
invocations should be inside the third argument to for
, not inside the fourth, body, argument.
As a final note, if your intent is to print out a sequence of binary numbers, it's a lot easier to do that this way:
for {set i 0} {$i < 16} {incr i} { puts [format %04b $i] }
Upvotes: 1