Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is my approach: build one sub-list at a time, then append to the result before building the next one.</p> <pre><code>proc lnth2 {L n} { set listLen [llength $L] set subListLen [expr {$listLen / $n}] if {$listLen % $n != 0} { incr subListLen } set result {} for {set iteration 0} {$iteration &lt; $n} {incr iteration} { set subList {} for {set i $iteration} {$i &lt; $listLen} {incr i $n} { lappend subList [lindex $L $i] } lappend result $subList } return $result } </code></pre> <p>Let say that L = <code>{a 1 b 2 c 3}</code> and n = 2, then I will build the first sub-list <code>{a b c}</code> by picking out the 0th, 2nd, and 4th items from the original list, append that to the result and move on the the second sub-list. Likewise, the second sub-list will be the 1th, 3rd, and 5th items. </p> <h1>Update</h1> <p>After reviewing my solution, I still don't like the fact that I have to use <code>lindex</code>. I imagine <code>lindex</code> has to travese the list in order to find the list item, and my solution placed <code>lindex</code> right inside a loop; which means we traverse the same list several times. The next attempt is to traverse the list only once. This time, I mimic your algorithm, but avoid using the list functions such as <code>lrange</code>.</p> <pre><code>proc lnth3 {L n} { # Create a list of variables: subList0, subList1, subList2, ... for {set subListNumber 0} {$subListNumber &lt; $n} {incr subListNumber} { set subList$subListNumber {} } # Build the sub-lists set i 0 foreach item $L { set subListNumber [expr {$i % $n}] lappend subList$subListNumber $item incr i } # Build the result from all the sub-lists set result {} for {set subListNumber 0} {$subListNumber &lt; $n} {incr subListNumber} { lappend result [set subList$subListNumber] } return $result } </code></pre> <p>Sadly, this attempt performs worse than my first attempt. I still don't understand why.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload