Programming Search⌘K

Taskintro

Filter a list

Also called keep the items that match, select items, remove items that do not match, where, retain, copy_if, grep a list.

Keep the items of a list that pass a test, in their input order, and do not remove items from a list while a loop goes over it.

Task

Keep the items of a list that pass a test. The function keep_odd(items) returns a new list of the odd items of a list of integers, in their input order. For example, keep_odd([1, 2, 3, 4, 5]) is [1, 3, 5], and keep_odd([2, 4, 6]) is [].

An item is odd if the remainder of the item divided by 2 is not 0. So -3 and -1 are odd too. The input list does not change.

Solutions

Language Keep the odd items
Python [x for x in items if x % 2 != 0]
JavaScript, TypeScript items.filter((x) => x % 2 !== 0)
Java Arrays.stream(items).filter(x -> x % 2 != 0).toArray()
C# items.Where(x => x % 2 != 0).ToArray()
Go a loop and append to a new slice
Rust items.iter().copied().filter(...).collect()
C a loop that copies each odd item to out, and returns the count
C++ std::ranges::copy_if with std::back_inserter
Bash a loop that prints each odd argument
  • The test. Each solution uses x % 2 != 0, not x % 2 == 1, because the remainder of a negative item can be negative. See the JavaScript pitfall below.
  • JavaScript and TypeScript. filter "creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function"1. The input array does not change.
  • C#. ToArray runs the query at once and keeps the result.
  • Go. The loop appends to a new slice, so the input slice does not change.
  • C. The caller gives an out array with room for n items. The function returns the number of odd items.

Edge cases

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

  • empty: the filter of an empty list is an empty list.
  • none-odd and all-odd: the result can be empty, or the same as the input.
  • negative: -3 and -1 are odd. A test with x % 2 == 1 drops them in JavaScript, where -3 % 2 is -1.
  • zero: 0 is even, so it is not in the result.
  • order: the odd items keep their input order, also if they are not sorted.
  • extremes: -2147483648 is even, and 2147483647 is odd.
  • duplicates: each copy of an odd item stays.

Pitfalls

  • Python list.remove in a for loop skips items. "Code that modifies a collection while iterating over that same collection can be tricky to get right"2. In the example, the loop removes 2, then the next item is 1, so 4 stays. Make a new list:
items = [2, 4, 1, 3]
for x in items:
    if x % 2 == 0:
        items.remove(x)
print(items)
items = [2, 4, 1, 3]
print([x for x in items if x % 2 != 0])
Output
[4, 1, 3]
[1, 3]
  • JavaScript % keeps the sign. The remainder "always takes the sign of the dividend"3. So x % 2 === 1 is false for -3:
const items = [-3, -2, -1, 0, 1];
console.log(-3 % 2);
console.log(items.filter((x) => x % 2 === 1));
console.log(items.filter((x) => x % 2 !== 0));
Output
-1
[ 1 ]
[ -3, -1, 1 ]
  • Java remove in a for-each loop throws. The iterators of ArrayList are fail-fast: "if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException"4. Use removeIf:
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> items = new ArrayList<>(List.of(1, 2, 3, 4));
    try {
      for (Integer x : items) {
        if (x % 2 == 0) {
          items.remove(x);
        }
      }
    } catch (ConcurrentModificationException e) {
      System.out.println("ConcurrentModificationException");
    }
    items = new ArrayList<>(List.of(1, 2, 3, 4));
    items.removeIf(x -> x % 2 == 0);
    System.out.println(items);
  }
}
Output
ConcurrentModificationException
[1, 3]
  • C# Where runs later. "This method is implemented by using deferred execution"5. In the example, the query sees the item that the code adds after the call to Where. ToList keeps the result of that moment:
var items = new List<int> { 1, 2, 3 };
var odd = items.Where(x => x % 2 != 0);
var copy = items.Where(x => x % 2 != 0).ToList();
items.Add(5);
Console.WriteLine(string.Join(" ", odd));
Console.WriteLine(string.Join(" ", copy));
Output
1 3 5
1 3
  • Go slices.DeleteFunc changes the input. It works in place, and "DeleteFunc zeroes the elements between the new length and the original length"6. Clone the slice first if the caller needs it:
