Programming Search⌘K

Taskintro

Reverse a list

Also called reverse an array, reversed copy, reverse in place, invert the order of a list, flip a list, iterate backwards, reverse iterator, toReversed.

Make a new list with the items of a list in the opposite order, and know which reverse functions change the list in place, which return a view, and which return a lazy iterator.

Task

Make a new list with the items of a list in the opposite order. The function reverse(items) returns a list whose first item is the last item of items. For example, reverse([1, 2, 3]) is [3, 2, 1].

The result is a new list, and items must not change. Each item is a 32-bit signed integer, and the list has 0 to 1000 items.

Solutions

Language A reversed copy Reverse in place Walk backwards
Python items[::-1] items.reverse() reversed(items)
JavaScript, TypeScript items.toReversed() items.reverse() a loop from length - 1
Java a copy loop, or new ArrayList<>(list.reversed()) Collections.reverse(list) list.reversed()
C# Enumerable.Reverse(items).ToArray() Array.Reverse(items), list.Reverse() Enumerable.Reverse(items)
Go slices.Clone, then slices.Reverse slices.Reverse(items) slices.Backward(items)
Rust items.iter().rev().copied().collect() items.reverse() items.iter().rev()
C malloc and a copy loop a swap loop a loop from n down
C++ std::vector<int>(items.rbegin(), items.rend()) std::reverse std::views::reverse
Bash a loop from the last position none a loop from the last position
  • Python. sequence.reverse() will "Reverse the items of sequence in place"1, and "To remind users that it operates by side-effect, it returns None"1. The solution uses the slice items[::-1], which is a new list. reversed(items) will "Return a reverse iterator"2, so list(reversed(items)) is also a new list.
  • JavaScript. reverse "reverses an array in place and returns the reference to the same array"3. toReversed "is the copying counterpart of the reverse() method. It returns a new array with the elements in reversed order"4. TypeScript uses the same method on a readonly number[].
  • Java. Collections.reverse "Reverses the order of the elements in the specified list"5, in place. Since Java 21, List.reversed() "Returns a reverse-ordered view of this collection"6. The solution fills a new int[] from the end of the input.
  • C#. The method List<T>.Reverse() "Reverses the order of the elements in the entire List"7, in place. Enumerable.Reverse "Inverts the order of the elements in a sequence"8, and it does not change the source. The solution copies the array and calls Array.Reverse on the copy.
  • Go. "Reverse reverses the elements of the slice in place"9. The solution reverses a clone.
  • Rust. reverse "Reverses the order of elements in the slice, in place"10. rev "Reverses an iterator’s direction"11, and the solution collects the reversed iterator into a new vector.
  • C. The solution allocates n items and copies item n - 1 - i to position i. The caller must free the result.
  • C++. std::reverse "Reverses the order of the elements in the target range [first, last)"12. std::views::reverse is "a view of underlying view with reversed order"13, and it does not copy. The solution makes a vector from the reverse iterators.
  • Bash. Bash has no reverse command. The solution walks the positional parameters from $# down to 1 and prints one item on each line.

Edge cases

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

  • empty: the reverse of an empty list is an empty list.
  • single: the reverse of one item is the same list, but it must still be a new list.
  • two and four: a list with an even count has no middle item, so each item moves. A swap loop must stop at n / 2, or it swaps each pair back.
  • three, duplicates and palindrome: with an odd count, the middle item stays. The reverse of [1, 2, 1] is equal to the input, so a test that compares only the values cannot find an impl that returns the input. The tests also check that the result is not the input list.
  • negative and limit: the items can be negative, and the largest and the smallest 32-bit integers.
  • Each test checks that items does not change. The concept page in-place and copying operations compares the two forms.

Pitfalls

  • Python reverse() returns None, and reversed() gives one pass. items.reverse() changes the list and returns None1, so b = a.reverse() sets b to None. The iterator from reversed2 is empty after one pass. Use a[::-1] or list(reversed(a)) for a copy:
