Programming Search⌘K

Taskintro

Rotate a list

Also called rotate an array, left rotation, circular shift, cyclic shift, shift a list, rotate left.

Move the first k items of a list to its end, keep the order of the other items, and make a k that is larger than the list work.

Task

Rotate a list of integers to the left by k positions. The function rotate_left(items, k) moves the first k items to the end, and keeps the order of the other items. For example, rotate_left([1, 2, 3, 4, 5], 2) is [3, 4, 5, 1, 2].

The function returns a new list, and the input does not change. k is 0 or more, and it can be larger than the length of the list. A rotation by the length of the list gives the same list, so the function uses the remainder of k divided by the length. An empty list gives an empty list for each k.

Solutions

Language Rotate to the left by k
Python items[s:] + items[:s], with s = k % len(items)
JavaScript, TypeScript [...items.slice(s), ...items.slice(0, s)]
Java two System.arraycopy calls into a new array
C# [.. items[s..], .. items[..s]]
Go slices.Concat(items[s:], items[:s])
Rust rotate_left(k % v.len()) on items.to_vec()
C out[i] = items[(i + s) % n] for each index
C++ std::ranges::rotate on a copy
Bash "${items[@]:s}" "${items[@]:0:s}"
  • Each language. Each solution first checks for an empty list, because the remainder of a division by 0 is not defined. Then it computes s, the remainder of k divided by the length.
  • C#. "The start of the range is inclusive, but the end of the range is exclusive"1. Thus items[..s] is the first s items, and items[s..] is the other items.
  • Rust. After rotate_left(mid), "the element previously at index mid will become the first element in the slice"2. The rotation is in place, so the solution rotates a copy.
  • C++. std::rotate "Performs a left rotation on the target range [first, last)"3. The middle iterator is the item that becomes the first item.
  • Bash. ${items[@]:s} expands to the items from index s to the end, and ${items[@]:0:s} expands to the first s items.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • zero and full-turn: a rotation by 0 or by the length gives the same list.
  • more-than-length and much-larger: a rotation by 4 of a list of 3 items is a rotation by 1. A k of 2000000000 also works, because the remainder is 2.
  • empty and empty-zero: an empty list gives an empty list. A division by its length 0 is not possible, so the solutions check for it first.
  • single: a list of one item does not change.
  • duplicates and negative-items: the values of the items do not change the rotation.

Pitfalls

  • Python deque.rotate rotates to the right. "Rotate the deque n steps to the right. If n is negative, rotate to the left."4 For a left rotation by k, give -k:
from collections import deque

d = deque([1, 2, 3, 4, 5])
d.rotate(2)
print(list(d))
d = deque([1, 2, 3, 4, 5])
d.rotate(-2)
print(list(d))
Output
[4, 5, 1, 2, 3]
[3, 4, 5, 1, 2]
  • JavaScript % can give a negative result. The remainder "always takes the sign of the dividend"5. For a negative k, k % n is negative. If a negative k is a right rotation, use ((k % n) + n) % n:
const n = 3;
const k = -1;
console.log(k % n);
console.log(((k % n) + n) % n);
Output
-1
2
  • Java Collections.rotate rotates to the right. After the call, "the element at index i will be the element previously at index (i - distance) mod list.size()"6. Thus a positive distance moves the items to the right. For a left rotation by k, give -k:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> right = new ArrayList<>(List.of(1, 2, 3, 4, 5));
    Collections.rotate(right, 2);
    System.out.println(right);
    List<Integer> left = new ArrayList<>(List.of(1, 2, 3, 4, 5));
    Collections.rotate(left, -2);
    System.out.println(left);
  }
}
Output
[4, 5, 1, 2, 3]
[3, 4, 5, 1, 2]
  • C# a range past the end throws. In the example, items[4..] on an array of 3 items throws an ArgumentOutOfRangeException. Use the remainder of k first:
using System;

int[] items = [1, 2, 3];
int k = 4;
try
{
    int[] rest = items[k..];
    Console.WriteLine(rest.Length);
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine(e.GetType().Name);
}
int s = k % items.Length;
Console.WriteLine(string.Join(" ", [.. items[s..], .. items[..s]]));
Output
ArgumentOutOfRangeException
2 3 1
  • Go % can give a negative result. Integer division in Go has "x / y truncated towards zero"7, so -1 % 3 is -1. Add n and use % again:
