Shift list elements to left by 3

From Rosetta Code
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]

ALGOL 68

<lang algol68>BEGIN

   # shifts in place the elements of a left by n                          #
   PRIO <<:= = 1;
   OP   <<:= = ( REF[]INT a, INT n )REF[]INT:
        BEGIN
           INT    a length = ( UPB a - LWB a ) + 1;
           IF n < a length AND n > 0 THEN
               # the amount to shift is less than the length of the array #
               [ 1 : a length ]INT shifted;
               shifted[ 1                    : a length - n ] := a[ n + 1 :   @ 1 ];
               shifted[ ( a length + 1 ) - n :              ] := a[ 1     : n @ 1 ];
               a[ @ 1 ] := shifted
           FI;
           a
        END # <<:= # ;
   # prints the elements of v                                             #
   OP   PRINT = ( []INT v )VOID:
        BEGIN
           print( ( "[" ) );
           BOOL need comma := FALSE;
           FOR i FROM LWB v TO UPB v DO
               print( ( IF need comma THEN "," ELSE "" FI, whole( v[ i ], 0 ) ) );
               need comma := TRUE
           OD;
           print( ( "]" ) )
        END # PRINT # ;            
   [ 1 : 9 ]INT v := ( 1, 2, 3, 4, 5, 6, 7, 8, 9 );
   PRINT v;
   print( ( " -> " ) );
   v <<:= 3;
   PRINT v;
   print( ( newline ) )

END</lang>

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

AWK

<lang AWK>

  1. syntax: GAWK -f SHIFT_LIST_ELEMENTS_TO_LEFT_BY_3.AWK

BEGIN {

   list = "1,2,3,4,5,6,7,8,9"
   printf("old: %s\n",list)
   printf("new: %s\n",shift_left(list,3))
   list = "a;b;c;d"
   printf("old: %s\n",list)
   printf("new: %s\n",shift_left(list,1,";"))
   exit(0)

} function shift_left(str,n,sep, i,left,right) {

   if (sep == "") {
     sep = ","
   }
   for (i=1; i<=n; i++) {
     left = substr(str,1,index(str,sep)-1)
     right = substr(str,index(str,sep)+1)
     str = right sep left
   }
   return(str)

} </lang>

Output:
old: 1,2,3,4,5,6,7,8,9
new: 4,5,6,7,8,9,1,2,3
old: a;b;c;d
new: b;c;d;a

C

Translation of: Wren

<lang c>#include <stdio.h>

/* in place left shift by 1 */ void lshift(int *l, size_t n) {

   int i, f;
   if (n < 2) return;
   f = l[0];
   for (i = 0; i < n-1; ++i) l[i] = l[i+1];
   l[n-1] = f;

}

int main() {

   int l[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
   int i;
   size_t n = 9;
   printf("Original list     : ");
   for (i = 0; i < n; ++i) printf("%d ", l[i]);
   printf("\nShifted left by 3 : ");
   for (i = 0; i < 3; ++i) lshift(l, n);
   for (i = 0; i < n; ++i) printf("%d ", l[i]);
   printf("\n");
   return 0;

}</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 

C++

<lang cpp>#include <algorithm>

  1. include <iostream>
  2. include <iterator>
  3. include <vector>

template <typename T> void print(const std::vector<T>& v) {

   std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
   std::cout << '\n';

}

int main() {

   std::vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9};
   std::cout << "Before: ";
   print(vec);
   std::rotate(vec.begin(), vec.begin() + 3, vec.end());
   std::cout << " After: ";
   print(vec);

}</lang>

Output:
Before: 1 2 3 4 5 6 7 8 9 
 After: 4 5 6 7 8 9 1 2 3 

Delphi

Library: Boost.Int

Boost.Int is part of DelphiBoostLib. <lang Delphi> program Shift_list_elements_to_left_by_3;

{$APPTYPE CONSOLE}

uses

 System.SysUtils,
 Boost.Int;

var

 List: TArray<Integer>;

begin

 List := [1, 2, 3, 4, 5, 6, 7, 8, 9];
 writeln('Original list     :', list.ToString);
 List.shift(3);
 writeln('Shifted left by 3 :', list.ToString);
 Readln;

end.</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]

Factor

<lang factor> USING: prettyprint sequences.extras ;

{ 1 2 3 4 5 6 7 8 9 } 3 rotate .</lang>

Output:
{ 4 5 6 7 8 9 1 2 3 }

You can also make a virtual rotated sequence. In other words, the underlying array remains the same, but the way it is indexed has been changed.

