Shift list elements to left by 3: Difference between revisions

From Rosetta Code
Content added Content deleted
m (julia example)
Line 26: Line 26:
see "original list:" + nl
see "original list:" + nl
showArray(shift)
showArray(shift)
see nl + "shift list elements to left by 3:" + nl
see nl + "Shifted left by 3:" + nl


for n = 1 to nshift
for n = 1 to nshift
Line 58: Line 58:
original list:
original list:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
shift list elements to left by 3:
Shifted left by 3:
[4, 5, 6, 7, 8, 9, 1, 2, 3]
[4, 5, 6, 7, 8, 9, 1, 2, 3]
done...
done...

</pre>
</pre>



Revision as of 10:19, 14 March 2021

Shift list elements to left by 3 is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task
Shift list elements to left by 3.


shift = [1,2,3,4,5,6,7,8,9]
result = [4, 5, 6, 7, 8, 9, 1, 2, 3]

Julia

<lang julia>list = [1, 2, 3, 4, 5, 6, 7, 8, 9] println(list, " => ", circshift(list, -3))

</lang>

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [4, 5, 6, 7, 8, 9, 1, 2, 3]


Ring

<lang ring> see "working..." + nl

shift = [1,2,3,4,5,6,7,8,9] lenshift = len(shift) shiftNew = list(lenshift) nshift = 3 temp = list(nshift)

see "original list:" + nl showArray(shift) see nl + "Shifted left by 3:" + nl

for n = 1 to nshift

   temp[n] = shift[n]

next

for n = 1 to lenshift - nshift

   shiftNew[n] = shift[n+nshift]

next

for n = lenshift-nshift+1 to lenshift

   shiftNew[n] = temp[n-lenshift+nshift]

next

showArray(shiftNew)

see nl + "done..." + nl

func showArray(array)

    txt = "["
    for n = 1 to len(array)
        txt = txt + array[n] + ", "
    next
    txt = left(txt,len(txt)-2)
    txt = txt + "]"
    see txt

</lang>

Output:
working...
original list:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Shifted left by 3:
[4, 5, 6, 7, 8, 9, 1, 2, 3]
done...

Wren

<lang ecmascript>// in place left shift by 1 var lshift = Fn.new { |l|

   var n = l.count
   if (n < 2) return
   var f = l[0]
   for (i in 0..n-2) l[i] = l[i+1]
   l[-1] = f

}

var l = (1..9).toList System.print("Original list  : %(l)") for (i in 1..3) lshift.call(l) System.print("Shifted left by 3 : %(l)")</lang>

Output:
Original list     : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Shifted left by 3 : [4, 5, 6, 7, 8, 9, 1, 2, 3]