package main

import "fmt"

func main() {
	n, k := 3, -1
	fmt.Println(k % n)
	fmt.Println((k%n + n) % n)
}
Output
-1
2
  • Rust rotate_left panics for a large k. "This function will panic if mid is greater than the length of the slice."2 Use k % len:
fn main() {
    // Hide the panic message, so the example prints only its own lines.
    std::panic::set_hook(Box::new(|_| {}));
    let result = std::panic::catch_unwind(|| {
        let mut v = vec![1, 2, 3];
        v.rotate_left(4);
        v
    });
    println!("panic: {}", result.is_err());
    let mut v = vec![1, 2, 3];
    let k = 4;
    let len = v.len();
    v.rotate_left(k % len);
    println!("{v:?}");
}
Output
panic: true
[2, 3, 1]
  • C memcpy must not copy to an overlapping area. "If the objects overlap (which is a violation of the restrict contract)"8, the behavior of memcpy is undefined. An in-place rotation moves items inside one array, so use memmove for that step:
#include <stdio.h>
#include <string.h>

int main(void) {
    int a[] = {1, 2, 3, 4, 5};
    size_t n = sizeof a / sizeof a[0];
    size_t s = 2;
    int first[2];
    memcpy(first, a, s * sizeof a[0]);
    // The source and the destination overlap, so use memmove, not memcpy.
    memmove(a, a + s, (n - s) * sizeof a[0]);
    memcpy(a + n - s, first, s * sizeof a[0]);
    for (size_t i = 0; i < n; i++) {
        printf("%d%s", a[i], i + 1 < n ? " " : "\n");
    }
    return 0;
}
Output
3 4 5 1 2
  • C++ std::rotate rotates to the left. For a right rotation, give reverse iterators:
#include <algorithm>
#include <iostream>
#include <vector>

static void print(const std::vector<int> &v) {
    for (std::size_t i = 0; i < v.size(); i++) {
        std::cout << v[i] << (i + 1 < v.size() ? " " : "\n");
    }
}

int main() {
    std::vector<int> v{1, 2, 3, 4, 5};
    // The middle iterator is the item that becomes the first item.
    std::rotate(v.begin(), v.begin() + 2, v.end());
    print(v);
    std::vector<int> w{1, 2, 3, 4, 5};
    // With reverse iterators, the rotation is to the right.
    std::rotate(w.rbegin(), w.rbegin() + 2, w.rend());
    print(w);
}
Output
3 4 5 1 2
4 5 1 2 3
  • Bash needs a space before a negative offset. "a negative offset must be separated from the colon by at least one space"9. In the example, ${a[@]: -2} gives the last two items. ${a[@]:-2} is a default value expansion, so it gives all the items:
a=(1 2 3 4 5)
echo "${a[@]: -2}"
echo "${a[@]:-2}"
echo "${a[@]:2}" "${a[@]:0:2}"
Output
4 5
1 2 3 4 5
3 4 5 1 2

Code

The build runs the native tests of each language in a pinned toolchain.

rotate_left.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/rotate-a-list/.

def rotate_left(items: list[int], k: int) -> list[int]:
    """Return a new list with the first k items moved to the end."""
    if not items:
        return []
    # k % len(items) makes a k that is larger than the list work.
    s = k % len(items)
    return items[s:] + items[:s]
test_rotate_left.py 32 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/rotate-a-list/.

import pytest

from rotate_left import rotate_left

CASES = {
    "by-two": ([1, 2, 3, 4, 5], 2, [3, 4, 5, 1, 2]),
    "by-one": ([1, 2, 3], 1, [2, 3, 1]),
    "zero": ([1, 2, 3], 0, [1, 2, 3]),
    "full-turn": ([1, 2, 3], 3, [1, 2, 3]),
    "more-than-length": ([1, 2, 3], 4, [2, 3, 1]),
    "much-larger": ([1, 2, 3], 2000000000, [3, 1, 2]),
    "empty": ([], 5, []),
    "empty-zero": ([], 0, []),
    "single": ([7], 3, [7]),
    "duplicates": ([1, 1, 2], 1, [1, 2, 1]),
    "negative-items": ([-1, -2, -3], 1, [-2, -3, -1]),
}


