Quantcast
Channel: Cadence PCB Skill Forum
Viewing all articles
Browse latest Browse all 2154

Swapping elements in a list

$
0
0

I need to receive a list and then reverse two elements in the list. Not finding a good way to do it with the included SKILL functions (though I could have just missed it), I wrote my own. Here it is (as usual, sorry for the lack of formatting):

; swaps element at given index with following element in list
; parameters:
; swap_index: index of film to move [integer]
; input_list: list to be modified [list]
; returns: input_list with swapped elements [list]
procedure(swap_next(swap_index input_list)
   let((j final_list)
      setq(j 0) ; need external counter in for loop variable auto-increments

      ; run through input list and either grab the current element or swap the next two
      for(i 0 (length(input_list) - 2)
         if(j == swap_index then
            ; at the index to swap, dump next element and then current element into output list
            final_list = cons(nth((j + 1) input_list) final_list)
            final_list = cons(nth(j input_list) final_list)

            j++ ; increment counter since we grabbed two elements
         else
            ; for any other index, just copy the input list to output list
            final_list = cons(nth(j input_list) final_list)
         )

         j++
      )

      reverse(final_list) ; return reversed list since it was built "backwards"
   )
)

This works, but it's awfully complicated. Since I don't have direct access to the auto-incrementing loop variable, I created my own. It seemed more complicated to use foreach() than this, but I'm a hardware guy who likes to think he can write a bit of code. I wouldn't be surprised if there's an obvious way to do it and I'm just daft for overlooking it.

Thanks in advance for any advice.


Viewing all articles
Browse latest Browse all 2154

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>