Shift list elements to left by 3
- 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]
Ada
Using slices and array concatenation. <lang Ada>with Ada.Text_Io;
procedure Shift_Left is
Shift_Count : constant := 3;
type List_Type is array (Positive range <>) of Integer;
procedure Put_List (List : List_Type) is use Ada.Text_Io; begin for V of List loop Put (V'Image); Put (" "); end loop; New_Line; end Put_List;
Shift : List_Type := (1, 2, 3, 4, 5, 6, 7, 8, 9);
begin
Put_List (Shift);
Shift := Shift (Shift'First + Shift_Count .. Shift'Last) & Shift (Shift'First .. Shift_Count);
Put_List (Shift);
end Shift_Left;</lang>
- Output:
1 2 3 4 5 6 7 8 9 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]
AppleScript
Functional
<lang applescript>------------- SHIFT LIST ELEMENTS TO LEFT BY 3 -----------
-- rotated :: Int -> [a] -> [a] on rotated(n, xs)
set m to |mod|(n, length of xs) if 0 ≠ n then (items (1 + m) thru -1 of xs) & ¬ (items 1 thru m of xs) else xs end if
end rotated
TEST -------------------------
on run
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9} unlines({" Input list: " & showList(xs), ¬ " Rotated 3 left: " & showList(rotated(3, xs)), ¬ "Rotated 3 right: " & showList(rotated(-3, xs))})
end run
GENERIC ------------------------
-- mod :: Int -> Int -> Int on |mod|(n, d)
-- The built-in infix `mod` inherits the sign of the -- *dividend* for non zero results. -- (i.e. the 'rem' pattern in some languages). -- -- This version inherits the sign of the *divisor*. -- (A more typical 'mod' pattern, and useful, -- for example, with biredirectional list rotations). if signum(n) = signum(-d) then (n mod d) + d else (n mod d) end if
end |mod|
-- signum :: Num -> Num
on signum(x)
if x < 0 then -1 else if x = 0 then 0 else 1 end if
end signum
FORMATTING ----------------------
-- intercalate :: String -> [String] -> String on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬ {my text item delimiters, delim} set s to xs as text set my text item delimiters to dlm s
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f -- to each element of xs. tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell
end map
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper. if script is class of f then f else script property |λ| : f end script end if
end mReturn
-- showList :: [a] -> String
on showList(xs)
"{" & intercalate(", ", map(my str, xs)) & "}"
end showList
-- str :: a -> String
on str(x)
x as string
end str
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation -- of a list of strings with the newline character. set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set s to xs as text set my text item delimiters to dlm s
end unlines</lang>
- Output:
Input list: {1, 2, 3, 4, 5, 6, 7, 8, 9} Rotated 3 left: {4, 5, 6, 7, 8, 9, 1, 2, 3} Rotated 3 right: {7, 8, 9, 1, 2, 3, 4, 5, 6}
Two in-place alternatives
Fewest moves: <lang applescript>(* List rotation, in-place with temporary external storage. Negative 'amount' = left rotation, positive = right.
Method: Adjust the specified amount to get a positive, < list length, left-rotation figure. Store the leftmost 'amount' items. Move the other items 'amount' places to the left. Move the stored items into the rightmost slots.
- )
on rotate(lst, amount)
script o property l : lst property storage : missing value end script set len to (count o's l) if (len is 0) then return set amount to ((len - amount) mod len + len) mod len if (amount is 0) then return set o's storage to items 1 thru amount of o's l repeat with i from (amount + 1) to len set item (i - amount) of o's l to item i of o's l end repeat repeat with i from -amount to -1 set item i of o's l to item i of o's storage end repeat
end rotate
-- Task code: local lst set lst to {1, 2, 3, 4, 5, 6, 7, 8, 9} rotate(lst, -3) return lst</lang>
Wholly in-place: <lang applescript>(* List rotation, wholly in-place. Negative 'amount' = left rotation, positive = right.
Method: Adjust the specified rotation amount to get a positive, < list length, left-rotation figure. If rotating by only 1 in either direction, do it in the obvious way. Otherwise reverse the leftmost 'amount' items, reverse the others, then reverse the entire list.
- )
on rotate(lst, amount)
set len to (count lst) if (len is 0) then return script o property l : lst on rotate1(a, z, step) set v to item a of my l repeat with i from (a + step) to z by step set item (i - step) of my l to item i of my l end repeat set item z of my l to v end rotate on |reverse|(i, j) repeat with i from i to ((i + j - 1) div 2) set v to item i of my l set item i of my l to item j of my l set item j of my l to v set j to j - 1 end repeat end |reverse| end script set amount to ((len - amount) mod len + len) mod len if (amount is 1) then tell o to rotate1(1, len, 1) -- Rotate left by 1. else if (amount is len - 1) then tell o to rotate1(len, 1, -1) -- Rotate right by 1. else if (amount > 0) then tell o to |reverse|(1, amount) tell o to |reverse|(amount + 1, len) tell o to |reverse|(1, len) end if
end rotate
-- Task code: local lst set lst to {1, 2, 3, 4, 5, 6, 7, 8, 9} rotate(lst, -3) return lst</lang>
Result in both cases:
- Output:
<lang applescript>{4, 5, 6, 7, 8, 9, 1, 2, 3}</lang>
AutoHotkey
<lang AutoHotkey>Shift_list_elements(Arr, dir, n){
nums := Arr.Clone() loop % n if InStr(dir, "l") nums.Push(nums.RemoveAt(1)) else nums.InsertAt(1, nums.RemoveAt(nums.count())) return nums
}</lang> Examples:<lang AutoHotkey>Arr := [1,2,3,4,5,6,7,8,9] output1 := Shift_list_elements(Arr, "L", 3) output2 := Shift_list_elements(Arr, "R", 3) return</lang>
- Output:
output1 = [4, 5, 6, 7, 8, 9, 1, 2, 3] output2 = [7, 8, 9, 1, 2, 3, 4, 5, 6]
AWK
<lang AWK>
- 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
<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>
- include <iostream>
- include <iterator>
- 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
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]
Excel
LAMBDA
Binding the name rotatedRow to the following lambda expression in the Name Manager of the Excel WorkBook:
(See LAMBDA: The ultimate Excel worksheet function)
<lang lisp>rotatedRow =LAMBDA(n,
LAMBDA(xs, LET( nCols, COLUMNS(xs), m, MOD(n, nCols), x, SEQUENCE( 1, nCols, 1, 1 ), d, nCols - m,
IF(x > d, x - d, m + x ) ) )
)</lang>
- Output:
The formula in cell B2 defines an array which populates the whole range B2:J2
fx | =rotatedRow(3)(B1#) | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
A | B | C | D | E | F | G | H | I | J | ||
1 | List | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
2 | Rotated | 4 | 5 | 6 | 7 | 8 | 9 | 1 | 2 | 3 |
F#
<lang fsharp> // Nigel Gallowy. March 29th., 2021 let fN=function _::_::_::n->n |_->raise(System.Exception("List has fewer than 3 elements")) [[1..10];[1;2];[1;2;3]]|>Seq.iter(fun n->try printfn "%A->%A" n (fN n) with :? System.Exception as e->printfn "oops -> %s" (e.Message)) </lang>
- Output:
[1; 2; 3; 4; 5; 6; 7; 8; 9; 10]->[4; 5; 6; 7; 8; 9; 10] oops -> List has fewer than 3 elements [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 }
FreeBASIC
<lang freebasic>sub shift_left( list() as integer )
'shifts list left by one step dim as integer lo = lbound(list), hi = ubound(list), first first = list(lo) for i as integer = lo to hi list(i) = list(i+1) next i list(hi) = first return
end sub
sub shift_left_n( list() as integer, n as uinteger )
for i as uinteger = 1 to n shift_left( list() ) next i return
end sub
dim as integer list(1 to 9) = {1,2,3,4,5,6,7,8,9} shift_left_n( list(), 3 ) for i as integer = 1 to 9
print list(i); if i<9 then print ", ";
next i</lang>
- Output:
4, 5, 6, 7, 8, 9, 1, 2, 3
Go
<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]
Haskell
<lang haskell>------------- SHIFT LIST ELEMENTS TO LEFT BY N -----------
rotated :: Int -> [a] -> [a] rotated n xs =
take <*> (flip drop (cycle xs) . mod n) $ length xs
TEST -------------------------
main :: IO () main =
let xs = [1 .. 9] in putStrLn "List rotated 3 positions to the left:" >> print (rotated 3 xs) >> print (rotated 30 xs) >> putStrLn "\nList rotated 3 positions to the right:" >> print (rotated (-3) xs) >> print (rotated (-30) xs)</lang>
- Output:
List rotated 3 positions to the left: [4,5,6,7,8,9,1,2,3] [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] [7,8,9,1,2,3,4,5,6]
Java
<lang java>import java.util.List; import java.util.Arrays; import java.util.Collections;
public class RotateLeft {
public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); System.out.println("original: " + list); Collections.rotate(list, -3); System.out.println("rotated: " + list); }
} </lang>
- Output:
original: [1, 2, 3, 4, 5, 6, 7, 8, 9] rotated: [4, 5, 6, 7, 8, 9, 1, 2, 3]
JavaScript
<lang javascript>(() => {
"use strict";
// -------- SHIFT LIST ELEMENTS TO LEFT BY 3 ---------
// rotated :: Int -> [a] -> [a] const rotated = n => // A rotation, n elements to the left, // of the input list. xs => 0 !== n ? (() => { const m = mod(n)(xs.length);
return xs.slice(m).concat( xs.slice(0, m) ); })() : Array.from(xs);
// ---------------------- TEST ----------------------- // main :: IO () const main = () => { const xs = [1, 2, 3, 4, 5, 6, 7, 8, 9];
return [ ` The input list: ${show(xs)}`, ` rotated 3 to left: ${show(rotated(3)(xs))}`, ` or 3 to right: ${show(rotated(-3)(xs))}` ] .join("\n"); };
// --------------------- GENERIC ---------------------
// mod :: Int -> Int -> Int const mod = n => // Inherits the sign of the *divisor* for non zero // results. Compare with `rem`, which inherits // the sign of the *dividend*. d => (n % d) + ( signum(n) === signum(-d) ? ( d ) : 0 );
// signum :: Num -> Num const signum = n => 0 > n ? ( -1 ) : ( 0 < n ? 1 : 0 );
// show :: a -> String const show = x => JSON.stringify(x);
// MAIN --- return main();
})();</lang>
- Output:
The input list: [1,2,3,4,5,6,7,8,9] rotated 3 to left: [4,5,6,7,8,9,1,2,3] or 3 to right: [7,8,9,1,2,3,4,5,6]
jq
Works with gojq, the Go implementation of jq <lang jq># input should be an array or string def rotateLeft($n):
.[$n:] + .[:$n];</lang>
Examples:
[1, 2, 3, 4, 5, 6, 7, 8, 9] | rotateLeft(3) #=> [4,5,6,7,8,9,1,2,3] "123456789" | rotateLeft(3) #=> "456789123"
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]
Nim
Using “rotatedLeft” from standard module “algorithm”. Note that its exists also “rotateLeft” for rotation in place.
<lang Nim>import algorithm
let list = @[1, 2, 3, 4, 5, 6, 7, 8, 9] echo list, " → ", rotatedLeft(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
sequence s = {1,2,3,4,5,6,7,8,9} s = s[4..$]&s[1..3] ?s
- 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
- 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>Shift list elements to left by 3
from itertools import cycle, islice
- 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
- ------------------------- TEST -------------------------
- 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 positions 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) )
- MAIN ---
if __name__ == '__main__':
main()</lang>
- Output:
List rotated 3 positions 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]
Quackery
<lang Quackery>' [ 1 2 3 4 5 6 7 8 9 ] 3 split swap join echo</lang>
- Output:
[ 4 5 6 7 8 9 1 2 3 ]
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...
Ruby
Note, unlike some other languages, for Ruby's Array.rotate() method, a positive number means rotate to the left, while a negative number means rotate to the right. Use Array.rotate!() if you wish to mutate the original array rather than return a new one. <lang ruby>list = [1,2,3,4,5,6,7,8,9] p list.rotate(3)
</lang>
- Output:
[4, 5, 6, 7, 8, 9, 1, 2, 3]
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]