package main

import (
	"fmt"
	"slices"
)

func main() {
	items := []int{1, 2, 3, 4}
	odd := slices.DeleteFunc(items, func(x int) bool { return x%2 == 0 })
	fmt.Println(odd, items)
	items = []int{1, 2, 3, 4}
	odd = slices.DeleteFunc(slices.Clone(items), func(x int) bool { return x%2 == 0 })
	fmt.Println(odd, items)
}
Output
[1 3] [1 3 0 0]
[1 3] [1 2 3 4]
  • Rust swap_remove changes the order. "The removed element is replaced by the last element of the vector. This does not preserve ordering of the remaining elements"7. retain "preserves the order of the retained elements"7:
fn main() {
    let mut v = vec![2, 1, 3, 5];
    v.swap_remove(0);
    println!("{v:?}");
    let mut w = vec![2, 1, 3, 5];
    w.retain(|x| x % 2 != 0);
    println!("{w:?}");
}
Output
[5, 1, 3]
[1, 3, 5]
  • C removal in a loop skips items. After a removal, the next item moves to index i, and i++ goes past it. In the example, 4 stays. Copy each item to keep to the next free index:
#include <stdio.h>

int main(void) {
    int a[] = {2, 4, 1};
    size_t n = 3;
    // Wrong: after a removal, the next item moves to index i, and i++ skips it.
    for (size_t i = 0; i < n; i++) {
        if (a[i] % 2 == 0) {
            for (size_t j = i; j + 1 < n; j++) {
                a[j] = a[j + 1];
            }
            n--;
        }
    }
    for (size_t i = 0; i < n; i++) {
        printf(i ? " %d" : "%d", a[i]);
    }
    printf("\n");
    // Right: copy each item to keep to the next free index k.
    int b[] = {2, 4, 1};
    size_t k = 0;
    for (size_t i = 0; i < 3; i++) {
        if (b[i] % 2 != 0) {
            b[k++] = b[i];
        }
    }
    for (size_t i = 0; i < k; i++) {
        printf(i ? " %d" : "%d", b[i]);
    }
    printf("\n");
    return 0;
}
Output
4 1
1
  • C++ remove_if does not change the size. "A call to remove or remove_if is typically followed by a call to a container's erase member function to actually remove elements from the container"8. std::erase_if does both:
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    auto even = [](int x) { return x % 2 == 0; };
    std::vector<int> v{1, 2, 3, 4};
    auto rest = std::ranges::remove_if(v, even);
    std::cout << v.size() << " " << rest.size() << "\n";
    v.erase(rest.begin(), rest.end());
    std::cout << v.size() << "\n";
    std::vector<int> w{1, 2, 3, 4};
    std::erase_if(w, even);
    std::cout << w.size() << ":";
    for (int x : w) {
        std::cout << " " << x;
    }
    std::cout << "\n";
}
Output
4 2
2
2: 1 3
  • Bash unset leaves a gap. "unset name[subscript] unsets the array element at index subscript"9. The other items keep their indices, so a loop from 0 to ${#a[@]} reads the gap and misses the last item. Make a new array:
a=(2 4 1 3)
unset 'a[0]'
echo "count ${#a[@]}, indices ${!a[@]}"
for ((i = 0; i < ${#a[@]}; i++)); do printf '[%s]' "${a[i]}"; done
echo
a=("${a[@]}")
echo "indices ${!a[@]}"
Output
count 3, indices 1 2 3
[][4][1]
indices 0 1 2

Code

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

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

def keep_odd(items: list[int]) -> list[int]:
    """Return a new list of the odd items of items, in their order."""
    # x % 2 != 0 is true for each odd item, also for -3.
    return [x for x in items if x % 2 != 0]
test_keep_odd.py 25 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/filter-a-list/.

import pytest

from keep_odd import keep_odd

CASES = {
    "mixed": ([1, 2, 3, 4, 5], [1, 3, 5]),
    "tens": ([10, 15, 20, 25], [15, 25]),
    "empty": ([], []),
    "none-odd": ([2, 4, 6], []),
    "all-odd": ([1, 3, 5], [1, 3, 5]),
    "negative": ([-3, -2, -1, 0], [-3, -1]),
    "zero": ([0], []),
    "order": ([9, 1, 7], [9, 1, 7]),
    "extremes": ([-2147483648, 2147483647], [2147483647]),
    "duplicates": ([3, 3, 2, 3], [3, 3, 3]),
}


@pytest.mark.parametrize("name", CASES)
def test_keep_odd(name):
    items, want = CASES[name]
    assert keep_odd(items) == want
keep_odd.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

#include "keep_odd.hpp"

#include <algorithm>
#include <iterator>
#include <span>
#include <vector>

std::vector<int> keep_odd(std::span<const int> items) {
    std::vector<int> out;
    // Use != 0, not == 1: the remainder of a negative item can be negative.
    std::ranges::copy_if(items, std::back_inserter(out), [](int x) { return x % 2 != 0; });
    return out;
}
keep_odd.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

#pragma once

#include <span>
#include <vector>

// keep_odd returns a new vector of the odd items, in their order.
std::vector<int> keep_odd(std::span<const int> items);
test_keep_odd.cpp 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

#include "keep_odd.hpp"

#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 (keep_odd(items) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("mixed", std::vector<int>{1, 2, 3, 4, 5}, {1, 3, 5});
    check("tens", std::vector<int>{10, 15, 20, 25}, {15, 25});
    check("empty", std::vector<int>{}, std::vector<int>{});
    check("none-odd", std::vector<int>{2, 4, 6}, {});
    check("all-odd", std::vector<int>{1, 3, 5}, {1, 3, 5});
    check("negative", std::vector<int>{-3, -2, -1, 0}, {-3, -1});
    check("zero", std::vector<int>{0}, {});
    check("order", std::vector<int>{9, 1, 7}, {9, 1, 7});
    check("extremes", std::vector<int>{(-2147483647 - 1), 2147483647}, {2147483647});
    check("duplicates", std::vector<int>{3, 3, 2, 3}, {3, 3, 3});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
KeepOdd.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

import java.util.Arrays;

final class KeepOdd {
  private KeepOdd() {}

  /** Returns a new array of the odd items, in their order. */
  static int[] keepOdd(int[] items) {
    // Use != 0, not == 1: the remainder of a negative item can be negative.
    return Arrays.stream(items).filter(x -> x % 2 != 0).toArray();
  }
}
KeepOddTest.java 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-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 KeepOddTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("mixed", new int[] {1, 2, 3, 4, 5}, new int[] {1, 3, 5}),
        Arguments.of("tens", new int[] {10, 15, 20, 25}, new int[] {15, 25}),
        Arguments.of("empty", new int[] {}, new int[] {}),
        Arguments.of("none-odd", new int[] {2, 4, 6}, new int[] {}),
        Arguments.of("all-odd", new int[] {1, 3, 5}, new int[] {1, 3, 5}),
        Arguments.of("negative", new int[] {-3, -2, -1, 0}, new int[] {-3, -1}),
        Arguments.of("zero", new int[] {0}, new int[] {}),
        Arguments.of("order", new int[] {9, 1, 7}, new int[] {9, 1, 7}),
        Arguments.of("extremes", new int[] {-2147483648, 2147483647}, new int[] {2147483647}),
        Arguments.of("duplicates", new int[] {3, 3, 2, 3}, new int[] {3, 3, 3}));
  }

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

#include "keep_odd.h"

size_t keep_odd(const int *items, size_t n, int *out) {
    size_t k = 0;
    for (size_t i = 0; i < n; i++) {
        // Use != 0, not == 1: the remainder of a negative item can be negative.
        if (items[i] % 2 != 0) {
            out[k++] = items[i];
        }
    }
    return k;
}
keep_odd.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

#ifndef KEEP_ODD_H
#define KEEP_ODD_H

#include <stddef.h>

// keep_odd copies the odd items of items[0..n) to out, in their order, and
// returns the number of items it copied. out must have room for n items.
size_t keep_odd(const int *items, size_t n, int *out);

#endif
test_keep_odd.c 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

#include "keep_odd.h"

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

static int failures = 0;

#define L(...) {__VA_ARGS__}

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

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

int main(void) {
    CHECK("mixed", 5, L(1, 2, 3, 4, 5), 3, L(1, 3, 5));
    CHECK("tens", 4, L(10, 15, 20, 25), 2, L(15, 25));
    CHECK("empty", 0, L(0), 0, L(0));
    CHECK("none-odd", 3, L(2, 4, 6), 0, L(0));
    CHECK("all-odd", 3, L(1, 3, 5), 3, L(1, 3, 5));
    CHECK("negative", 4, L(-3, -2, -1, 0), 2, L(-3, -1));
    CHECK("zero", 1, L(0), 0, L(0));
    CHECK("order", 3, L(9, 1, 7), 3, L(9, 1, 7));
    CHECK("extremes", 2, L((-2147483647 - 1), 2147483647), 1, L(2147483647));
    CHECK("duplicates", 4, L(3, 3, 2, 3), 3, L(3, 3, 3));
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
KeepOdd.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

using System.Linq;

public static class KeepOdd
{
    // ToArray runs the query now. Without it, Where runs each time the
    // result is read. Use != 0, not == 1: the remainder of a negative item can be negative.
    public static int[] Filter(int[] items) => items.Where(x => x % 2 != 0).ToArray();
}
KeepOddTests.cs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

using Xunit;

public sealed class KeepOddTests
{
    public static TheoryData<string, int[], int[]> Cases => new()
    {
        { "mixed", new int[] { 1, 2, 3, 4, 5 }, new int[] { 1, 3, 5 } },
        { "tens", new int[] { 10, 15, 20, 25 }, new int[] { 15, 25 } },
        { "empty", new int[0], new int[0] },
        { "none-odd", new int[] { 2, 4, 6 }, new int[0] },
        { "all-odd", new int[] { 1, 3, 5 }, new int[] { 1, 3, 5 } },
        { "negative", new int[] { -3, -2, -1, 0 }, new int[] { -3, -1 } },
        { "zero", new int[] { 0 }, new int[0] },
        { "order", new int[] { 9, 1, 7 }, new int[] { 9, 1, 7 } },
        { "extremes", new int[] { -2147483648, 2147483647 }, new int[] { 2147483647 } },
        { "duplicates", new int[] { 3, 3, 2, 3 }, new int[] { 3, 3, 3 } },
    };

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

/**
 * @param {number[]} items
 * @returns {number[]}
 */
export function keepOdd(items) {
  // Use !== 0, not === 1: the remainder of a negative item can be negative.
  return items.filter((x) => x % 2 !== 0);
}
keep_odd.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

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

import { keepOdd } from "./keep_odd.js";

const cases = [
  ["mixed", [1, 2, 3, 4, 5], [1, 3, 5]],
  ["tens", [10, 15, 20, 25], [15, 25]],
  ["empty", [], []],
  ["none-odd", [2, 4, 6], []],
  ["all-odd", [1, 3, 5], [1, 3, 5]],
  ["negative", [-3, -2, -1, 0], [-3, -1]],
  ["zero", [0], []],
  ["order", [9, 1, 7], [9, 1, 7]],
  ["extremes", [-2147483648, 2147483647], [2147483647]],
  ["duplicates", [3, 3, 2, 3], [3, 3, 3]],
];

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

export function keepOdd(items: readonly number[]): number[] {
  // Use !== 0, not === 1: the remainder of a negative item can be negative.
  return items.filter((x) => x % 2 !== 0);
}
keep_odd.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

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

import { keepOdd } from "./keep_odd.ts";

const cases: [string, number[], number[]][] = [
  ["mixed", [1, 2, 3, 4, 5], [1, 3, 5]],
  ["tens", [10, 15, 20, 25], [15, 25]],
  ["empty", [], []],
  ["none-odd", [2, 4, 6], []],
  ["all-odd", [1, 3, 5], [1, 3, 5]],
  ["negative", [-3, -2, -1, 0], [-3, -1]],
  ["zero", [0], []],
  ["order", [9, 1, 7], [9, 1, 7]],
  ["extremes", [-2147483648, 2147483647], [2147483647]],
  ["duplicates", [3, 3, 2, 3], [3, 3, 3]],
];

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

// Package keepodd keeps the odd items of a slice.
package keepodd

// KeepOdd returns a new slice of the odd items, in their order. The input
// slice does not change.
func KeepOdd(items []int) []int {
	out := []int{}
	for _, x := range items {
		// Use != 0, not == 1: the remainder of a negative item can be negative.
		if x%2 != 0 {
			out = append(out, x)
		}
	}
	return out
}
keep_odd_test.go 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

package keepodd

import (
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	items []int
	want  []int
}{
	{"mixed", []int{1, 2, 3, 4, 5}, []int{1, 3, 5}},
	{"tens", []int{10, 15, 20, 25}, []int{15, 25}},
	{"empty", []int{}, []int{}},
	{"none-odd", []int{2, 4, 6}, []int{}},
	{"all-odd", []int{1, 3, 5}, []int{1, 3, 5}},
	{"negative", []int{-3, -2, -1, 0}, []int{-3, -1}},
	{"zero", []int{0}, []int{}},
	{"order", []int{9, 1, 7}, []int{9, 1, 7}},
	{"extremes", []int{-2147483648, 2147483647}, []int{2147483647}},
	{"duplicates", []int{3, 3, 2, 3}, []int{3, 3, 3}},
}

func TestKeepOdd(t *testing.T) {
	for _, c := range cases {
		if got := KeepOdd(c.items); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}
keep_odd.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

/// Returns a new vector of the odd items, in their order.
pub fn keep_odd(items: &[i32]) -> Vec<i32> {
    // Use != 0, not == 1: the remainder of a negative item can be negative.
    items.iter().copied().filter(|x| x % 2 != 0).collect()
}
tests/keep_odd_test.rs 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/filter-a-list/.

use algo_filter_a_list::keep_odd;

#[test]
fn cases() {
    let cases: &[(&str, &[i32], &[i32])] = &[
        ("mixed", &[1, 2, 3, 4, 5], &[1, 3, 5]),
        ("tens", &[10, 15, 20, 25], &[15, 25]),
        ("empty", &[], &[]),
        ("none-odd", &[2, 4, 6], &[]),
        ("all-odd", &[1, 3, 5], &[1, 3, 5]),
        ("negative", &[-3, -2, -1, 0], &[-3, -1]),
        ("zero", &[0], &[]),
        ("order", &[9, 1, 7], &[9, 1, 7]),
        ("extremes", &[-2147483648, 2147483647], &[2147483647]),
        ("duplicates", &[3, 3, 2, 3], &[3, 3, 3]),
    ];
    for &(name, items, want) in cases {
        assert_eq!(keep_odd(items), want, "{name}");
    }
}
keep_odd.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/filter-a-list/.

# keep_odd ITEM...
# Prints the odd integer arguments, one on each line, in their order.
keep_odd() {
  local x
  for x in "$@"; do
    # Use != 0, not == 1: the remainder of a negative item can be negative.
    if ((x % 2 != 0)); then
      printf '%s\n' "$x"
    fi
  done
}
test_keep_odd.bats 36 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/filter-a-list/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/keep_odd.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 "mixed" { check keep_odd 1 2 3 4 5 -- 1 3 5; }
@test "tens" { check keep_odd 10 15 20 25 -- 15 25; }
@test "empty" { check keep_odd --; }
@test "none-odd" { check keep_odd 2 4 6 --; }
@test "all-odd" { check keep_odd 1 3 5 -- 1 3 5; }
@test "negative" { check keep_odd -3 -2 -1 0 -- -3 -1; }
@test "zero" { check keep_odd 0 --; }
@test "order" { check keep_odd 9 1 7 -- 9 1 7; }
@test "extremes" { check keep_odd -2147483648 2147483647 -- 2147483647; }
@test "duplicates" { check keep_odd 3 3 2 3 -- 3 3 3; }

References

  1. MDN Web Docs, Array.prototype.filter(), Description
  2. The Python Tutorial, More Control Flow Tools, 4.2 for Statements
  3. MDN Web Docs, Remainder (%), Description
  4. Java SE 25 API, Class ArrayList, Class description
  5. .NET API reference, Enumerable.Where method, Remarks
  6. Go standard library, package slices, DeleteFunc
  7. Rust standard library, struct Vec, retain, swap_remove
  8. cppreference.com, std::remove, std::remove_if, Notes
  9. 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