@pytest.mark.parametrize("name", CASES)
def test_rotate_left(name):
    items, k, want = CASES[name]
    assert rotate_left(items, k) == want


def test_input_does_not_change():
    items = [1, 2, 3]
    rotate_left(items, 1)
    assert items == [1, 2, 3]
rotate_left.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

#include "rotate_left.hpp"

#include <algorithm>
#include <cstddef>

std::vector<int> rotate_left(std::span<const int> items, std::size_t k) {
    std::vector<int> v(items.begin(), items.end());
    if (!v.empty()) {
        auto s = static_cast<std::ptrdiff_t>(k % v.size());
        // The middle iterator is the item that becomes the first item.
        std::ranges::rotate(v, v.begin() + s);
    }
    return v;
}
rotate_left.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

#pragma once

#include <cstddef>
#include <span>
#include <vector>

// rotate_left returns a new vector with the first k items moved to the end.
std::vector<int> rotate_left(std::span<const int> items, std::size_t k);
test_rotate_left.cpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

#include "rotate_left.hpp"

#include <cstddef>
#include <iostream>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view name, const std::vector<int> &items, std::size_t k, const std::vector<int> &want) {
    if (rotate_left(items, k) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("by-two", std::vector<int>{1, 2, 3, 4, 5}, 2, std::vector<int>{3, 4, 5, 1, 2});
    check("by-one", std::vector<int>{1, 2, 3}, 1, std::vector<int>{2, 3, 1});
    check("zero", std::vector<int>{1, 2, 3}, 0, std::vector<int>{1, 2, 3});
    check("full-turn", std::vector<int>{1, 2, 3}, 3, std::vector<int>{1, 2, 3});
    check("more-than-length", std::vector<int>{1, 2, 3}, 4, std::vector<int>{2, 3, 1});
    check("much-larger", std::vector<int>{1, 2, 3}, 2000000000, std::vector<int>{3, 1, 2});
    check("empty", std::vector<int>{}, 5, std::vector<int>{});
    check("empty-zero", std::vector<int>{}, 0, std::vector<int>{});
    check("single", std::vector<int>{7}, 3, std::vector<int>{7});
    check("duplicates", std::vector<int>{1, 1, 2}, 1, std::vector<int>{1, 2, 1});
    check("negative-items", std::vector<int>{-1, -2, -3}, 1, std::vector<int>{-2, -3, -1});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
RotateLeft.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

final class RotateLeft {
  private RotateLeft() {}

  /** Returns a new array with the first k items moved to the end. k must not be negative. */
  static int[] rotateLeft(int[] items, int k) {
    int n = items.length;
    int[] out = new int[n];
    if (n == 0) {
      return out;
    }
    int s = k % n;
    System.arraycopy(items, s, out, 0, n - s);
    System.arraycopy(items, 0, out, n - s, s);
    return out;
  }
}
RotateLeftTest.java 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class RotateLeftTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("by-two", new int[] {1, 2, 3, 4, 5}, 2, new int[] {3, 4, 5, 1, 2}),
        Arguments.of("by-one", new int[] {1, 2, 3}, 1, new int[] {2, 3, 1}),
        Arguments.of("zero", new int[] {1, 2, 3}, 0, new int[] {1, 2, 3}),
        Arguments.of("full-turn", new int[] {1, 2, 3}, 3, new int[] {1, 2, 3}),
        Arguments.of("more-than-length", new int[] {1, 2, 3}, 4, new int[] {2, 3, 1}),
        Arguments.of("much-larger", new int[] {1, 2, 3}, 2000000000, new int[] {3, 1, 2}),
        Arguments.of("empty", new int[] {}, 5, new int[] {}),
        Arguments.of("empty-zero", new int[] {}, 0, new int[] {}),
        Arguments.of("single", new int[] {7}, 3, new int[] {7}),
        Arguments.of("duplicates", new int[] {1, 1, 2}, 1, new int[] {1, 2, 1}),
        Arguments.of("negative-items", new int[] {-1, -2, -3}, 1, new int[] {-2, -3, -1}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void rotateLeft(String name, int[] items, int k, int[] want) {
    assertArrayEquals(want, RotateLeft.rotateLeft(items, k));
  }
}
rotate_left.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

#include "rotate_left.h"

void rotate_left(const int *items, size_t n, size_t k, int *out) {
    if (n == 0) {
        return;
    }
    size_t s = k % n;
    for (size_t i = 0; i < n; i++) {
        out[i] = items[(i + s) % n];
    }
}
rotate_left.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

#ifndef ROTATE_LEFT_H
#define ROTATE_LEFT_H

#include <stddef.h>

// rotate_left writes items[0..n) to out[0..n), with the first k items moved
// to the end.
void rotate_left(const int *items, size_t n, size_t k, int *out);

#endif
test_rotate_left.c 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

#include "rotate_left.h"

#include <stdbool.h>
#include <stdio.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

// Each list has a 0 in it when it is empty, because C has no empty array.
// The count n gives the real length.
static void check(const char *name, const int *got, const int *want, size_t n) {
    bool ok = true;
    for (size_t i = 0; ok && i < n; i++) {
        ok = got[i] == want[i];
    }
    if (!ok) {
        fprintf(stderr, "case %s failed\n", name);
        failures++;
    }
}

#define CHECK(name, n, given, k, want)   \
    do {                                 \
        const int g[] = given;           \
        const int w[] = want;            \
        int out[sizeof g / sizeof g[0]]; \
        rotate_left(g, n, k, out);       \
        check(name, out, w, n);          \
    } while (0)

int main(void) {
    CHECK("by-two", 5, L(1, 2, 3, 4, 5), 2, L(3, 4, 5, 1, 2));
    CHECK("by-one", 3, L(1, 2, 3), 1, L(2, 3, 1));
    CHECK("zero", 3, L(1, 2, 3), 0, L(1, 2, 3));
    CHECK("full-turn", 3, L(1, 2, 3), 3, L(1, 2, 3));
    CHECK("more-than-length", 3, L(1, 2, 3), 4, L(2, 3, 1));
    CHECK("much-larger", 3, L(1, 2, 3), 2000000000, L(3, 1, 2));
    CHECK("empty", 0, L(0), 5, L(0));
    CHECK("empty-zero", 0, L(0), 0, L(0));
    CHECK("single", 1, L(7), 3, L(7));
    CHECK("duplicates", 3, L(1, 1, 2), 1, L(1, 2, 1));
    CHECK("negative-items", 3, L(-1, -2, -3), 1, L(-2, -3, -1));
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
RotateLeft.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

public static class RotateLeft
{
    // By returns a new array with the first k items moved to the end.
    public static int[] By(int[] items, int k)
    {
        if (items.Length == 0)
        {
            return [];
        }
        int s = k % items.Length;
        return [.. items[s..], .. items[..s]];
    }
}
RotateLeftTests.cs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

using Xunit;

public sealed class RotateLeftTests
{
    public static TheoryData<string, int[], int, int[]> Cases => new()
    {
        { "by-two", new int[] { 1, 2, 3, 4, 5 }, 2, new int[] { 3, 4, 5, 1, 2 } },
        { "by-one", new int[] { 1, 2, 3 }, 1, new int[] { 2, 3, 1 } },
        { "zero", new int[] { 1, 2, 3 }, 0, new int[] { 1, 2, 3 } },
        { "full-turn", new int[] { 1, 2, 3 }, 3, new int[] { 1, 2, 3 } },
        { "more-than-length", new int[] { 1, 2, 3 }, 4, new int[] { 2, 3, 1 } },
        { "much-larger", new int[] { 1, 2, 3 }, 2000000000, new int[] { 3, 1, 2 } },
        { "empty", new int[0], 5, new int[0] },
        { "empty-zero", new int[0], 0, new int[0] },
        { "single", new int[] { 7 }, 3, new int[] { 7 } },
        { "duplicates", new int[] { 1, 1, 2 }, 1, new int[] { 1, 2, 1 } },
        { "negative-items", new int[] { -1, -2, -3 }, 1, new int[] { -2, -3, -1 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] items, int k, int[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, RotateLeft.By(items, k));
    }
}
rotate_left.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

/**
 * @param {number[]} items
 * @param {number} k
 * @returns {number[]}
 */
export function rotateLeft(items, k) {
  if (items.length === 0) {
    return [];
  }
  // k % items.length makes a k that is larger than the array work.
  const s = k % items.length;
  return [...items.slice(s), ...items.slice(0, s)];
}
rotate_left.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { rotateLeft } from "./rotate_left.js";

const cases = [
  ["by-two", [1, 2, 3, 4, 5], 2, [3, 4, 5, 1, 2]],
  ["by-one", [1, 2, 3], 1, [2, 3, 1]],
  ["zero", [1, 2, 3], 0, [1, 2, 3]],
  ["full-turn", [1, 2, 3], 3, [1, 2, 3]],
  ["more-than-length", [1, 2, 3], 4, [2, 3, 1]],
  ["much-larger", [1, 2, 3], 2000000000, [3, 1, 2]],
  ["empty", [], 5, []],
  ["empty-zero", [], 0, []],
  ["single", [7], 3, [7]],
  ["duplicates", [1, 1, 2], 1, [1, 2, 1]],
  ["negative-items", [-1, -2, -3], 1, [-2, -3, -1]],
];

for (const [name, items, k, want] of cases) {
  test(name, () => {
    assert.deepEqual(rotateLeft(items, k), want);
  });
}
rotate_left.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

export function rotateLeft(items: readonly number[], k: number): number[] {
  if (items.length === 0) {
    return [];
  }
  // k % items.length makes a k that is larger than the array work.
  const s = k % items.length;
  return [...items.slice(s), ...items.slice(0, s)];
}
rotate_left.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { rotateLeft } from "./rotate_left.ts";

const cases: [string, number[], number, number[]][] = [
  ["by-two", [1, 2, 3, 4, 5], 2, [3, 4, 5, 1, 2]],
  ["by-one", [1, 2, 3], 1, [2, 3, 1]],
  ["zero", [1, 2, 3], 0, [1, 2, 3]],
  ["full-turn", [1, 2, 3], 3, [1, 2, 3]],
  ["more-than-length", [1, 2, 3], 4, [2, 3, 1]],
  ["much-larger", [1, 2, 3], 2000000000, [3, 1, 2]],
  ["empty", [], 5, []],
  ["empty-zero", [], 0, []],
  ["single", [7], 3, [7]],
  ["duplicates", [1, 1, 2], 1, [1, 2, 1]],
  ["negative-items", [-1, -2, -3], 1, [-2, -3, -1]],
];

for (const [name, items, k, want] of cases) {
  test(name, () => {
    assert.deepEqual(rotateLeft(items, k), want);
  });
}
rotate_left.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

// Package rotateleft rotates the items of a slice.
package rotateleft

import "slices"

// RotateLeft returns a new slice with the first k items moved to the end.
// k must not be negative.
func RotateLeft(items []int, k int) []int {
	if len(items) == 0 {
		return []int{}
	}
	s := k % len(items)
	// Concat makes a new slice, so the input does not change.
	return slices.Concat(items[s:], items[:s])
}
rotate_left_test.go 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

package rotateleft

import (
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	items []int
	k     int
	want  []int
}{
	{"by-two", []int{1, 2, 3, 4, 5}, 2, []int{3, 4, 5, 1, 2}},
	{"by-one", []int{1, 2, 3}, 1, []int{2, 3, 1}},
	{"zero", []int{1, 2, 3}, 0, []int{1, 2, 3}},
	{"full-turn", []int{1, 2, 3}, 3, []int{1, 2, 3}},
	{"more-than-length", []int{1, 2, 3}, 4, []int{2, 3, 1}},
	{"much-larger", []int{1, 2, 3}, 2000000000, []int{3, 1, 2}},
	{"empty", []int{}, 5, []int{}},
	{"empty-zero", []int{}, 0, []int{}},
	{"single", []int{7}, 3, []int{7}},
	{"duplicates", []int{1, 1, 2}, 1, []int{1, 2, 1}},
	{"negative-items", []int{-1, -2, -3}, 1, []int{-2, -3, -1}},
}

func TestRotateLeft(t *testing.T) {
	for _, c := range cases {
		if got := RotateLeft(c.items, c.k); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}

func TestInputDoesNotChange(t *testing.T) {
	items := []int{1, 2, 3}
	RotateLeft(items, 1)
	if !slices.Equal(items, []int{1, 2, 3}) {
		t.Errorf("the input changed: %v", items)
	}
}
rotate_left.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

/// Returns a new vector with the first `k` items moved to the end.
pub fn rotate_left(items: &[i32], k: usize) -> Vec<i32> {
    let mut v = items.to_vec();
    if !v.is_empty() {
        // slice::rotate_left panics if its argument is larger than the length.
        let s = k % v.len();
        v.rotate_left(s);
    }
    v
}
tests/rotate_left_test.rs 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/rotate-a-list/.

use algo_rotate_a_list::rotate_left;

#[test]
fn cases() {
    let cases: &[(&str, &[i32], usize, &[i32])] = &[
        ("by-two", &[1, 2, 3, 4, 5], 2, &[3, 4, 5, 1, 2]),
        ("by-one", &[1, 2, 3], 1, &[2, 3, 1]),
        ("zero", &[1, 2, 3], 0, &[1, 2, 3]),
        ("full-turn", &[1, 2, 3], 3, &[1, 2, 3]),
        ("more-than-length", &[1, 2, 3], 4, &[2, 3, 1]),
        ("much-larger", &[1, 2, 3], 2000000000, &[3, 1, 2]),
        ("empty", &[], 5, &[]),
        ("empty-zero", &[], 0, &[]),
        ("single", &[7], 3, &[7]),
        ("duplicates", &[1, 1, 2], 1, &[1, 2, 1]),
        ("negative-items", &[-1, -2, -3], 1, &[-2, -3, -1]),
    ];
    for &(name, items, k, want) in cases {
        assert_eq!(rotate_left(items, k), want, "{name}");
    }
}
rotate_left.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/rotate-a-list/.

# rotate_left K ITEM...
# Prints the items, one on each line, with the first K items moved to the end.
rotate_left() {
  local k=$1
  shift
  local -a items=("$@")
  local n=${#items[@]}
  if ((n == 0)); then
    return 0
  fi
  local s=$((k % n))
  printf '%s\n' "${items[@]:s}" "${items[@]:0:s}"
}
test_rotate_left.bats 37 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/rotate-a-list/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/rotate_left.sh"
}

lines() { # lines ITEM...: prints each item on a line, and nothing for no items
  if (($# > 0)); then printf '%s\n' "$@"; fi
}

check() { # check FUNCTION GIVEN... -- WANT...
  local fn=$1 got want
  shift
  local -a given=()
  while [ "$1" != -- ]; do given+=("$1"); shift; done
  shift
  # The x keeps the trailing newlines, which $(...) removes.
  got=$("$fn" "${given[@]}"; printf x)
  want=$(lines "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "by-two" { check rotate_left 2 1 2 3 4 5 -- 3 4 5 1 2; }
@test "by-one" { check rotate_left 1 1 2 3 -- 2 3 1; }
@test "zero" { check rotate_left 0 1 2 3 -- 1 2 3; }
@test "full-turn" { check rotate_left 3 1 2 3 -- 1 2 3; }
@test "more-than-length" { check rotate_left 4 1 2 3 -- 2 3 1; }
@test "much-larger" { check rotate_left 2000000000 1 2 3 -- 3 1 2; }
@test "empty" { check rotate_left 5 --; }
@test "empty-zero" { check rotate_left 0 --; }
@test "single" { check rotate_left 3 7 -- 7; }
@test "duplicates" { check rotate_left 1 1 1 2 -- 1 2 1; }
@test "negative-items" { check rotate_left 1 -1 -2 -3 -- -2 -3 -1; }

References

  1. Microsoft Learn, Indices and ranges (C#), Language support for indices and ranges
  2. Rust standard library, primitive type slice, rotate_left
  3. cppreference.com, std::rotate, Description
  4. The Python Standard Library, collections, deque.rotate()
  5. MDN Web Docs, Remainder (%), Description
  6. Java SE 25 API, Class Collections, rotate(List, int)
  7. The Go Programming Language Specification, Integer operators
  8. cppreference.com, memcpy, memcpy_s, Description
  9. Bash Reference Manual, 3.5.3 Shell Parameter Expansion

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source