Shift list elements to left by 3: Difference between revisions
Added Rust solution |
|||
(70 intermediate revisions by 33 users not shown) | |||
Line 1: | Line 1: | ||
{{Draft task}} |
{{Draft task}} |
||
;Task: |
|||
;Task: Shift list elements to left by 3. |
|||
Shift list elements to left by '''3'''. |
|||
<br> shift = [1,2,3,4,5,6,7,8,9] |
|||
shift = [1,2,3,4,5,6,7,8,9] |
|||
result = [4, 5, 6, 7, 8, 9, 1, 2, 3] |
|||
<br><br> |
|||
=={{header|11l}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="11l">F rotate(l, n) |
|||
V k = (l.len + n) % l.len |
|||
R l[k ..] [+] l[0 .< k] |
|||
V l = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
|||
print(l‘ => ’rotate(l, 3))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [4, 5, 6, 7, 8, 9, 1, 2, 3] |
|||
</pre> |
|||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size) |
|||
INT i |
|||
Put('[) |
|||
FOR i=0 TO size-1 |
|||
DO |
|||
IF i>0 THEN Put(' ) FI |
|||
PrintI(a(i)) |
|||
OD |
|||
Put(']) PutE() |
|||
RETURN |
|||
PROC ShiftLeft(INT ARRAY a INT size) |
|||
INT i,j,tmp |
|||
tmp=a(0) |
|||
FOR i=0 TO size-2 |
|||
DO |
|||
a(i)=a(i+1) |
|||
OD |
|||
a(size-1)=tmp |
|||
RETURN |
|||
PROC ShiftLeftNTimes(INT ARRAY a INT size,times) |
|||
INT i |
|||
FOR i=1 TO times |
|||
DO |
|||
ShiftLeft(a,size) |
|||
OD |
|||
RETURN |
|||
PROC Test(INT ARRAY a INT size,offset) |
|||
PrintArray(a,size) |
|||
ShiftLeftNTimes(a,size,3) |
|||
PrintArray(a,size) |
|||
RETURN |
|||
PROC Main() |
|||
INT ARRAY a=[1 2 3 4 5 6 7 8 9] |
|||
Test(a,9,-3) |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Shift_list_elements_to_left_by_3.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
[1 2 3 4 5 6 7 8 9] |
|||
[4 5 6 7 8 9 1 2 3] |
|||
</pre> |
|||
=={{header|Ada}}== |
|||
Using slices and array concatenation. |
|||
<syntaxhighlight 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;</syntaxhighlight> |
|||
{{out}} |
|||
<pre> 1 2 3 4 5 6 7 8 9 |
|||
4 5 6 7 8 9 1 2 3</pre> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
< |
<syntaxhighlight lang="algol68">BEGIN |
||
# shifts in place the elements of a left by n # |
# shifts in place the elements of a left by n # |
||
PRIO <<:= = 1; |
PRIO <<:= = 1; |
||
Line 25: | Line 125: | ||
BEGIN |
BEGIN |
||
print( ( "[" ) ); |
print( ( "[" ) ); |
||
IF LWB v <= UPB v THEN |
|||
print( ( whole( v[ LWB v ], 0 ) ) ); |
|||
FOR i FROM LWB v + 1 TO UPB v DO |
|||
print( ( "," , whole( v[ i ], 0 ) ) ) |
|||
OD |
OD |
||
FI; |
|||
print( ( "]" ) ) |
print( ( "]" ) ) |
||
END # PRINT # ; |
END # PRINT # ; |
||
Line 38: | Line 139: | ||
PRINT v; |
PRINT v; |
||
print( ( newline ) ) |
print( ( newline ) ) |
||
END</ |
END</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
[1,2,3,4,5,6,7,8,9] -> [4,5,6,7,8,9,1,2,3] |
[1,2,3,4,5,6,7,8,9] -> [4,5,6,7,8,9,1,2,3] |
||
</pre> |
</pre> |
||
=={{header|ALGOL W}}== |
|||
{{Trans|ALGOL 68}} |
|||
<syntaxhighlight lang="pascal">begin |
|||
% increments a and returns the new value % |
|||
integer procedure inc ( integer value result a ) ; begin a := a + 1; a end; |
|||
% shifts in place the elements of a left by n, a must have bounds lb::ub % |
|||
procedure rotateLeft ( integer array a ( * ); integer value lb, ub, n ) ; |
|||
if n < ( ub - lb ) and n > 0 then begin |
|||
% the amount to shift is less than the length of the array % |
|||
integer array shifted ( 1 :: n ); |
|||
integer aPos; |
|||
for i := 0 until n - 1 do shifted( i ) := a( lb + i ); |
|||
for i := lb until ub - n do a( i ) := a( i + n ); |
|||
aPos := ub - n; |
|||
for i := 0 until n - 1 do a( inc( aPos ) ) := shifted( i ); |
|||
end rotateLeft ; |
|||
% prints the elements of v from lb to ub % |
|||
procedure printArray ( integer array v ( * ); integer value lb, ub ) ; |
|||
begin |
|||
writeon( s_w := 0, "[" ); |
|||
if lb <= ub then begin |
|||
writeon( i_w := 1, s_w := 0, v( lb ) ); |
|||
for i := lb + 1 until ub do writeon( i_w := 1, s_w := 0, "," , v( i ) ) |
|||
end; |
|||
writeon( s_w := 0, "]" ) |
|||
end printArray ; |
|||
begin |
|||
integer array v ( 1 :: 9 ); |
|||
for i := 1 until 9 do v( i ) := i; |
|||
printArray( v, 1, 9 ); |
|||
writeon( " -> " ); |
|||
rotateLeft( v, 1, 9, 3 ); |
|||
printArray( v, 1, 9 ); |
|||
write() |
|||
end |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[1,2,3,4,5,6,7,8,9] -> [4,5,6,7,8,9,1,2,3] |
|||
</pre> |
|||
=={{header|AppleScript}}== |
|||
===Functional=== |
|||
====Prefix appended==== |
|||
<syntaxhighlight lang="applescript">------------- SHIFT LIST ELEMENTS TO LEFT BY 3 ----------- |
|||
-- rotated :: Int -> [a] -> [a] |
|||
on rotated(n, xs) |
|||
if 0 ≠ n then |
|||
set m to |mod|(n, length of xs) |
|||
(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</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> 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}</pre> |
|||
====Cycle sampled==== |
|||
Another approach: drawing from an infinite list of cycles: |
|||
<syntaxhighlight lang="applescript">------------- SHIFT LIST ELEMENTS TO LEFT BY 3 ----------- |
|||
-- rotated :: Int -> [a] -> [a] |
|||
on rotated(n, xs) |
|||
set m to length of xs |
|||
take(m, drop(|mod|(n, m), cycle(xs))) |
|||
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)), ¬ |
|||
" " & showList(rotated(30, xs)), ¬ |
|||
" Rotated 3 right: " & showList(rotated(-3, xs)), ¬ |
|||
" " & showList(rotated(-30, xs))}) |
|||
end run |
|||
------------------------- GENERIC ------------------------ |
|||
-- cycle :: [a] -> Generator [a] |
|||
on cycle(xs) |
|||
script |
|||
property lng : 1 + (length of xs) |
|||
property i : missing value |
|||
on |λ|() |
|||
if missing value is i then |
|||
set i to 1 |
|||
else |
|||
set nxt to (1 + i) mod lng |
|||
if 0 = ((1 + i) mod lng) then |
|||
set i to 1 |
|||
else |
|||
set i to nxt |
|||
end if |
|||
end if |
|||
return item i of xs |
|||
end |λ| |
|||
end script |
|||
end cycle |
|||
-- drop :: Int -> [a] -> [a] |
|||
-- drop :: Int -> String -> String |
|||
on drop(n, xs) |
|||
set c to class of xs |
|||
if script is not c then |
|||
if string is not c then |
|||
if n < length of xs then |
|||
items (1 + n) thru -1 of xs |
|||
else |
|||
{} |
|||
end if |
|||
else |
|||
if n < length of xs then |
|||
text (1 + n) thru -1 of xs |
|||
else |
|||
"" |
|||
end if |
|||
end if |
|||
else |
|||
take(n, xs) -- consumed |
|||
return xs |
|||
end if |
|||
end drop |
|||
-- 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 |
|||
-- take :: Int -> [a] -> [a] |
|||
-- take :: Int -> String -> String |
|||
on take(n, xs) |
|||
set c to class of xs |
|||
if list is c then |
|||
set lng to length of xs |
|||
if 0 < n and 0 < lng then |
|||
items 1 thru min(n, lng) of xs |
|||
else |
|||
{} |
|||
end if |
|||
else if string is c then |
|||
if 0 < n then |
|||
text 1 thru min(n, length of xs) of xs |
|||
else |
|||
"" |
|||
end if |
|||
else if script is c then |
|||
set ys to {} |
|||
repeat with i from 1 to n |
|||
set v to |λ|() of xs |
|||
if missing value is v then |
|||
return ys |
|||
else |
|||
set end of ys to v |
|||
end if |
|||
end repeat |
|||
return ys |
|||
else |
|||
missing value |
|||
end if |
|||
end take |
|||
------------------------ 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</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> Input list: {1, 2, 3, 4, 5, 6, 7, 8, 9} |
|||
Rotated 3 left: {4, 5, 6, 7, 8, 9, 1, 2, 3} |
|||
{4, 5, 6, 7, 8, 9, 1, 2, 3} |
|||
Rotated 3 right: {7, 8, 9, 1, 2, 3, 4, 5, 6} |
|||
{7, 8, 9, 1, 2, 3, 4, 5, 6}</pre> |
|||
===Two in-place alternatives=== |
|||
Fewest moves: |
|||
<syntaxhighlight lang="applescript">(* List range 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 range's leftmost 'amount' items. |
|||
Move the range's other items 'amount' places to the left. |
|||
Move the stored items into the range's rightmost slots. |
|||
*) |
|||
on rotate(theList, l, r, amount) |
|||
set listLength to (count theList) |
|||
if (listLength < 2) then return |
|||
if (l < 0) then set l to listLength + l + 1 |
|||
if (r < 0) then set r to listLength + r + 1 |
|||
if (l > r) then set {l, r} to {r, l} |
|||
script o |
|||
property lst : theList |
|||
property storage : missing value |
|||
end script |
|||
set rangeLength to r - l + 1 |
|||
set amount to (rangeLength + rangeLength - amount) mod rangeLength |
|||
if (amount is 0) then return |
|||
set o's storage to o's lst's items l thru (l + amount - 1) |
|||
repeat with i from (l + amount) to r |
|||
set o's lst's item (i - amount) to o's lst's item i |
|||
end repeat |
|||
set j to r - amount |
|||
repeat with i from 1 to amount |
|||
set o's lst's item (j + i) to o's storage's item i |
|||
end repeat |
|||
end rotate |
|||
-- Task code: |
|||
local lst |
|||
set lst to {1, 2, 3, 4, 5, 6, 7, 8, 9} |
|||
-- Left-rotate all items (1 thru -1) by three places. |
|||
rotate(lst, 1, -1, -3) |
|||
return lst</syntaxhighlight> |
|||
Wholly in-place: |
|||
<syntaxhighlight lang="applescript">(* List range 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 range's leftmost 'amount' items, reverse the others, then reverse the lot. |
|||
*) |
|||
on rotate(theList, l, r, amount) |
|||
set listLength to (count theList) |
|||
if (listLength < 2) then return |
|||
if (l < 0) then set l to listLength + l + 1 |
|||
if (r < 0) then set r to listLength + r + 1 |
|||
if (l > r) then set {l, r} to {r, l} |
|||
script o |
|||
property lst : theList |
|||
on rotate1(a, z, step) |
|||
set v to my lst's item a |
|||
repeat with i from (a + step) to z by step |
|||
set my lst's item (i - step) to my lst's item i |
|||
end repeat |
|||
set my lst's item z to v |
|||
end rotate1 |
|||
on |reverse|(i, j) |
|||
repeat with i from i to ((i + j - 1) div 2) |
|||
set v to my lst's item i |
|||
set my lst's item i to my lst's item j |
|||
set my lst's item j to v |
|||
set j to j - 1 |
|||
end repeat |
|||
end |reverse| |
|||
end script |
|||
set rangeLength to r - l + 1 |
|||
set amount to (rangeLength + rangeLength - amount) mod rangeLength |
|||
if (amount is 1) then |
|||
tell o to rotate1(l, r, 1) -- Rotate left by 1. |
|||
else if (amount = rangeLength - 1) then |
|||
tell o to rotate1(r, l, -1) -- Rotate right by 1. |
|||
else if (amount > 0) then |
|||
tell o to |reverse|(l, l + amount - 1) |
|||
tell o to |reverse|(l + amount, r) |
|||
tell o to |reverse|(l, r) |
|||
end if |
|||
end rotate |
|||
-- Task code: |
|||
local lst |
|||
set lst to {1, 2, 3, 4, 5, 6, 7, 8, 9} |
|||
-- Left-rotate all items (1 thru -1) by three places. |
|||
rotate(lst, 1, -1, -3) |
|||
return lst</syntaxhighlight> |
|||
Result in both cases: |
|||
{{output}} |
|||
<syntaxhighlight lang="applescript">{4, 5, 6, 7, 8, 9, 1, 2, 3}</syntaxhighlight> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">lst: [1 2 3 4 5 6 7 8 9] |
|||
print rotate.left lst 3</syntaxhighlight> |
|||
{{out}} |
|||
<pre>4 5 6 7 8 9 1 2 3</pre> |
|||
=={{header|AutoHotkey}}== |
|||
<syntaxhighlight 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 |
|||
}</syntaxhighlight> |
|||
Examples:<syntaxhighlight 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</syntaxhighlight> |
|||
{{out}} |
|||
<pre>output1 = [4, 5, 6, 7, 8, 9, 1, 2, 3] |
|||
output2 = [7, 8, 9, 1, 2, 3, 4, 5, 6] |
|||
</pre> |
|||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f SHIFT_LIST_ELEMENTS_TO_LEFT_BY_3.AWK |
# syntax: GAWK -f SHIFT_LIST_ELEMENTS_TO_LEFT_BY_3.AWK |
||
BEGIN { |
BEGIN { |
||
Line 66: | Line 668: | ||
return(str) |
return(str) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 74: | Line 676: | ||
new: b;c;d;a |
new: b;c;d;a |
||
</pre> |
</pre> |
||
=={{header|BASIC}}== |
|||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="freebasic">arraybase 1 |
|||
global lista |
|||
dim lista(9) |
|||
lista[1] = 1 |
|||
lista[2] = 2 |
|||
lista[3] = 3 |
|||
lista[4] = 4 |
|||
lista[5] = 5 |
|||
lista[6] = 6 |
|||
lista[7] = 7 |
|||
lista[8] = 8 |
|||
lista[9] = 9 |
|||
subroutine shiftLeft (lista) |
|||
lo = lista[?,] |
|||
hi = lista[?] |
|||
first = lista[lo] |
|||
for i = lo to hi-1 |
|||
lista[i] = lista[i + 1] |
|||
next i |
|||
lista[hi] = first |
|||
end subroutine |
|||
subroutine shiftLeftN (lista, n) |
|||
for i = 1 to n |
|||
call shiftLeft(lista) |
|||
next i |
|||
end subroutine |
|||
call shiftLeftN(lista, 3) |
|||
for i = 1 to 9 |
|||
print lista[i]; |
|||
if i < 9 then print ", "; |
|||
next i |
|||
end |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Igual que la entrada de FreeBASIC. |
|||
</pre> |
|||
==={{header|PureBasic}}=== |
|||
<syntaxhighlight lang="purebasic">Global Dim lista.i(9) |
|||
DataSection |
|||
Data.i 1,2,3,4,5,6,7,8,9 |
|||
EndDataSection |
|||
For i.i = 1 To 9 |
|||
Read lista(i) |
|||
Next i |
|||
Procedure shiftLeft (lista) |
|||
;shifts list left by one step |
|||
lo.i = 1 ;ArraySize(lista(), 1) |
|||
hi.i = ArraySize(lista()) |
|||
first.i = lista(lo) |
|||
For i.i = lo To hi-1 |
|||
lista(i) = lista(i + 1) |
|||
Next i |
|||
lista(hi) = first |
|||
EndProcedure |
|||
Procedure shiftLeftN (lista, n) |
|||
For i.i = 1 To n |
|||
shiftLeft(lista) |
|||
Next i |
|||
EndProcedure |
|||
OpenConsole() |
|||
shiftLeftN(lista, 3) |
|||
For i.i = 1 To 9 |
|||
Print(Str(lista(i))) |
|||
If i < 9 : Print(", ") : EndIf |
|||
Next i |
|||
Input() |
|||
CloseConsole()</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Igual que la entrada de FreeBASIC. |
|||
</pre> |
|||
==={{header|QBasic}}=== |
|||
<syntaxhighlight lang="qbasic">DIM SHARED lista(1 TO 9) |
|||
DATA 1,2,3,4,5,6,7,8,9 |
|||
FOR i = 1 TO 9 |
|||
READ lista(i) |
|||
NEXT i |
|||
SUB shiftLeft (lista()) |
|||
lo = LBOUND(lista) |
|||
hi = UBOUND(lista) |
|||
first = lista(lo) |
|||
FOR i = lo TO hi |
|||
lista(i) = lista(i + 1) |
|||
NEXT i |
|||
lista(hi) = first |
|||
END SUB |
|||
SUB shiftLeftN (lista(), n) |
|||
FOR i = 1 TO n |
|||
CALL shiftLeft(lista()) |
|||
NEXT i |
|||
END SUB |
|||
CALL shiftLeftN(lista(), 3) |
|||
FOR i = 1 TO 9 |
|||
PRINT lista(i); |
|||
IF i < 9 THEN PRINT ", "; |
|||
NEXT i |
|||
END</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Igual que la entrada de FreeBASIC. |
|||
</pre> |
|||
=={{header|BQN}}== |
|||
<syntaxhighlight lang="bqn">data ← 1 + ↕9 |
|||
3 ⌽ data</syntaxhighlight> |
|||
{{out}} |
|||
<pre>⟨ 4 5 6 7 8 9 1 2 3 ⟩</pre> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
{{trans|Wren}} |
{{trans|Wren}} |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
/* in place left shift by 1 */ |
/* in place left shift by 1 */ |
||
Line 99: | Line 828: | ||
printf("\n"); |
printf("\n"); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 108: | Line 837: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <algorithm> |
||
#include <iostream> |
#include <iostream> |
||
#include <iterator> |
#include <iterator> |
||
Line 126: | Line 855: | ||
std::cout << " After: "; |
std::cout << " After: "; |
||
print(vec); |
print(vec); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 133: | Line 862: | ||
After: 4 5 6 7 8 9 1 2 3 |
After: 4 5 6 7 8 9 1 2 3 |
||
</pre> |
</pre> |
||
=={{header|CLU}}== |
|||
<syntaxhighlight lang="clu">% Shift an array left by a certain amount |
|||
shift_left = proc [T: type] (a: array[T], n: int) |
|||
at = array[T] |
|||
% shifting an empty array is a no-op |
|||
if at$empty(a) then return end |
|||
% otherwise we take elements from the bottom |
|||
% and put them at the top |
|||
low: int := at$low(a) |
|||
for i: int in int$from_to(1, n) do |
|||
at$addh(a, at$reml(a)) |
|||
end |
|||
at$set_low(a, low) |
|||
end shift_left |
|||
show = proc (s: stream, a: array[int]) |
|||
for i: int in array[int]$elements(a) do |
|||
stream$puts(s, int$unparse(i) || " ") |
|||
end |
|||
stream$putc(s,'\n') |
|||
end show |
|||
start_up = proc () |
|||
po: stream := stream$primary_output() |
|||
arr: array[int] := array[int]$[1,2,3,4,5,6,7,8,9] |
|||
stream$puts(po, "Before: ") show(po, arr) |
|||
shift_left[int](arr, 3) |
|||
stream$puts(po, " After: ") show(po, arr) |
|||
end start_up </syntaxhighlight> |
|||
{{out}} |
|||
<pre>Before: 1 2 3 4 5 6 7 8 9 |
|||
After: 4 5 6 7 8 9 1 2 3</pre> |
|||
=={{header|Common Lisp}}== |
|||
<syntaxhighlight lang="lisp">;; Load the alexandria library from the quicklisp repository |
|||
CL-USER> (ql:quickload "alexandria") |
|||
CL-USER> (alexandria:rotate '(1 2 3 4 5 6 7 8 9) -3) |
|||
(4 5 6 7 8 9 1 2 3)</syntaxhighlight> |
|||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
{{libheader| System.SysUtils}} |
{{libheader| System.SysUtils}} |
||
{{libheader| Boost.Int}} |
{{libheader| Boost.Int}} |
||
Boost.Int is part of [https://github.com/MaiconSoft/DelphiBoostLib DelphiBoostLib]. |
Boost.Int is part of [https://github.com/MaiconSoft/DelphiBoostLib DelphiBoostLib]. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program Shift_list_elements_to_left_by_3; |
program Shift_list_elements_to_left_by_3; |
||
Line 155: | Line 927: | ||
writeln('Shifted left by 3 :', list.ToString); |
writeln('Shifted left by 3 :', list.ToString); |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Original list :[1, 2, 3, 4, 5, 6, 7, 8, 9] |
<pre>Original list :[1, 2, 3, 4, 5, 6, 7, 8, 9] |
||
Shifted left by 3 :[4, 5, 6, 7, 8, 9, 1, 2, 3]</pre> |
Shifted left by 3 :[4, 5, 6, 7, 8, 9, 1, 2, 3]</pre> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang=text> |
|||
func[] rotate a[] n . |
|||
for i to len a[] |
|||
r[] &= a[(i + n) mod1 len a[]] |
|||
. |
|||
return r[] |
|||
. |
|||
print rotate [ 1 2 3 4 5 6 7 8 9 ] 3 |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[ 4 5 6 7 8 9 1 2 3 ] |
|||
</pre> |
|||
=={{header|ed}}== |
|||
Port of [[#sed]] version. |
|||
<syntaxhighlight lang="sed"> |
|||
H |
|||
g/.*/s/^\([^,]*\),\(.*\)/\2,\1/ |
|||
g/.*/s/^\([^,]*\),\(.*\)/\2,\1/ |
|||
g/.*/s/^\([^,]*\),\(.*\)/\2,\1/ |
|||
,p |
|||
Q |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ ed -s rotate.input < rotate.ed |
|||
Newline appended |
|||
4,5,6,7,8,9,1,2,3</pre> |
|||
=={{header|Elixir}}== |
|||
<syntaxhighlight lang="elixir"> |
|||
def rotate(enumerable, count) do |
|||
{left, right} = Enum.split(enumerable, count) |
|||
right ++ left |
|||
end |
|||
rotate(1..9, 3) |
|||
# [4, 5, 6, 7, 8, 9, 1, 2, 3] |
|||
</syntaxhighlight> |
|||
=={{header|Euler}}== |
|||
'''begin''' |
|||
'''new''' shl; '''new''' shl3; |
|||
shl <- ` '''formal''' ls; |
|||
'''if''' '''length''' ls < 2 '''then''' ls |
|||
'''else''' '''begin''' |
|||
'''new''' L; |
|||
L <- ls; |
|||
'''tail''' L & ( L[ 1 ] ) |
|||
'''end''' |
|||
'; |
|||
shl3 <- ` '''formal''' ls; shl( shl( shl( ls ) ) ) '; |
|||
'''out''' shl3( ( 1, 2, 3, 4, 5, 6, 7, 8 ) ) |
|||
'''end''' |
|||
$ |
|||
=={{header|Excel}}== |
|||
===LAMBDA=== |
|||
Binding the name '''rotatedRow''' to the following lambda expression in the Name Manager of the Excel WorkBook: |
|||
(See [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ LAMBDA: The ultimate Excel worksheet function]) |
|||
{{Works with|Office 365 betas 2021}} |
|||
<syntaxhighlight 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 |
|||
) |
|||
) |
|||
) |
|||
)</syntaxhighlight> |
|||
{{Out}} |
|||
The formula in cell B2 defines an array which populates the whole range '''B2:J2''' |
|||
{| class="wikitable" |
|||
|- |
|||
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx |
|||
! colspan="10" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=rotatedRow(3)(B1#) |
|||
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;" |
|||
| |
|||
| A |
|||
| B |
|||
| C |
|||
| D |
|||
| E |
|||
| F |
|||
| G |
|||
| H |
|||
| I |
|||
| J |
|||
|- |
|||
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1 |
|||
| style="font-weight:bold" | List |
|||
| style="text-align:right; font-weight:bold" | 1 |
|||
| style="text-align:right; font-weight:bold" | 2 |
|||
| style="text-align:right; font-weight:bold" | 3 |
|||
| style="text-align:right; font-weight:bold" | 4 |
|||
| style="text-align:right; font-weight:bold" | 5 |
|||
| style="text-align:right; font-weight:bold" | 6 |
|||
| style="text-align:right; font-weight:bold" | 7 |
|||
| style="text-align:right; font-weight:bold" | 8 |
|||
| style="text-align:right; font-weight:bold" | 9 |
|||
|- |
|||
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2 |
|||
| Rotated |
|||
| style="text-align:right; background-color:#cbcefb" | 4 |
|||
| style="text-align:right" | 5 |
|||
| style="text-align:right" | 6 |
|||
| style="text-align:right" | 7 |
|||
| style="text-align:right" | 8 |
|||
| style="text-align:right" | 9 |
|||
| style="text-align:right" | 1 |
|||
| style="text-align:right" | 2 |
|||
| style="text-align:right" | 3 |
|||
|} |
|||
Or, in terms of the MAKEARRAY function: |
|||
<syntaxhighlight lang="lisp">rotated |
|||
=LAMBDA(n, |
|||
LAMBDA(xs, |
|||
LET( |
|||
nCols, COLUMNS(xs), |
|||
m, MOD(n, nCols), |
|||
d, nCols - m, |
|||
MAKEARRAY( |
|||
1, nCols, |
|||
LAMBDA( |
|||
_, x, |
|||
IF(d < x, |
|||
x - d, |
|||
m + x |
|||
) |
|||
) |
|||
) |
|||
) |
|||
) |
|||
)</syntaxhighlight> |
|||
{{Out}} |
|||
{| class="wikitable" |
|||
|- |
|||
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx |
|||
! colspan="10" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=rotated(3)(B1#) |
|||
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;" |
|||
| |
|||
| A |
|||
| B |
|||
| C |
|||
| D |
|||
| E |
|||
| F |
|||
| G |
|||
| H |
|||
| I |
|||
| J |
|||
|- |
|||
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1 |
|||
| List |
|||
| style="text-align:right" | 1 |
|||
| style="text-align:right" | 2 |
|||
| style="text-align:right" | 3 |
|||
| style="text-align:right" | 4 |
|||
| style="text-align:right" | 5 |
|||
| style="text-align:right" | 6 |
|||
| style="text-align:right" | 7 |
|||
| style="text-align:right" | 8 |
|||
| style="text-align:right" | 9 |
|||
|- |
|||
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2 |
|||
| Rotated |
|||
| style="text-align:right; background-color:#cbcefb" | 4 |
|||
| style="text-align:right" | 5 |
|||
| style="text-align:right" | 6 |
|||
| style="text-align:right" | 7 |
|||
| style="text-align:right" | 8 |
|||
| style="text-align:right" | 9 |
|||
| style="text-align:right" | 1 |
|||
| style="text-align:right" | 2 |
|||
| style="text-align:right" | 3 |
|||
|} |
|||
=={{header|F_Sharp|F#}}== |
|||
<syntaxhighlight 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)) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[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]->[] |
|||
</pre> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor"> USING: prettyprint sequences.extras ; |
||
{ 1 2 3 4 5 6 7 8 9 } 3 rotate .</ |
{ 1 2 3 4 5 6 7 8 9 } 3 rotate .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 171: | Line 1,155: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="factor">USING: arrays prettyprint sequences.rotated ; |
||
{ 1 2 3 4 5 6 7 8 9 } 3 <rotated> >array .</ |
{ 1 2 3 4 5 6 7 8 9 } 3 <rotated> >array .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
{ 4 5 6 7 8 9 1 2 3 } |
{ 4 5 6 7 8 9 1 2 3 } |
||
</pre> |
</pre> |
||
=={{header|FreeBASIC}}== |
|||
<syntaxhighlight 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</syntaxhighlight> |
|||
{{out}}<pre>4, 5, 6, 7, 8, 9, 1, 2, 3</pre> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
{{trans|Wren}} |
{{trans|Wren}} |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 205: | Line 1,216: | ||
} |
} |
||
fmt.Println("Shifted left by 3 :", l) |
fmt.Println("Shifted left by 3 :", l) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 211: | Line 1,222: | ||
Original list : [1 2 3 4 5 6 7 8 9] |
Original list : [1 2 3 4 5 6 7 8 9] |
||
Shifted left by 3 : [4 5 6 7 8 9 1 2 3] |
Shifted left by 3 : [4 5 6 7 8 9 1 2 3] |
||
</pre> |
|||
=={{header|Haskell}}== |
|||
<syntaxhighlight lang="haskell">------------- SHIFT LIST ELEMENTS TO LEFT BY N ----------- |
|||
rotated :: Int -> [a] -> [a] |
|||
rotated n = |
|||
( (<*>) take |
|||
. flip (drop . mod n) |
|||
. cycle |
|||
) |
|||
<*> length |
|||
--------------------------- TEST ------------------------- |
|||
main :: IO () |
|||
main = |
|||
let xs = [1 .. 9] |
|||
in putStrLn ("Initial list: " <> show xs <> "\n") |
|||
>> putStrLn "Rotated 3 or 30 positions to the left:" |
|||
>> print (rotated 3 xs) |
|||
>> print (rotated 30 xs) |
|||
>> putStrLn "\nRotated 3 or 30 positions to the right:" |
|||
>> print (rotated (-3) xs) |
|||
>> print (rotated (-30) xs)</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>Initial list: [1,2,3,4,5,6,7,8,9] |
|||
Rotated 3 or 30 positions to the left: |
|||
[4,5,6,7,8,9,1,2,3] |
|||
[4,5,6,7,8,9,1,2,3] |
|||
Rotated 3 or 30 positions to the right: |
|||
[7,8,9,1,2,3,4,5,6] |
|||
[7,8,9,1,2,3,4,5,6]</pre> |
|||
=={{header|J}}== |
|||
<syntaxhighlight lang=J> 3 |. 1 2 3 4 5 6 7 8 9 |
|||
4 5 6 7 8 9 1 2 3</syntaxhighlight> |
|||
However, while this matches the task example, it does not match the task title. In most contexts, a shift is different from a rotate: |
|||
<syntaxhighlight lang=J> 3 |.(!.0) 1 2 3 4 5 6 7 8 9 |
|||
4 5 6 7 8 9 0 0 0</syntaxhighlight> |
|||
=={{header|Java}}== |
|||
<syntaxhighlight 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); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>original: [1, 2, 3, 4, 5, 6, 7, 8, 9] |
|||
rotated: [4, 5, 6, 7, 8, 9, 1, 2, 3]</pre> |
|||
=={{header|JavaScript}}== |
|||
<syntaxhighlight 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(); |
|||
})();</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> 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]</pre> |
|||
=={{header|jq}}== |
|||
{{works with|jq}} |
|||
'''Works with gojq, the Go implementation of jq''' |
|||
<syntaxhighlight lang="jq"># input should be an array or string |
|||
def rotateLeft($n): |
|||
.[$n:] + .[:$n];</syntaxhighlight> |
|||
Examples: |
|||
<pre> |
|||
[1, 2, 3, 4, 5, 6, 7, 8, 9] | rotateLeft(3) #=> [4,5,6,7,8,9,1,2,3] |
|||
"123456789" | rotateLeft(3) #=> "456789123" |
|||
</pre> |
</pre> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">list = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
||
println(list, " => ", circshift(list, -3)) |
println(list, " => ", circshift(list, -3)) |
||
</ |
</syntaxhighlight>{{out}} |
||
<pre> |
<pre> |
||
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [4, 5, 6, 7, 8, 9, 1, 2, 3] |
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [4, 5, 6, 7, 8, 9, 1, 2, 3] |
||
</pre> |
</pre> |
||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
|||
<syntaxhighlight lang="mathematica">RotateLeft[{1, 2, 3, 4, 5, 6, 7, 8, 9}, 3]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>{4, 5, 6, 7, 8, 9, 1, 2, 3}</pre> |
|||
=={{header|Maxima}}== |
|||
<syntaxhighlight lang="maxima"> |
|||
list:[1,2,3,4,5,6,7,8,9]$ |
|||
append(rest(list,3),rest(list,-(length(list)-3))); |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[4,5,6,7,8,9,1,2,3] |
|||
</pre> |
|||
=={{header|Nim}}== |
|||
Using “rotatedLeft” from standard module “algorithm”. Note that its exists also “rotateLeft” for rotation in place. |
|||
<syntaxhighlight lang="nim">import algorithm |
|||
let list = @[1, 2, 3, 4, 5, 6, 7, 8, 9] |
|||
echo list, " → ", rotatedLeft(list, 3)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>@[1, 2, 3, 4, 5, 6, 7, 8, 9] → @[4, 5, 6, 7, 8, 9, 1, 2, 3]</pre> |
|||
=={{header|OCaml}}== |
|||
At the [[REPL]]: |
|||
<syntaxhighlight lang="ocaml"># let rec rotate n = function |
|||
| h :: (_ :: _ as t) when n > 0 -> rotate (pred n) (t @ [h]) |
|||
| l -> l |
|||
;; |
|||
val rotate : int -> 'a list -> 'a list = <fun> |
|||
# rotate 3 [1; 2; 3; 4; 5; 6; 7; 8; 9] ;; |
|||
- : int list = [4; 5; 6; 7; 8; 9; 1; 2; 3]</syntaxhighlight> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">// 20210315 Perl programming solution |
||
use strict; |
use strict; |
||
Line 232: | Line 1,418: | ||
push @list, splice @list, 0, $n; |
push @list, splice @list, 0, $n; |
||
print join ' ', @list, "\n"</ |
print join ' ', @list, "\n"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 239: | Line 1,425: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--<syntaxhighlight lang="phix">--> |
|||
<lang Phix>sequence s = {1,2,3,4,5,6,7,8,9} |
|||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">}</span> |
|||
s = s[4..$]&s[1..3] |
|||
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">..$]&</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span> |
|||
?s</lang> |
|||
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
{4,5,6,7,8,9,1,2,3} |
{4,5,6,7,8,9,1,2,3} |
||
</pre> |
|||
=={{header|PicoLisp}}== |
|||
<syntaxhighlight lang="picolisp">(let L (range 1 9) |
|||
(println (conc (tail -3 L) (head 3 L))) )</syntaxhighlight> |
|||
=={{header|PL/0}}== |
|||
PL/0 has no data structures, not even arrays. This sample simulates an array using separate variables for each element. The simulated array is then used to represent the list. |
|||
<br> |
|||
The output shows the original list (one element per line) and the shifted list, separated by -111. |
|||
<br> |
|||
Note that PL/0 was intended as an educational tool for teaching compiler writing - so, e.g.: adding arrays might be an exercise for the students. |
|||
<syntaxhighlight lang="pascal"> |
|||
const maxlist = 8; |
|||
var sub, v, l1, l2, l3, l4, l5, l6, l7, l8; |
|||
procedure getelement; |
|||
begin |
|||
if sub = 1 then v := l1; |
|||
if sub = 2 then v := l2; |
|||
if sub = 3 then v := l3; |
|||
if sub = 4 then v := l4; |
|||
if sub = 5 then v := l5; |
|||
if sub = 6 then v := l6; |
|||
if sub = 7 then v := l7; |
|||
if sub = 8 then v := l8; |
|||
end; |
|||
procedure setelement; |
|||
begin |
|||
if sub = 1 then l1 := v; |
|||
if sub = 2 then l2 := v; |
|||
if sub = 3 then l3 := v; |
|||
if sub = 4 then l4 := v; |
|||
if sub = 5 then l5 := v; |
|||
if sub = 6 then l6 := v; |
|||
if sub = 7 then l7 := v; |
|||
if sub = 8 then l8 := v; |
|||
end; |
|||
procedure shiftleft; |
|||
var first; |
|||
begin |
|||
sub := 1; |
|||
call getelement; |
|||
first := v; |
|||
sub := 0; |
|||
while sub < maxlist do begin |
|||
sub := sub + 2; |
|||
call getelement; |
|||
sub := sub - 1; |
|||
call setelement |
|||
end; |
|||
sub := maxlist; |
|||
v := first; |
|||
call setelement |
|||
end; |
|||
begin |
|||
sub := 0; |
|||
while sub < maxlist do begin |
|||
sub := sub + 1; |
|||
v := sub; |
|||
call setelement; |
|||
! v |
|||
end; |
|||
call shiftleft; |
|||
call shiftleft; |
|||
call shiftleft; |
|||
! -111; |
|||
sub := 0; |
|||
while sub < maxlist do begin |
|||
sub := sub + 1; |
|||
call getelement; |
|||
! v |
|||
end |
|||
end. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 |
|||
2 |
|||
3 |
|||
4 |
|||
5 |
|||
6 |
|||
7 |
|||
8 |
|||
-111 |
|||
4 |
|||
5 |
|||
6 |
|||
7 |
|||
8 |
|||
1 |
|||
2 |
|||
3 |
|||
</pre> |
</pre> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">def rotate(list, n): |
||
for _ in range(n): |
for _ in range(n): |
||
list.append(list.pop(0)) |
list.append(list.pop(0)) |
||
Line 263: | Line 1,544: | ||
list = [1,2,3,4,5,6,7,8,9] |
list = [1,2,3,4,5,6,7,8,9] |
||
print(list, " => ", rotate(list, 3)) |
print(list, " => ", rotate(list, 3)) |
||
</ |
</syntaxhighlight>{{out}} |
||
<pre> |
<pre> |
||
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [4, 5, 6, 7, 8, 9, 1, 2, 3] |
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [4, 5, 6, 7, 8, 9, 1, 2, 3] |
||
</pre> |
</pre> |
||
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: |
|||
<syntaxhighlight 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()</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>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]</pre> |
|||
=={{header|Quackery}}== |
|||
<syntaxhighlight lang="quackery">' [ 1 2 3 4 5 6 7 8 9 ] 3 split swap join echo</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[ 4 5 6 7 8 9 1 2 3 ]</pre> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
<lang |
<syntaxhighlight lang="raku" line># 20210315 Raku programming solution |
||
say [1..9].rotate(3)</ |
say [1..9].rotate(3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 278: | Line 1,627: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
< |
<syntaxhighlight 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*/ |
parse arg n $ . /*obtain optional arguments from the CL*/ |
||
if n=='' | n=="," then n= 3 /*Not specified? Then use the default.*/ |
if n=='' | n=="," then n= 3 /*Not specified? Then use the default.*/ |
||
Line 288: | Line 1,637: | ||
say 'shifting elements in the list by ' n /*display action used on the input list*/ |
say 'shifting elements in the list by ' n /*display action used on the input list*/ |
||
say ' input list=' $ /* " the input list ───► terminal*/ |
say ' input list=' $ /* " the input list ───► terminal*/ |
||
say 'output list=' $$ /* " the output " " " */</ |
say 'output list=' $$ /* " the output " " " */</syntaxhighlight> |
||
{{out|output|text= when using the default inputs:}} |
{{out|output|text= when using the default inputs:}} |
||
<pre> |
<pre> |
||
Line 297: | Line 1,646: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
see "working..." + nl |
see "working..." + nl |
||
Line 334: | Line 1,683: | ||
txt = txt + "]" |
txt = txt + "]" |
||
see txt |
see txt |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 343: | Line 1,692: | ||
[4, 5, 6, 7, 8, 9, 1, 2, 3] |
[4, 5, 6, 7, 8, 9, 1, 2, 3] |
||
done... |
done... |
||
</pre> |
|||
=={{header|RPL}}== |
|||
====Using the stack (idiomatic)==== |
|||
≪ LIST→ → size |
|||
≪ <span style="color:red">1 3</span> '''START''' size ROLL '''NEXT''' |
|||
size →LIST |
|||
≫ ≫ '<span style="color:blue">SLL3</span>' STO |
|||
====Following ''Programming Pearls''' Problem B algorithm==== |
|||
{{works with|HP|48G}} |
|||
≪ <span style="color:red">3</span> DUP2 <span style="color:red">1</span> SWAP SUB REVLIST |
|||
ROT ROT <span style="color:red">1</span> + OVER SIZE SUB REVLIST |
|||
+ REVLIST |
|||
≫ ‘<span style="color:blue">SLL3</span>’ STO |
|||
{ 1 2 3 4 5 6 7 8 } <span style="color:blue">SLL3</span> |
|||
{{out}} |
|||
<pre> |
|||
1: { 4 5 6 7 8 1 2 3 } |
|||
</pre> |
|||
=={{header|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. |
|||
<syntaxhighlight lang="ruby">list = [1,2,3,4,5,6,7,8,9] |
|||
p list.rotate(3) |
|||
</syntaxhighlight>{{out}} |
|||
<pre> |
|||
[4, 5, 6, 7, 8, 9, 1, 2, 3] |
|||
</pre> |
</pre> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn main() { |
||
let mut v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; |
let mut v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; |
||
println!("Before: {:?}", v); |
println!("Before: {:?}", v); |
||
v.rotate_left(3); |
v.rotate_left(3); |
||
println!(" After: {:?}", v); |
println!(" After: {:?}", v); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 358: | Line 1,736: | ||
After: [4, 5, 6, 7, 8, 9, 1, 2, 3] |
After: [4, 5, 6, 7, 8, 9, 1, 2, 3] |
||
</pre> |
</pre> |
||
=={{header|Scheme}}== |
|||
{{works with|Chez Scheme}} |
|||
<syntaxhighlight lang="scheme">; Rotate a list by the given number of elements. |
|||
; Positive = Rotate left; Negative = Rotate right. |
|||
(define list-rotate |
|||
(lambda (lst n) |
|||
(cond |
|||
((or (not (pair? lst)) (= n 0)) |
|||
lst) |
|||
((< n 0) |
|||
(let ((end (1- (length lst)))) |
|||
(list-rotate (append (list (list-ref lst end)) (list-head lst end)) (1+ n)))) |
|||
(else |
|||
(list-rotate (cdr (append lst (list (car lst)))) (1- n))))))</syntaxhighlight> |
|||
{{out}} |
|||
<pre>(list-rotate '(1 2 3 4 5 6 7 8 9) 3) --> (4 5 6 7 8 9 1 2 3) |
|||
(list-rotate '(1 2 3 4 5 6 7 8 9) -3) --> (7 8 9 1 2 3 4 5 6)</pre> |
|||
=={{header|sed}}== |
|||
<syntaxhighlight lang="sed"># rotate in 3 steps to easily work with lengths < 4 |
|||
s/^\([^,]*\),\(.*\)/\2,\1/ |
|||
s/^\([^,]*\),\(.*\)/\2,\1/ |
|||
s/^\([^,]*\),\(.*\)/\2,\1/</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ echo 1,2,3,4,5,6,7,8,9 | sed -f rotate.sed |
|||
4,5,6,7,8,9,1,2,3</pre> |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="wren">// in place left shift by 1 |
||
var lshift = Fn.new { |l| |
var lshift = Fn.new { |l| |
||
var n = l.count |
var n = l.count |
||
Line 372: | Line 1,778: | ||
System.print("Original list : %(l)") |
System.print("Original list : %(l)") |
||
for (i in 1..3) lshift.call(l) |
for (i in 1..3) lshift.call(l) |
||
System.print("Shifted left by 3 : %(l)")</ |
System.print("Shifted left by 3 : %(l)")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 378: | Line 1,784: | ||
Original list : [1, 2, 3, 4, 5, 6, 7, 8, 9] |
Original list : [1, 2, 3, 4, 5, 6, 7, 8, 9] |
||
Shifted left by 3 : [4, 5, 6, 7, 8, 9, 1, 2, 3] |
Shifted left by 3 : [4, 5, 6, 7, 8, 9, 1, 2, 3] |
||
</pre> |
|||
<br> |
|||
{{libheader|Wren-seq}} |
|||
Alternatively, using a library method to produce the same output as before. |
|||
<syntaxhighlight lang="wren">import "./seq" for Lst |
|||
var l = (1..9).toList |
|||
System.print("Original list : %(l)") |
|||
System.print("Shifted left by 3 : %(Lst.lshift(l, 3))")</syntaxhighlight> |
|||
=={{header|XPL0}}== |
|||
<syntaxhighlight lang="xpl0">int A, N, T, I; |
|||
[A:= [1, 2, 3, 4, 5, 6, 7, 8, 9]; |
|||
for N:= 1 to 3 do \rotate A left 3 places |
|||
[T:= A(0); |
|||
for I:= 0 to 9-2 do A(I):= A(I+1); |
|||
A(I):= T]; |
|||
for I:= 0 to 9-2 do |
|||
[IntOut(0, A(I)); Text(0, ", ")]; |
|||
IntOut(0, A(I)); |
|||
]</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
4, 5, 6, 7, 8, 9, 1, 2, 3 |
|||
</pre> |
|||
=={{header|Z80 Assembly}}== |
|||
===Zilog Z80=== |
|||
This example code will not work on the Game Boy, as the Game Boy does not have the <code>RLD</code> or <code>RRD</code> instructions. |
|||
The <code>RLD</code> instruction is a very peculiar one. It rotates leftward the bottom four bits of the accumulator with the byte pointed to by HL. For example, if <code>A = &36</code> and <code>(HL) = &BF</code>, then a single <code>RLD</code> will result in <code>A = &3B</code> and <code>(HL) = &F6</code>. As it turns out, this can be used to rotate the entries in an array without using a ton of stack space. |
|||
<syntaxhighlight lang="z80">PrintChar equ &BB5A ;address of Amstrad CPC firmware routine, writes accumulator to stdout. |
|||
org &1000 |
|||
ld hl,myarray_end-1 ;HL must point to the last byte in the array. |
|||
ld b,9 ;byte count |
|||
call RLCA_RANGE |
|||
ld hl,myarray_end-1 |
|||
ld b,9 |
|||
call RLCA_RANGE |
|||
ld hl,myarray_end-1 |
|||
ld b,9 |
|||
call RLCA_RANGE |
|||
ld hl,myarray |
|||
jp PrintString |
|||
;ret |
|||
myarray: |
|||
;pre-convert these numbers to ascii so that the job is easier. |
|||
byte &31,&32,&33,&34,&35,&36,&37,&38,&39 |
|||
myarray_end: |
|||
byte 0 ;null terminator |
|||
RLCA_RANGE: ;DOESN'T WORK ON GAME BOY |
|||
;rotates a range of memory, e.g. &1000 = &23,&45,&67,&89 > &45,&67,&89,&23 |
|||
;point HL at the end of the memory range this time. |
|||
ld a,(hl) |
|||
push hl |
|||
push bc |
|||
loop_RLCA_RANGE_FIRST: |
|||
RLD |
|||
DEC HL |
|||
djnz loop_RLCA_RANGE_FIRST |
|||
pop bc |
|||
pop hl |
|||
push hl |
|||
push bc |
|||
loop_RLCA_RANGE_SECOND: |
|||
RLD |
|||
DEC HL |
|||
djnz loop_RLCA_RANGE_SECOND |
|||
pop bc |
|||
pop hl |
|||
RLD |
|||
ret |
|||
PrintString: |
|||
ld a,(hl) |
|||
or a |
|||
ret z |
|||
call PrintChar |
|||
inc hl |
|||
jr PrintString</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
456789123 |
|||
</pre> |
</pre> |
Latest revision as of 21:19, 22 July 2024
- 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]
11l
F rotate(l, n)
V k = (l.len + n) % l.len
R l[k ..] [+] l[0 .< k]
V l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(l‘ => ’rotate(l, 3))
- Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [4, 5, 6, 7, 8, 9, 1, 2, 3]
Action!
PROC PrintArray(INT ARRAY a INT size)
INT i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
PROC ShiftLeft(INT ARRAY a INT size)
INT i,j,tmp
tmp=a(0)
FOR i=0 TO size-2
DO
a(i)=a(i+1)
OD
a(size-1)=tmp
RETURN
PROC ShiftLeftNTimes(INT ARRAY a INT size,times)
INT i
FOR i=1 TO times
DO
ShiftLeft(a,size)
OD
RETURN
PROC Test(INT ARRAY a INT size,offset)
PrintArray(a,size)
ShiftLeftNTimes(a,size,3)
PrintArray(a,size)
RETURN
PROC Main()
INT ARRAY a=[1 2 3 4 5 6 7 8 9]
Test(a,9,-3)
RETURN
- Output:
Screenshot from Atari 8-bit computer
[1 2 3 4 5 6 7 8 9] [4 5 6 7 8 9 1 2 3]
Ada
Using slices and array concatenation.
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;
- Output:
1 2 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3
ALGOL 68
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( ( "[" ) );
IF LWB v <= UPB v THEN
print( ( whole( v[ LWB v ], 0 ) ) );
FOR i FROM LWB v + 1 TO UPB v DO
print( ( "," , whole( v[ i ], 0 ) ) )
OD
FI;
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
- Output:
[1,2,3,4,5,6,7,8,9] -> [4,5,6,7,8,9,1,2,3]
ALGOL W
begin
% increments a and returns the new value %
integer procedure inc ( integer value result a ) ; begin a := a + 1; a end;
% shifts in place the elements of a left by n, a must have bounds lb::ub %
procedure rotateLeft ( integer array a ( * ); integer value lb, ub, n ) ;
if n < ( ub - lb ) and n > 0 then begin
% the amount to shift is less than the length of the array %
integer array shifted ( 1 :: n );
integer aPos;
for i := 0 until n - 1 do shifted( i ) := a( lb + i );
for i := lb until ub - n do a( i ) := a( i + n );
aPos := ub - n;
for i := 0 until n - 1 do a( inc( aPos ) ) := shifted( i );
end rotateLeft ;
% prints the elements of v from lb to ub %
procedure printArray ( integer array v ( * ); integer value lb, ub ) ;
begin
writeon( s_w := 0, "[" );
if lb <= ub then begin
writeon( i_w := 1, s_w := 0, v( lb ) );
for i := lb + 1 until ub do writeon( i_w := 1, s_w := 0, "," , v( i ) )
end;
writeon( s_w := 0, "]" )
end printArray ;
begin
integer array v ( 1 :: 9 );
for i := 1 until 9 do v( i ) := i;
printArray( v, 1, 9 );
writeon( " -> " );
rotateLeft( v, 1, 9, 3 );
printArray( v, 1, 9 );
write()
end
end.
- Output:
[1,2,3,4,5,6,7,8,9] -> [4,5,6,7,8,9,1,2,3]
AppleScript
Functional
Prefix appended
------------- SHIFT LIST ELEMENTS TO LEFT BY 3 -----------
-- rotated :: Int -> [a] -> [a]
on rotated(n, xs)
if 0 ≠ n then
set m to |mod|(n, length of xs)
(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
- 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}
Cycle sampled
Another approach: drawing from an infinite list of cycles:
------------- SHIFT LIST ELEMENTS TO LEFT BY 3 -----------
-- rotated :: Int -> [a] -> [a]
on rotated(n, xs)
set m to length of xs
take(m, drop(|mod|(n, m), cycle(xs)))
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)), ¬
" " & showList(rotated(30, xs)), ¬
" Rotated 3 right: " & showList(rotated(-3, xs)), ¬
" " & showList(rotated(-30, xs))})
end run
------------------------- GENERIC ------------------------
-- cycle :: [a] -> Generator [a]
on cycle(xs)
script
property lng : 1 + (length of xs)
property i : missing value
on |λ|()
if missing value is i then
set i to 1
else
set nxt to (1 + i) mod lng
if 0 = ((1 + i) mod lng) then
set i to 1
else
set i to nxt
end if
end if
return item i of xs
end |λ|
end script
end cycle
-- drop :: Int -> [a] -> [a]
-- drop :: Int -> String -> String
on drop(n, xs)
set c to class of xs
if script is not c then
if string is not c then
if n < length of xs then
items (1 + n) thru -1 of xs
else
{}
end if
else
if n < length of xs then
text (1 + n) thru -1 of xs
else
""
end if
end if
else
take(n, xs) -- consumed
return xs
end if
end drop
-- 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
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
set lng to length of xs
if 0 < n and 0 < lng then
items 1 thru min(n, lng) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
------------------------ 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
- Output:
Input list: {1, 2, 3, 4, 5, 6, 7, 8, 9} Rotated 3 left: {4, 5, 6, 7, 8, 9, 1, 2, 3} {4, 5, 6, 7, 8, 9, 1, 2, 3} Rotated 3 right: {7, 8, 9, 1, 2, 3, 4, 5, 6} {7, 8, 9, 1, 2, 3, 4, 5, 6}
Two in-place alternatives
Fewest moves:
(* List range 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 range's leftmost 'amount' items.
Move the range's other items 'amount' places to the left.
Move the stored items into the range's rightmost slots.
*)
on rotate(theList, l, r, amount)
set listLength to (count theList)
if (listLength < 2) then return
if (l < 0) then set l to listLength + l + 1
if (r < 0) then set r to listLength + r + 1
if (l > r) then set {l, r} to {r, l}
script o
property lst : theList
property storage : missing value
end script
set rangeLength to r - l + 1
set amount to (rangeLength + rangeLength - amount) mod rangeLength
if (amount is 0) then return
set o's storage to o's lst's items l thru (l + amount - 1)
repeat with i from (l + amount) to r
set o's lst's item (i - amount) to o's lst's item i
end repeat
set j to r - amount
repeat with i from 1 to amount
set o's lst's item (j + i) to o's storage's item i
end repeat
end rotate
-- Task code:
local lst
set lst to {1, 2, 3, 4, 5, 6, 7, 8, 9}
-- Left-rotate all items (1 thru -1) by three places.
rotate(lst, 1, -1, -3)
return lst
Wholly in-place:
(* List range 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 range's leftmost 'amount' items, reverse the others, then reverse the lot.
*)
on rotate(theList, l, r, amount)
set listLength to (count theList)
if (listLength < 2) then return
if (l < 0) then set l to listLength + l + 1
if (r < 0) then set r to listLength + r + 1
if (l > r) then set {l, r} to {r, l}
script o
property lst : theList
on rotate1(a, z, step)
set v to my lst's item a
repeat with i from (a + step) to z by step
set my lst's item (i - step) to my lst's item i
end repeat
set my lst's item z to v
end rotate1
on |reverse|(i, j)
repeat with i from i to ((i + j - 1) div 2)
set v to my lst's item i
set my lst's item i to my lst's item j
set my lst's item j to v
set j to j - 1
end repeat
end |reverse|
end script
set rangeLength to r - l + 1
set amount to (rangeLength + rangeLength - amount) mod rangeLength
if (amount is 1) then
tell o to rotate1(l, r, 1) -- Rotate left by 1.
else if (amount = rangeLength - 1) then
tell o to rotate1(r, l, -1) -- Rotate right by 1.
else if (amount > 0) then
tell o to |reverse|(l, l + amount - 1)
tell o to |reverse|(l + amount, r)
tell o to |reverse|(l, r)
end if
end rotate
-- Task code:
local lst
set lst to {1, 2, 3, 4, 5, 6, 7, 8, 9}
-- Left-rotate all items (1 thru -1) by three places.
rotate(lst, 1, -1, -3)
return lst
Result in both cases:
- Output:
{4, 5, 6, 7, 8, 9, 1, 2, 3}
Arturo
lst: [1 2 3 4 5 6 7 8 9]
print rotate.left lst 3
- Output:
4 5 6 7 8 9 1 2 3
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
}
Examples:
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
- Output:
output1 = [4, 5, 6, 7, 8, 9, 1, 2, 3] output2 = [7, 8, 9, 1, 2, 3, 4, 5, 6]
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)
}
- 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
BASIC
BASIC256
arraybase 1
global lista
dim lista(9)
lista[1] = 1
lista[2] = 2
lista[3] = 3
lista[4] = 4
lista[5] = 5
lista[6] = 6
lista[7] = 7
lista[8] = 8
lista[9] = 9
subroutine shiftLeft (lista)
lo = lista[?,]
hi = lista[?]
first = lista[lo]
for i = lo to hi-1
lista[i] = lista[i + 1]
next i
lista[hi] = first
end subroutine
subroutine shiftLeftN (lista, n)
for i = 1 to n
call shiftLeft(lista)
next i
end subroutine
call shiftLeftN(lista, 3)
for i = 1 to 9
print lista[i];
if i < 9 then print ", ";
next i
end
- Output:
Igual que la entrada de FreeBASIC.
PureBasic
Global Dim lista.i(9)
DataSection
Data.i 1,2,3,4,5,6,7,8,9
EndDataSection
For i.i = 1 To 9
Read lista(i)
Next i
Procedure shiftLeft (lista)
;shifts list left by one step
lo.i = 1 ;ArraySize(lista(), 1)
hi.i = ArraySize(lista())
first.i = lista(lo)
For i.i = lo To hi-1
lista(i) = lista(i + 1)
Next i
lista(hi) = first
EndProcedure
Procedure shiftLeftN (lista, n)
For i.i = 1 To n
shiftLeft(lista)
Next i
EndProcedure
OpenConsole()
shiftLeftN(lista, 3)
For i.i = 1 To 9
Print(Str(lista(i)))
If i < 9 : Print(", ") : EndIf
Next i
Input()
CloseConsole()
- Output:
Igual que la entrada de FreeBASIC.
QBasic
DIM SHARED lista(1 TO 9)
DATA 1,2,3,4,5,6,7,8,9
FOR i = 1 TO 9
READ lista(i)
NEXT i
SUB shiftLeft (lista())
lo = LBOUND(lista)
hi = UBOUND(lista)
first = lista(lo)
FOR i = lo TO hi
lista(i) = lista(i + 1)
NEXT i
lista(hi) = first
END SUB
SUB shiftLeftN (lista(), n)
FOR i = 1 TO n
CALL shiftLeft(lista())
NEXT i
END SUB
CALL shiftLeftN(lista(), 3)
FOR i = 1 TO 9
PRINT lista(i);
IF i < 9 THEN PRINT ", ";
NEXT i
END
- Output:
Igual que la entrada de FreeBASIC.
BQN
data ← 1 + ↕9
3 ⌽ data
- Output:
⟨ 4 5 6 7 8 9 1 2 3 ⟩
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;
}
- 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++
#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);
}
- Output:
Before: 1 2 3 4 5 6 7 8 9 After: 4 5 6 7 8 9 1 2 3
CLU
% Shift an array left by a certain amount
shift_left = proc [T: type] (a: array[T], n: int)
at = array[T]
% shifting an empty array is a no-op
if at$empty(a) then return end
% otherwise we take elements from the bottom
% and put them at the top
low: int := at$low(a)
for i: int in int$from_to(1, n) do
at$addh(a, at$reml(a))
end
at$set_low(a, low)
end shift_left
show = proc (s: stream, a: array[int])
for i: int in array[int]$elements(a) do
stream$puts(s, int$unparse(i) || " ")
end
stream$putc(s,'\n')
end show
start_up = proc ()
po: stream := stream$primary_output()
arr: array[int] := array[int]$[1,2,3,4,5,6,7,8,9]
stream$puts(po, "Before: ") show(po, arr)
shift_left[int](arr, 3)
stream$puts(po, " After: ") show(po, arr)
end start_up
- Output:
Before: 1 2 3 4 5 6 7 8 9 After: 4 5 6 7 8 9 1 2 3
Common Lisp
;; Load the alexandria library from the quicklisp repository
CL-USER> (ql:quickload "alexandria")
CL-USER> (alexandria:rotate '(1 2 3 4 5 6 7 8 9) -3)
(4 5 6 7 8 9 1 2 3)
Delphi
Boost.Int is part of DelphiBoostLib.
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.
- 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]
EasyLang
func[] rotate a[] n .
for i to len a[]
r[] &= a[(i + n) mod1 len a[]]
.
return r[]
.
print rotate [ 1 2 3 4 5 6 7 8 9 ] 3
- Output:
[ 4 5 6 7 8 9 1 2 3 ]
ed
Port of #sed version.
H
g/.*/s/^\([^,]*\),\(.*\)/\2,\1/
g/.*/s/^\([^,]*\),\(.*\)/\2,\1/
g/.*/s/^\([^,]*\),\(.*\)/\2,\1/
,p
Q
- Output:
$ ed -s rotate.input < rotate.ed Newline appended 4,5,6,7,8,9,1,2,3
Elixir
def rotate(enumerable, count) do
{left, right} = Enum.split(enumerable, count)
right ++ left
end
rotate(1..9, 3)
# [4, 5, 6, 7, 8, 9, 1, 2, 3]
Euler
begin new shl; new shl3; shl <- ` formal ls; if length ls < 2 then ls else begin new L; L <- ls; tail L & ( L[ 1 ] ) end '; shl3 <- ` formal ls; shl( shl( shl( ls ) ) ) '; out shl3( ( 1, 2, 3, 4, 5, 6, 7, 8 ) ) end $
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)
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
)
)
)
)
- 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 |
Or, in terms of the MAKEARRAY function:
rotated
=LAMBDA(n,
LAMBDA(xs,
LET(
nCols, COLUMNS(xs),
m, MOD(n, nCols),
d, nCols - m,
MAKEARRAY(
1, nCols,
LAMBDA(
_, x,
IF(d < x,
x - d,
m + x
)
)
)
)
)
)
- Output:
fx | =rotated(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#
// 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))
- 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
USING: prettyprint sequences.extras ;
{ 1 2 3 4 5 6 7 8 9 } 3 rotate .
- 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.
USING: arrays prettyprint sequences.rotated ;
{ 1 2 3 4 5 6 7 8 9 } 3 <rotated> >array .
- Output:
{ 4 5 6 7 8 9 1 2 3 }
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
- Output:
4, 5, 6, 7, 8, 9, 1, 2, 3
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)
}
- 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
------------- SHIFT LIST ELEMENTS TO LEFT BY N -----------
rotated :: Int -> [a] -> [a]
rotated n =
( (<*>) take
. flip (drop . mod n)
. cycle
)
<*> length
--------------------------- TEST -------------------------
main :: IO ()
main =
let xs = [1 .. 9]
in putStrLn ("Initial list: " <> show xs <> "\n")
>> putStrLn "Rotated 3 or 30 positions to the left:"
>> print (rotated 3 xs)
>> print (rotated 30 xs)
>> putStrLn "\nRotated 3 or 30 positions to the right:"
>> print (rotated (-3) xs)
>> print (rotated (-30) xs)
- Output:
Initial list: [1,2,3,4,5,6,7,8,9] Rotated 3 or 30 positions to the left: [4,5,6,7,8,9,1,2,3] [4,5,6,7,8,9,1,2,3] Rotated 3 or 30 positions to the right: [7,8,9,1,2,3,4,5,6] [7,8,9,1,2,3,4,5,6]
J
3 |. 1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
However, while this matches the task example, it does not match the task title. In most contexts, a shift is different from a rotate:
3 |.(!.0) 1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 0 0 0
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);
}
}
- Output:
original: [1, 2, 3, 4, 5, 6, 7, 8, 9] rotated: [4, 5, 6, 7, 8, 9, 1, 2, 3]
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();
})();
- 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
# input should be an array or string
def rotateLeft($n):
.[$n:] + .[:$n];
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
list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
println(list, " => ", circshift(list, -3))
- Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9] => [4, 5, 6, 7, 8, 9, 1, 2, 3]
Mathematica /Wolfram Language
RotateLeft[{1, 2, 3, 4, 5, 6, 7, 8, 9}, 3]
- Output:
{4, 5, 6, 7, 8, 9, 1, 2, 3}
Maxima
list:[1,2,3,4,5,6,7,8,9]$
append(rest(list,3),rest(list,-(length(list)-3)));
- Output:
[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.
import algorithm
let list = @[1, 2, 3, 4, 5, 6, 7, 8, 9]
echo list, " → ", rotatedLeft(list, 3)
- Output:
@[1, 2, 3, 4, 5, 6, 7, 8, 9] → @[4, 5, 6, 7, 8, 9, 1, 2, 3]
OCaml
At the REPL:
# let rec rotate n = function
| h :: (_ :: _ as t) when n > 0 -> rotate (pred n) (t @ [h])
| l -> l
;;
val rotate : int -> 'a list -> 'a list = <fun>
# rotate 3 [1; 2; 3; 4; 5; 6; 7; 8; 9] ;;
- : int list = [4; 5; 6; 7; 8; 9; 1; 2; 3]
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"
- 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}
PicoLisp
(let L (range 1 9)
(println (conc (tail -3 L) (head 3 L))) )
PL/0
PL/0 has no data structures, not even arrays. This sample simulates an array using separate variables for each element. The simulated array is then used to represent the list.
The output shows the original list (one element per line) and the shifted list, separated by -111.
Note that PL/0 was intended as an educational tool for teaching compiler writing - so, e.g.: adding arrays might be an exercise for the students.
const maxlist = 8;
var sub, v, l1, l2, l3, l4, l5, l6, l7, l8;
procedure getelement;
begin
if sub = 1 then v := l1;
if sub = 2 then v := l2;
if sub = 3 then v := l3;
if sub = 4 then v := l4;
if sub = 5 then v := l5;
if sub = 6 then v := l6;
if sub = 7 then v := l7;
if sub = 8 then v := l8;
end;
procedure setelement;
begin
if sub = 1 then l1 := v;
if sub = 2 then l2 := v;
if sub = 3 then l3 := v;
if sub = 4 then l4 := v;
if sub = 5 then l5 := v;
if sub = 6 then l6 := v;
if sub = 7 then l7 := v;
if sub = 8 then l8 := v;
end;
procedure shiftleft;
var first;
begin
sub := 1;
call getelement;
first := v;
sub := 0;
while sub < maxlist do begin
sub := sub + 2;
call getelement;
sub := sub - 1;
call setelement
end;
sub := maxlist;
v := first;
call setelement
end;
begin
sub := 0;
while sub < maxlist do begin
sub := sub + 1;
v := sub;
call setelement;
! v
end;
call shiftleft;
call shiftleft;
call shiftleft;
! -111;
sub := 0;
while sub < maxlist do begin
sub := sub + 1;
call getelement;
! v
end
end.
- Output:
1 2 3 4 5 6 7 8 -111 4 5 6 7 8 1 2 3
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))
- 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:
'''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()
- 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
' [ 1 2 3 4 5 6 7 8 9 ] 3 split swap join echo
- Output:
[ 4 5 6 7 8 9 1 2 3 ]
Raku
# 20210315 Raku programming solution
say [1..9].rotate(3)
- Output:
(4 5 6 7 8 9 1 2 3)
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 " " " */
- 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
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
- 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...
RPL
Using the stack (idiomatic)
≪ LIST→ → size ≪ 1 3 START size ROLL NEXT size →LIST ≫ ≫ 'SLL3' STO
Following Programming Pearls' Problem B algorithm
≪ 3 DUP2 1 SWAP SUB REVLIST ROT ROT 1 + OVER SIZE SUB REVLIST + REVLIST ≫ ‘SLL3’ STO
{ 1 2 3 4 5 6 7 8 } SLL3
- Output:
1: { 4 5 6 7 8 1 2 3 }
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.
list = [1,2,3,4,5,6,7,8,9]
p list.rotate(3)
- Output:
[4, 5, 6, 7, 8, 9, 1, 2, 3]
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);
}
- Output:
Before: [1, 2, 3, 4, 5, 6, 7, 8, 9] After: [4, 5, 6, 7, 8, 9, 1, 2, 3]
Scheme
; Rotate a list by the given number of elements.
; Positive = Rotate left; Negative = Rotate right.
(define list-rotate
(lambda (lst n)
(cond
((or (not (pair? lst)) (= n 0))
lst)
((< n 0)
(let ((end (1- (length lst))))
(list-rotate (append (list (list-ref lst end)) (list-head lst end)) (1+ n))))
(else
(list-rotate (cdr (append lst (list (car lst)))) (1- n))))))
- Output:
(list-rotate '(1 2 3 4 5 6 7 8 9) 3) --> (4 5 6 7 8 9 1 2 3) (list-rotate '(1 2 3 4 5 6 7 8 9) -3) --> (7 8 9 1 2 3 4 5 6)
sed
# rotate in 3 steps to easily work with lengths < 4
s/^\([^,]*\),\(.*\)/\2,\1/
s/^\([^,]*\),\(.*\)/\2,\1/
s/^\([^,]*\),\(.*\)/\2,\1/
- Output:
$ echo 1,2,3,4,5,6,7,8,9 | sed -f rotate.sed 4,5,6,7,8,9,1,2,3
Wren
// 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)")
- 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]
Alternatively, using a library method to produce the same output as before.
import "./seq" for Lst
var l = (1..9).toList
System.print("Original list : %(l)")
System.print("Shifted left by 3 : %(Lst.lshift(l, 3))")
XPL0
int A, N, T, I;
[A:= [1, 2, 3, 4, 5, 6, 7, 8, 9];
for N:= 1 to 3 do \rotate A left 3 places
[T:= A(0);
for I:= 0 to 9-2 do A(I):= A(I+1);
A(I):= T];
for I:= 0 to 9-2 do
[IntOut(0, A(I)); Text(0, ", ")];
IntOut(0, A(I));
]
- Output:
4, 5, 6, 7, 8, 9, 1, 2, 3
Z80 Assembly
Zilog Z80
This example code will not work on the Game Boy, as the Game Boy does not have the RLD
or RRD
instructions.
The RLD
instruction is a very peculiar one. It rotates leftward the bottom four bits of the accumulator with the byte pointed to by HL. For example, if A = &36
and (HL) = &BF
, then a single RLD
will result in A = &3B
and (HL) = &F6
. As it turns out, this can be used to rotate the entries in an array without using a ton of stack space.
PrintChar equ &BB5A ;address of Amstrad CPC firmware routine, writes accumulator to stdout.
org &1000
ld hl,myarray_end-1 ;HL must point to the last byte in the array.
ld b,9 ;byte count
call RLCA_RANGE
ld hl,myarray_end-1
ld b,9
call RLCA_RANGE
ld hl,myarray_end-1
ld b,9
call RLCA_RANGE
ld hl,myarray
jp PrintString
;ret
myarray:
;pre-convert these numbers to ascii so that the job is easier.
byte &31,&32,&33,&34,&35,&36,&37,&38,&39
myarray_end:
byte 0 ;null terminator
RLCA_RANGE: ;DOESN'T WORK ON GAME BOY
;rotates a range of memory, e.g. &1000 = &23,&45,&67,&89 > &45,&67,&89,&23
;point HL at the end of the memory range this time.
ld a,(hl)
push hl
push bc
loop_RLCA_RANGE_FIRST:
RLD
DEC HL
djnz loop_RLCA_RANGE_FIRST
pop bc
pop hl
push hl
push bc
loop_RLCA_RANGE_SECOND:
RLD
DEC HL
djnz loop_RLCA_RANGE_SECOND
pop bc
pop hl
RLD
ret
PrintString:
ld a,(hl)
or a
ret z
call PrintChar
inc hl
jr PrintString
- Output:
456789123
- Draft Programming Tasks
- 11l
- Action!
- Ada
- ALGOL 68
- ALGOL W
- AppleScript
- Arturo
- AutoHotkey
- AWK
- BASIC
- BASIC256
- PureBasic
- QBasic
- BQN
- C
- C++
- CLU
- Common Lisp
- Delphi
- System.SysUtils
- Boost.Int
- EasyLang
- Ed
- Elixir
- Euler
- Excel
- F Sharp
- Factor
- FreeBASIC
- Go
- Haskell
- J
- Java
- JavaScript
- Jq
- Julia
- Mathematica
- Wolfram Language
- Maxima
- Nim
- OCaml
- Perl
- Phix
- PicoLisp
- PL/0
- Python
- Quackery
- Raku
- REXX
- Ring
- RPL
- Ruby
- Rust
- Scheme
- Sed
- Wren
- Wren-seq
- XPL0
- Z80 Assembly