a = [1, 2, 3]
b = a.reverse()
print(a, b)
r = reversed(a)
print(list(r), list(r))
print(a[::-1], a)
Output
[3, 2, 1] None
[1, 2, 3] []
[1, 2, 3] [3, 2, 1]
  • JavaScript reverse() changes the array and returns it. It "returns the reference to the same array"3, so const b = a.reverse() gives two names for one changed array. Use toReversed()4 to keep the original:
const a = [1, 2, 3];
const b = a.reverse();
console.log(a, b === a);
const c = a.toReversed();
console.log(a, c);
Output
[ 3, 2, 1 ] true
[ 3, 2, 1 ] [ 1, 2, 3 ]
  • Java reversed() is a view, not a copy. reversed() "Returns a reverse-ordered view of this collection"6, so a later change to the list shows in the view. Collections.reverse changes the list, and it throws UnsupportedOperationException for an unmodifiable list such as List.of(...)5. Copy the view to keep it:
import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> a = new ArrayList<>(List.of(1, 2, 3));
    List<Integer> view = a.reversed();
    List<Integer> copy = new ArrayList<>(a.reversed());
    a.add(4);
    System.out.println(view + " " + copy);
    try {
      java.util.Collections.reverse(List.of(1, 2, 3));
    } catch (UnsupportedOperationException e) {
      System.out.println("UnsupportedOperationException");
    }
  }
}
Output
[4, 3, 2, 1] [3, 2, 1]
UnsupportedOperationException
  • C# Enumerable.Reverse runs when the code reads it. "This method is implemented by using deferred execution"8. So the result of Enumerable.Reverse(list) shows the list as it is when a loop reads it, not when the call runs. Also, list.Reverse() on a List<T> is the method that changes the list in place7, not the LINQ method. Call ToArray() or ToList() to keep a copy:
var list = new List<int> { 1, 2, 3 };
var later = Enumerable.Reverse(list);
var now = Enumerable.Reverse(list).ToArray();
list.Add(4);
Console.WriteLine(string.Join(",", later) + " " + string.Join(",", now));
list.Reverse();
Console.WriteLine(string.Join(",", list) + " " + string.Join(",", later));
Output
4,3,2,1 3,2,1
4,3,2,1 1,2,3,4
  • Go slices.Reverse changes the array under the slice. It "reverses the elements of the slice in place"9, and a slice shares the array of the slice that it came from. So the reverse of a[:2] changes a. Reverse a clone:
package main

import (
	"fmt"
	"slices"
)

func main() {
	a := []int{1, 2, 3, 4}
	slices.Reverse(a[:2])
	fmt.Println(a)
	c := slices.Clone(a)
	slices.Reverse(c)
	fmt.Println(a, c)
}
Output
[2 1 3 4]
[2 1 3 4] [4 3 1 2]
  • Rust the order of rev and enumerate changes the indexes. "After using rev(), an iterator will instead iterate from right to left"11. So rev().enumerate() counts from 0 at the last item, but enumerate().rev() keeps the position of each item in the slice:
fn main() {
    let v = [10, 20, 30];
    let a: Vec<(usize, &i32)> = v.iter().rev().enumerate().collect();
    let b: Vec<(usize, &i32)> = v.iter().enumerate().rev().collect();
    println!("{a:?}");
    println!("{b:?}");
}
Output
[(0, 30), (1, 20), (2, 10)]
[(2, 30), (1, 20), (0, 10)]
  • C a size_t that counts down never goes below 0. For an unsigned type, "subtracting one from 0 gives UINT_MAX"14, and for size_t it gives SIZE_MAX. So for (size_t j = n - 1; j >= 0; j--) never stops, and with n equal to 0 it starts at SIZE_MAX. The form for (size_t j = n; j-- > 0;) tests before it subtracts. The output is from a machine with a 64-bit size_t; the first loop stops only because of the count:
#include <stddef.h>
#include <stdio.h>

