(50g) (userRPL) additional operations with a list - pier4r - 04-04-2017 12:33 PM
As exposed here I need to shuffle elements in a list, I did not find anything useful already existing so I share my rough solution. If you have or know better ones, it would be great if you would share them 
Code:
shuffleList
\<<
@program that receives a list in input, and shuffles the elements
@returning the shuffled list in output on the stack
@arguments on the stack.
@ 2: list
@ 1: number of random elements to shuffle around
0
\->
@external inputs
inputList
noShuffles
@local var
numEl
\<<
@explode the list on the stack
inputList OBJ\->
@save the num of elements
'numEl' STO
@roll randomily the elements in the list
1 noShuffles
START
numEl RAND * 1 + IP
ROLL
NEXT
@build the list back
numEl
\->LIST
\>>
\>>
having both head and tail on the stack (not only HEAD or TAIL with the built in commands)
Code:
headTail
\<<
@given a list in input, leaves on level1 the first element
@ and on level 2 the rest of the list.
@0 numEl
\->
@external input
list
@local input
@numEl
@elements in the list.
\<<
list OBJ\-> 1 - \->LIST
@redung the number of elements of 1 for the new list
@we have the tail on level 2
SWAP
@now the head element is on the level 1 stack
\>>
\>>
Code:
tailHead
\<<
@given a list in input, leaves on level1 the rest of the list
@ and on level 1 the head of the list
@0 numEl
\->
@external input
list
@local input
@numEl
@elements in the list.
\<<
list OBJ\-> 1 - \->LIST
@redung the number of elements of 1 for the new list
@we have the tail on the level 1
@ head level 2
\>>
\>>
Increasing an element in the list
Code:
IncListElFunc
\<<
@ program to increase the value of an element in a list
@ input on the stack, see variables
@output, the list in input, modified, on the stack
0
\->
@external inputs
lList
@list
lPosV
@position of the element
lincV
@increase
@local var
numEl
\<<
lList OBJ\->
@list on the stack, with end part number of elements.
'numEl' STO
@now to access the element in position, starting from the back
@we need to do (numberOfelements - position) +1 steps.
numEl lPosV - 1 +
@the position on the stack to pick from the back
@we recall the element
ROLL
@Something like the following
@{ 1 2 3 5} 1 1 1
@2 (pos) 2 2 3
@ 3 3 5
@ 5 5 2
@ 4 (4-2+1)
@increment the value on the stack
lincV +
@roll it back, the same number of postions like before
@so to counter the previous roll.
numEl lPosV - 1 +
ROLLD
@recreate the list and leave it on the stack.
numEl
\->LIST
\>>
\>>
|