<lang factor>USING: arrays prettyprint sequences.rotated ;

{ 1 2 3 4 5 6 7 8 9 } 3 <rotated> >array .</lang>

Output:
{ 4 5 6 7 8 9 1 2 3 }

Go

Translation of: Wren

<lang go>package main

import "fmt"

// in place left shift by 1 func lshift(l []int) {

   n := len(l)
   if n < 2 {
       return
   }
   f := l[0]
   for i := 0; i < n-1; i++ {
       l[i] = l[i+1]
   }
   l[n-1] = f

}

func main() {

   l := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
   fmt.Println("Original list     :", l)
   for i := 0; i < 3; i++ {
       lshift(l)
   }
   fmt.Println("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]

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]

Perl

<lang perl>// 20210315 Perl programming solution

use strict; use warnings;

my $n = 3; my @list = 1..9;

push @list, splice @list, 0, $n;

print join ' ', @list, "\n"</lang>

Output:
4 5 6 7 8 9 1 2 3

Phix

<lang Phix>sequence s = {1,2,3,4,5,6,7,8,9} s = s[4..$]&s[1..3] ?s</lang>

Output:
{4,5,6,7,8,9,1,2,3}

Python

<lang python>def rotate(list, n):

   for _ in range(n):
       list.append(list.pop(0))
   return list
  1. or, supporting opposite direction rotations:

def rotate(list, n):

   k = (len(list) + n) % len(list)
   return list[k::] + list[:k:]


list = [1,2,3,4,5,6,7,8,9] print(list, " => ", rotate(list, 3))

</lang>

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


and we can also define rotated lists and ranges as slices taken from an infinite cycle of their values, after n initial items have been dropped:

<lang python>Padovan series

from itertools import cycle, islice


  1. rotated :: Int -> [a] -> [a]

def rotated(n):

   A list rotated n elements to the left.
   def go(xs):
       lng = len(xs)
       stream = cycle(xs)
       # (n modulo lng) elements dropped from the start,
       list(islice(stream, n % lng))
       # and lng elements drawn from the remaining cycle.
       return list(islice(stream, lng))
   return go


  1. ------------------------- TEST -------------------------
  2. main :: IO ()

def main():

   Positive and negative (left and right)
      rotations tested for list and range inputs.
   
   xs = [1, 2, 3, 4, 5, 6, 7, 8, 9]
   print("List rotated 3 position to the left:")
   print(
       rotated(3)(xs)
   )
   print("List rotated 3 positions to the right:")
   print(
       rotated(-3)(xs)
   )
   print("\nLists obtained by rotations of an input range:")
   rng = range(1, 1 + 9)
   print(
       rotated(3)(rng)
   )
   print(
       rotated(-3)(rng)
   )


  1. MAIN ---

if __name__ == '__main__':

   main()</lang>
Output:
List rotated 3 position to the left:
[4, 5, 6, 7, 8, 9, 1, 2, 3]
List rotated 3 positions to the right:
[7, 8, 9, 1, 2, 3, 4, 5, 6]

Lists obtained by rotations of an input range:
[4, 5, 6, 7, 8, 9, 1, 2, 3]
[7, 8, 9, 1, 2, 3, 4, 5, 6]

Raku

<lang perl6># 20210315 Raku programming solution

say [1..9].rotate(3)</lang>

Output:
(4 5 6 7 8 9 1 2 3)

REXX

<lang rexx>/*REXX program shifts (using a rotate) elements in a list left by some number N. */ parse arg n $ . /*obtain optional arguments from the CL*/ if n== | n=="," then n= 3 /*Not specified? Then use the default.*/ if $== | $=="," then $= '[1,2,3,4,5,6,7,8,9]' /* " " " " " " */

$$= space( translate($, , '],[') ) /*convert literal list to bare list. */ $$= '['translate( subword($$, N+1) subword($$, 1, n), ',', " ")']' /*rotate the list.*/

say 'shifting elements in the list by ' n /*display action used on the input list*/ say ' input list=' $ /* " the input list ───► terminal*/ say 'output list=' $$ /* " the output " " " */</lang>

output   when using the default inputs:
shifting elements in the list by  3
 input list= [1,2,3,4,5,6,7,8,9]
output list= [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...

Rust

<lang rust>fn main() {

   let mut v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
   println!("Before: {:?}", v);
   v.rotate_left(3);
   println!(" After: {:?}", v);

}</lang>

Output:
Before: [1, 2, 3, 4, 5, 6, 7, 8, 9]
 After: [4, 5, 6, 7, 8, 9, 1, 2, 3]

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]