int main(void) {
    const int a[] = {1, 2, 3};
    size_t n = 3;
    int steps = 0;
    for (size_t j = n - 1; j >= 0; j--) {
        printf("%zu ", j);
        if (++steps == 4) {
            break;
        }
    }
    printf("\n");
    for (size_t j = n; j-- > 0;) {
        printf("%d ", a[j]);
    }
    printf("\n");
    return 0;
}
Output
2 1 0 18446744073709551615
3 2 1
  • C++ base() of a reverse iterator is one item off. "The base iterator refers to the element that is next (from the iterator_type perspective) to the element the reverse_iterator is currently pointing to"15. So v.rbegin() reads the last item, but v.rbegin().base() is v.end(). Subtract one from base() to reach the same item, for example before erase:
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{1, 2, 3};
    auto r = v.rbegin();
    std::cout << *r << " " << (r.base() == v.end()) << " " << *(r.base() - 1) << "\n";
    v.erase(r.base() - 1);
    std::cout << v.size() << " " << v.back() << "\n";
}
Output
3 1 3
2 2
  • Bash ${#a[@]} - 1 is not always the last index. "There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously"16. After unset, an array has gaps, so a loop from ${#a[@]} - 1 down to 0 reads empty items and misses the last one. Walk the list of indexes from ${!a[@]} instead:
a=(1 2 3 4)
unset 'a[1]'
echo "${#a[@]} ${!a[@]}"
r=()
for ((i = ${#a[@]} - 1; i >= 0; i--)); do r+=("${a[i]}"); done
echo "${#r[@]} [${r[*]}]"
idx=("${!a[@]}")
r=()
for ((k = ${#idx[@]} - 1; k >= 0; k--)); do r+=("${a[${idx[k]}]}"); done
echo "${#r[@]} [${r[*]}]"
Output
3 0 2 3
3 [3  1]
3 [4 3 1]

Code

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

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

def reverse_list(items: list[int]) -> list[int]:
    """Return a new list of the items in the opposite order."""
    # items.reverse() would change items and return None.
    return items[::-1]
test_reverse_list.py 28 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reverse-a-list/.

import pytest

from reverse_list import reverse_list

CASES = {
    "three": ([1, 2, 3], [3, 2, 1]),
    "four": ([4, 7, 1, 9], [9, 1, 7, 4]),
    "empty": ([], []),
    "single": ([5], [5]),
    "two": ([1, 2], [2, 1]),
    "duplicates": ([1, 1, 2], [2, 1, 1]),
    "palindrome": ([1, 2, 1], [1, 2, 1]),
    "negative": ([-1, 0, -3], [-3, 0, -1]),
    "limit": ([2147483647, -2147483648, 0], [0, -2147483648, 2147483647]),
}


@pytest.mark.parametrize("name", CASES)
def test_reverse_list(name):
    items, want = CASES[name]
    items0 = list(items)
    got = reverse_list(items)
    assert got == want
    assert got is not items
    assert items == items0
reverse_list.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

#include "reverse_list.hpp"

#include <span>
#include <vector>

std::vector<int> reverse_list(std::span<const int> items) {
    // The reverse iterators walk the items from the end to the start.
    return std::vector<int>(items.rbegin(), items.rend());
}
reverse_list.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

#pragma once

#include <span>
#include <vector>

// reverse_list returns a new vector of the items in the opposite order.
std::vector<int> reverse_list(std::span<const int> items);
test_reverse_list.cpp 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

#include "reverse_list.hpp"

#include <climits>
#include <iostream>
#include <string_view>
#include <vector>

static int failures = 0;

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

int main() {
    check("three", std::vector<int>{1, 2, 3}, std::vector<int>{3, 2, 1});
    check("four", std::vector<int>{4, 7, 1, 9}, std::vector<int>{9, 1, 7, 4});
    check("empty", std::vector<int>{}, std::vector<int>{});
    check("single", std::vector<int>{5}, std::vector<int>{5});
    check("two", std::vector<int>{1, 2}, std::vector<int>{2, 1});
    check("duplicates", std::vector<int>{1, 1, 2}, std::vector<int>{2, 1, 1});
    check("palindrome", std::vector<int>{1, 2, 1}, std::vector<int>{1, 2, 1});
    check("negative", std::vector<int>{-1, 0, -3}, std::vector<int>{-3, 0, -1});
    check("limit", std::vector<int>{INT_MAX, INT_MIN, 0}, std::vector<int>{0, INT_MIN, INT_MAX});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
ReverseList.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

final class ReverseList {
  private ReverseList() {}

  /** Returns a new array of the items in the opposite order. */
  static int[] reverse(int[] items) {
    int n = items.length;
    int[] out = new int[n];
    for (int i = 0; i < n; i++) {
      out[i] = items[n - 1 - i];
    }
    return out;
  }
}
ReverseListTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

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

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 ReverseListTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("three", new int[] {1, 2, 3}, new int[] {3, 2, 1}),
        Arguments.of("four", new int[] {4, 7, 1, 9}, new int[] {9, 1, 7, 4}),
        Arguments.of("empty", new int[] {}, new int[] {}),
        Arguments.of("single", new int[] {5}, new int[] {5}),
        Arguments.of("two", new int[] {1, 2}, new int[] {2, 1}),
        Arguments.of("duplicates", new int[] {1, 1, 2}, new int[] {2, 1, 1}),
        Arguments.of("palindrome", new int[] {1, 2, 1}, new int[] {1, 2, 1}),
        Arguments.of("negative", new int[] {-1, 0, -3}, new int[] {-3, 0, -1}),
        Arguments.of("limit", new int[] {2147483647, Integer.MIN_VALUE, 0}, new int[] {0, Integer.MIN_VALUE, 2147483647}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void reverse(String name, int[] items, int[] want) {
    int[] items0 = items.clone();
    int[] got = ReverseList.reverse(items);
    assertArrayEquals(want, got);
    assertNotSame(items, got);
    assertArrayEquals(items0, items);
  }
}
reverse_list.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

#include "reverse_list.h"

#include <stdlib.h>

int *reverse_list(const int *items, size_t n) {
    // malloc(0) may return NULL, so ask for at least one item.
    int *out = malloc((n > 0 ? n : 1) * sizeof *out);
    if (out == NULL) {
        return NULL;
    }
    // i counts up, so the loop does not need an unsigned index below 0.
    for (size_t i = 0; i < n; i++) {
        out[i] = items[n - 1 - i];
    }
    return out;
}
reverse_list.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

#ifndef REVERSE_LIST_H
#define REVERSE_LIST_H

#include <stddef.h>

// reverse_list returns a new array of the n items in the opposite order. The
// caller must free it. It returns NULL when malloc fails.
int *reverse_list(const int *items, size_t n);

#endif
test_reverse_list.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

#include "reverse_list.h"

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

static void check(const char *name, const int *items, size_t n, const int *want) {
    int *out = reverse_list(items, n);
    if (out == NULL || (n > 0 && memcmp(out, want, n * sizeof *out) != 0)) {
        fprintf(stderr, "case %s failed\n", name);
        failures++;
    }
    free(out);
}

// C has no empty array, so an empty list is the array {0} with a count of 0.
#define CHECK(name, n, items, want) \
    do {                            \
        const int x[] = items;      \
        const int w[] = want;       \
        check(name, x, n, w);       \
    } while (0)

int main(void) {
    CHECK("three", 3, L(1, 2, 3), L(3, 2, 1));
    CHECK("four", 4, L(4, 7, 1, 9), L(9, 1, 7, 4));
    CHECK("empty", 0, L(0), L(0));
    CHECK("single", 1, L(5), L(5));
    CHECK("two", 2, L(1, 2), L(2, 1));
    CHECK("duplicates", 3, L(1, 1, 2), L(2, 1, 1));
    CHECK("palindrome", 3, L(1, 2, 1), L(1, 2, 1));
    CHECK("negative", 3, L(-1, 0, -3), L(-3, 0, -1));
    CHECK("limit", 3, L(INT_MAX, INT_MIN, 0), L(0, INT_MIN, INT_MAX));
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
ReverseList.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

public static class ReverseList
{
    // Returns a new array of the items in the opposite order.
    public static int[] Of(int[] items)
    {
        int[] copy = [.. items];
        // Array.Reverse changes the array that it gets, so it gets the copy.
        Array.Reverse(copy);
        return copy;
    }
}
ReverseListTests.cs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

using Xunit;

public sealed class ReverseListTests
{
    public static TheoryData<string, int[], int[]> Cases => new()
    {
        { "three", new int[] { 1, 2, 3 }, new int[] { 3, 2, 1 } },
        { "four", new int[] { 4, 7, 1, 9 }, new int[] { 9, 1, 7, 4 } },
        { "empty", new int[0], new int[0] },
        { "single", new int[] { 5 }, new int[] { 5 } },
        { "two", new int[] { 1, 2 }, new int[] { 2, 1 } },
        { "duplicates", new int[] { 1, 1, 2 }, new int[] { 2, 1, 1 } },
        { "palindrome", new int[] { 1, 2, 1 }, new int[] { 1, 2, 1 } },
        { "negative", new int[] { -1, 0, -3 }, new int[] { -3, 0, -1 } },
        { "limit", new int[] { 2147483647, int.MinValue, 0 }, new int[] { 0, int.MinValue, 2147483647 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] items, int[] want)
    {
        Assert.NotNull(name);
        var items0 = (int[])items.Clone();
        var got = ReverseList.Of(items);
        Assert.Equal(want, got);
        Assert.NotSame(items, got);
        Assert.Equal(items0, items);
    }
}
reverse_list.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

/**
 * Returns a new array of the items in the opposite order.
 * @param {number[]} items
 * @returns {number[]}
 */
export function reverseList(items) {
  // items.reverse() would change items and return the same array.
  return items.toReversed();
}
reverse_list.test.js 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

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

import { reverseList } from "./reverse_list.js";

const cases = [
  ["three", [1, 2, 3], [3, 2, 1]],
  ["four", [4, 7, 1, 9], [9, 1, 7, 4]],
  ["empty", [], []],
  ["single", [5], [5]],
  ["two", [1, 2], [2, 1]],
  ["duplicates", [1, 1, 2], [2, 1, 1]],
  ["palindrome", [1, 2, 1], [1, 2, 1]],
  ["negative", [-1, 0, -3], [-3, 0, -1]],
  ["limit", [2147483647, -2147483648, 0], [0, -2147483648, 2147483647]],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    const items0 = [...items];
    const got = reverseList(items);
    assert.deepEqual(got, want);
    assert.notEqual(got, items);
    assert.deepEqual(items, items0);
  });
}
reverse_list.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

export function reverseList(items: readonly number[]): number[] {
  // items.reverse() would change items and return the same array.
  return items.toReversed();
}
reverse_list.test.ts 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

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

import { reverseList } from "./reverse_list.ts";

const cases: [string, number[], number[]][] = [
  ["three", [1, 2, 3], [3, 2, 1]],
  ["four", [4, 7, 1, 9], [9, 1, 7, 4]],
  ["empty", [], []],
  ["single", [5], [5]],
  ["two", [1, 2], [2, 1]],
  ["duplicates", [1, 1, 2], [2, 1, 1]],
  ["palindrome", [1, 2, 1], [1, 2, 1]],
  ["negative", [-1, 0, -3], [-3, 0, -1]],
  ["limit", [2147483647, -2147483648, 0], [0, -2147483648, 2147483647]],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    const items0 = [...items];
    const got = reverseList(items);
    assert.deepEqual(got, want);
    assert.notEqual(got, items);
    assert.deepEqual(items, items0);
  });
}
reverse_list.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

// Package reverselist reverses a slice into a new slice.
package reverselist

import "slices"

// Reverse returns a new slice of the items in the opposite order.
// slices.Reverse changes the slice that it gets, so it gets a clone.
func Reverse(items []int) []int {
	out := slices.Clone(items)
	slices.Reverse(out)
	return out
}
reverse_list_test.go 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

package reverselist

import (
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	items []int
	want  []int
}{
	{"three", []int{1, 2, 3}, []int{3, 2, 1}},
	{"four", []int{4, 7, 1, 9}, []int{9, 1, 7, 4}},
	{"empty", []int{}, []int{}},
	{"single", []int{5}, []int{5}},
	{"two", []int{1, 2}, []int{2, 1}},
	{"duplicates", []int{1, 1, 2}, []int{2, 1, 1}},
	{"palindrome", []int{1, 2, 1}, []int{1, 2, 1}},
	{"negative", []int{-1, 0, -3}, []int{-3, 0, -1}},
	{"limit", []int{2147483647, -2147483648, 0}, []int{0, -2147483648, 2147483647}},
}

func TestReverse(t *testing.T) {
	for _, c := range cases {
		items0 := slices.Clone(c.items)
		got := Reverse(c.items)
		if !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
		if len(got) > 0 {
			got[0] ^= 1
		}
		if !slices.Equal(c.items, items0) {
			t.Errorf("%s: the input changed", c.name)
		}
	}
}
reverse_list.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

/// Returns a new vector of the items in the opposite order.
pub fn reverse(items: &[i32]) -> Vec<i32> {
    // rev() walks the items from the end; copied() turns each &i32 into an i32.
    items.iter().rev().copied().collect()
}
tests/reverse_list_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/reverse-a-list/.

use algo_reverse_a_list::reverse;

#[test]
fn cases() {
    let cases: &[(&str, &[i32], &[i32])] = &[
        ("three", &[1, 2, 3], &[3, 2, 1]),
        ("four", &[4, 7, 1, 9], &[9, 1, 7, 4]),
        ("empty", &[], &[]),
        ("single", &[5], &[5]),
        ("two", &[1, 2], &[2, 1]),
        ("duplicates", &[1, 1, 2], &[2, 1, 1]),
        ("palindrome", &[1, 2, 1], &[1, 2, 1]),
        ("negative", &[-1, 0, -3], &[-3, 0, -1]),
        ("limit", &[2147483647, i32::MIN, 0], &[0, i32::MIN, 2147483647]),
    ];
    for &(name, items, want) in cases {
        assert_eq!(reverse(items), want, "{name}");
    }
}
reverse_list.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reverse-a-list/.

# reverse_list ITEM...
# Prints the items in the opposite order, one on each line.
reverse_list() {
  local i
  # The positional parameters have no gaps, so $# is the last position.
  for ((i = $#; i >= 1; i--)); do
    printf '%s\n' "${!i}"
  done
}
test_reverse_list.bats 35 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/reverse-a-list/.

bats_require_minimum_version 1.5.0

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

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

check() { # check "ITEMS" -- WANT...
  local -a items
  read -r -a items <<<"$1"
  shift 2
  local got want
  # The x keeps the trailing newlines, which $(...) removes.
  got=$(reverse_list "${items[@]}"; printf x)
  want=$(lines "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "three" { check "1 2 3" -- 3 2 1; }
@test "four" { check "4 7 1 9" -- 9 1 7 4; }
@test "empty" { check "" --; }
@test "single" { check "5" -- 5; }
@test "two" { check "1 2" -- 2 1; }
@test "duplicates" { check "1 1 2" -- 2 1 1; }
@test "palindrome" { check "1 2 1" -- 1 2 1; }
@test "negative" { check "-1 0 -3" -- -3 0 -1; }
@test "limit" { check "2147483647 -2147483648 0" -- 0 -2147483648 2147483647; }
@test "spaces" { got=$(reverse_list a "New York" "" Paris; printf x); [ "$got" = $'Paris\n\nNew York\na\nx' ]; }

References

  1. The Python Standard Library, Built-in Types, Mutable Sequence Types, sequence.reverse()
  2. The Python Standard Library, Built-in Functions, reversed()
  3. MDN Web Docs, Array.prototype.reverse(), Description
  4. MDN Web Docs, Array.prototype.toReversed(), Description
  5. Java SE 25 API, Class Collections, reverse(List<?> list)
  6. Java SE 25 API, Interface List, reversed()
  7. .NET API reference, List<T>.Reverse Method, Overloads
  8. .NET API reference, Enumerable.Reverse Method, Overloads and Remarks
  9. Go standard library, package slices, func Reverse
  10. Rust standard library, Primitive Type slice, reverse
  11. Rust standard library, Trait Iterator, rev
  12. cppreference.com, std::reverse, Description
  13. cppreference.com, std::ranges::reverse_view, Description
  14. cppreference.com, C arithmetic operators, Overflows
  15. cppreference.com, std::reverse_iterator::base, Notes
  16. Bash Reference Manual, 6.7 Arrays

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