August 23, 2024

P19 - Rotate a list N places to the left.

Examples:

>p19:rotate(3, [1,2,3,4,5,6,7]). 
    [4,5,6,7,1,2,3]
    > p19:rotate(-3, [1,2,3,4,5,6,7]).
    [5,6,7,1,2,3,4]

erlang

%Rotate a list N places to the left.
-module(p19).
-export([rotate/2]).

rotate(N, Ls) ->
    if
        N > 0 ->
            [A, B] = p17:split(N, Ls),
            B ++ A;
        N < 0 ->
            Len = length(Ls),
            Index = Len + N,
            [A, B] = p17:split(Index, Ls),
            B ++ A
    end.
Be first to comment
Leave a reply