Programming Search⌘K

Taskintro

Find the index of a value

Also called index of, indexOf, position of a value, find the position of an item, first occurrence, last occurrence, findIndex, linear search for an index.

Find the first position of a value in a list, or a not-found result, and know how each language reports a value that is not there, -1, an error, an end iterator or an empty option.

Task

Find the position of a value in a list. The function index_of(items, value) returns the smallest index i with items[i] equal to value, or -1 if no item is equal to value. The positions start at 0. For example, index_of([4, 7, 1], 7) is 1, and index_of([4, 7, 1], 9) is -1.

The list can be in any order, so the search looks at the items one by one. The function must not change items. Each item and the value are 32-bit signed integers, and the list has 0 to 1000 items.

Solutions

Language First index Not found
Python items.index(value) ValueError
JavaScript, TypeScript items.indexOf(value) -1
Java a loop, or list.indexOf(value) -1
C# Array.IndexOf(items, value) -1, the lower bound minus 1
Go slices.Index(items, value) -1
Rust items.iter().position(|&x| x == value) None
C a loop a value that the caller agrees on
C++ std::ranges::find(items, value) the end iterator
Bash a loop that prints the index status 1
  • Python. sequence.index(value) will "Return the index of the first occurrence of value in sequence"1, and it "Raises ValueError if value is not found in sequence"1. The solution catches the error and returns -1.
  • JavaScript. indexOf returns "The first index of searchElement in the array; -1 if not found"2. findIndex takes a test function: it "returns the index of the first element in an array that satisfies the provided testing function"3. TypeScript uses the same method on a readonly number[].
  • Java. List.indexOf "Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element"4. An int[] has no such method, so the solution uses a loop.
  • C#. Array.IndexOf returns "The index of the first occurrence of value in array, if found; otherwise, the lower bound of the array minus 1"5. The lower bound of a C# array is 0, so the result is -1.
  • Go. "Index returns the index of the first occurrence of v in s, or -1 if not present"6.
  • Rust. position "Searches for an element in an iterator, returning its index"7, as an Option<usize>. The solution turns None into -1 to match the contract, but Rust code often keeps the Option.
  • C. The solution returns a ptrdiff_t, a signed type, so it can return -1.
  • C++. std::find returns "an iterator to the first element in the source range [first, last) that satisfies specific criteria (or last if there is no such iterator)"8. std::distance "Returns the number of hops from first to last"9, which is the index. The solution returns -1 when the iterator is the end.
  • Bash. "Exit statuses fall between 0 and 255"10, so a function cannot return an index as its status. The solution prints the index and returns the status 1 when the value is not there.

Edge cases

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

  • empty: the index of any value in an empty list is -1.
  • single and single-absent: the value is at index 0, or it is not there.
  • first and last: the value at index 0 and at the last index. The result 0 is a valid index, so a caller must not use it as a truth value.
  • duplicates and all-same: the value is in the list more than once, and the result is the first index.
  • negative: the value is negative, and the result is not -1. The result -1 means only "not found".
  • limit and limit-absent: the smallest 32-bit integer is found, or is not found in a list that has only the largest.
  • Each test checks that items does not change. The task check whether a list contains a value gives only a yes or no answer.

Pitfalls

  • Python index raises an error, and the index 0 is falsy. index "Raises ValueError if value is not found in sequence"1, so a search for a missing value stops the program unless the code catches the error. Its optional start argument finds a later occurrence. Also, if a.index(x): is false when x is the first item:
a = [5, 7, 5]
print(a.index(5), a.index(5, 1))
try:
    a.index(9)
except ValueError as e:
    print(type(e).__name__)
i = a.index(5)
print("found" if i else "not found", i)
Output
0 2
ValueError
not found 0
  • JavaScript splice with the -1 from indexOf removes the last item. For the start of splice, "Negative index counts back from the end of the array"11. So a.splice(a.indexOf(x), 1) removes the last item when x is not there. Test for -1 first:
const a = [1, 2, 3];
a.splice(a.indexOf(9), 1);
console.log(a);
const b = [1, 2, 3];
const i = b.indexOf(9);
if (i !== -1) {
  b.splice(i, 1);
}
console.log(b);
Output
[ 1, 2 ]
[ 1, 2, 3 ]
  • Java binarySearch returns a negative number, not -1. It returns the "index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1)"12. So a test with == -1 misses most values that are not there. Test with < 0. The array must also be sorted:
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] a = {1, 3, 5};
    System.out.println(Arrays.binarySearch(a, 3) + " " + Arrays.binarySearch(a, 4) + " " + Arrays.binarySearch(a, 9));
    int r = Arrays.binarySearch(a, 4);
    System.out.println((r == -1) + " " + (r < 0) + " " + (-r - 1));
  }
}
Output
1 -3 -4
false true 2
  • C# IndexOf finds NaN, but == does not. Array.IndexOf uses Equals, and "If two Double.NaN values are tested for equality by calling the Equals method, the method returns true. However, if two Double.NaN values are tested for equality by using the equality operator, the operator returns false"13. So IndexOf and a test function with == give different answers:
double[] a = [1.0, double.NaN];
Console.WriteLine(Array.IndexOf(a, double.NaN));
Console.WriteLine(Array.FindIndex(a, x => x == double.NaN));
Console.WriteLine(Array.FindIndex(a, double.IsNaN));
Output
1
-1
1
  • Go the -1 from slices.Index is not a valid index. For an index expression a[x], "if x is out of range at run time, a run-time panic occurs"14. So a[slices.Index(a, x)] panics when x is not there. Test for -1 first:
package main

import (
	"fmt"
	"slices"
)

func main() {
	a := []int{5, 7}
	i := slices.Index(a, 9)
	fmt.Println(i)
	defer func() {
		fmt.Println("panic:", recover())
	}()
	fmt.Println(a[i])
}
Output
-1
panic: runtime error: index out of range [-1]
  • Rust rev().position() counts from the end. After rev, the first item is the last item of the slice, so position gives the distance from the end. rposition "Searches for an element in an iterator from the right, returning its index"7, and the index counts from the front:
fn main() {
    let a = [5, 7, 5, 8];
    println!("{:?}", a.iter().position(|&x| x == 5));
    println!("{:?}", a.iter().rev().position(|&x| x == 5));
    println!("{:?}", a.iter().rposition(|&x| x == 5));
}
Output
Some(0)
Some(1)
Some(2)
  • C a size_t function that returns -1 returns SIZE_MAX. When a value goes to an unsigned type, "the value 2b, where b is the number of value bits in the target type, is repeatedly subtracted or added to the source value until the result fits in the target type"15. So return -1; in a function that returns size_t gives SIZE_MAX, and a test with r < 0 is never true. Compare with (size_t)-1, or return a signed type. The output is from a machine with a 64-bit size_t:
#include <stddef.h>
#include <stdio.h>

static size_t find(const int *a, size_t n, int v) {
    for (size_t i = 0; i < n; i++) {
        if (a[i] == v) {
            return i;
        }
    }
    return -1;
}

int main(void) {
    const int a[] = {5, 7};
    size_t r = find(a, 2, 9);
    printf("%zu\n", r);
    printf("%d\n", r == (size_t)-1);
    return 0;
}
Output
18446744073709551615
1
  • C++ "not found" is the end, not -1. std::find returns the end iterator when no item matches8, and its distance from the start is the size of the range, a valid number. A string search returns std::string::npos, the largest size_t. Compare with the end or with npos, not with -1:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

int main() {
    std::vector<int> v{5, 7};
    auto it = std::ranges::find(v, 9);
    std::cout << (it == v.end()) << " " << std::distance(v.begin(), it) << "\n";
    std::string s = "abc";
    std::cout << (s.find('z') == std::string::npos) << " " << s.find('z') << "\n";
}
Output
1 2
1 18446744073709551615
  • Bash a return status wraps above 255. "Exit statuses fall between 0 and 255"10, so return 300 gives the status 44. A function that returns an index in its status gives a wrong index for a long list, and the index 0 looks like success. Print the index instead:
index_bad() { return "$1"; }
index_bad 3
echo $?
index_bad 300
echo $?
Output
3
44

Code

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

index_of.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-the-index-of-a-value/.

def index_of(items: list[int], value: int) -> int:
    """Return the first index of value in items, or -1 if it is not there."""
    try:
        return items.index(value)
    except ValueError:
        # list.index raises an error, not -1, when the value is not there.
        return -1
test_index_of.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-the-index-of-a-value/.

import pytest

from index_of import index_of

CASES = {
    "middle": ([4, 7, 1], 7, 1),
    "absent": ([4, 7, 1], 9, -1),
    "empty": ([], 0, -1),
    "single": ([5], 5, 0),
    "single-absent": ([5], 0, -1),
    "first": ([7, 8, 9], 7, 0),
    "last": ([7, 8, 9], 9, 2),
    "duplicates": ([3, 5, 3, 5], 5, 1),
    "all-same": ([2, 2, 2], 2, 0),
    "negative": ([0, -1, -2], -2, 2),
    "limit": ([2147483647, -2147483648], -2147483648, 1),
    "limit-absent": ([2147483647], -2147483648, -1),
}


@pytest.mark.parametrize("name", CASES)
def test_index_of(name):
    items, value, want = CASES[name]
    items0 = list(items)
    assert index_of(items, value) == want
    assert items == items0
index_of.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

#include "index_of.hpp"

#include <algorithm>
#include <cstddef>
#include <iterator>
#include <span>

std::ptrdiff_t index_of(std::span<const int> items, int value) {
    // find returns the end when the value is not there, and the distance to
    // the end is the size, not -1.
    const auto it = std::ranges::find(items, value);
    if (it == items.end()) {
        return -1;
    }
    return std::distance(items.begin(), it);
}
index_of.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

#pragma once

#include <cstddef>
#include <span>

// index_of returns the first index of value in items, or -1 if it is not there.
std::ptrdiff_t index_of(std::span<const int> items, int value);
test_index_of.cpp 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

#include "index_of.hpp"

#include <climits>
#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, int value, std::ptrdiff_t want) {
    if (index_of(items, value) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("middle", std::vector<int>{4, 7, 1}, 7, 1);
    check("absent", std::vector<int>{4, 7, 1}, 9, -1);
    check("empty", std::vector<int>{}, 0, -1);
    check("single", std::vector<int>{5}, 5, 0);
    check("single-absent", std::vector<int>{5}, 0, -1);
    check("first", std::vector<int>{7, 8, 9}, 7, 0);
    check("last", std::vector<int>{7, 8, 9}, 9, 2);
    check("duplicates", std::vector<int>{3, 5, 3, 5}, 5, 1);
    check("all-same", std::vector<int>{2, 2, 2}, 2, 0);
    check("negative", std::vector<int>{0, -1, -2}, -2, 2);
    check("limit", std::vector<int>{INT_MAX, INT_MIN}, INT_MIN, 1);
    check("limit-absent", std::vector<int>{INT_MAX}, INT_MIN, -1);
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
IndexOf.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

final class IndexOf {
  private IndexOf() {}

  /** Returns the first index of value in items, or -1 if it is not there. */
  static int indexOf(int[] items, int value) {
    // Arrays.binarySearch needs a sorted array, so use a loop.
    for (int i = 0; i < items.length; i++) {
      if (items[i] == value) {
        return i;
      }
    }
    return -1;
  }
}
IndexOfTest.java 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

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

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 IndexOfTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("middle", new int[] {4, 7, 1}, 7, 1),
        Arguments.of("absent", new int[] {4, 7, 1}, 9, -1),
        Arguments.of("empty", new int[] {}, 0, -1),
        Arguments.of("single", new int[] {5}, 5, 0),
        Arguments.of("single-absent", new int[] {5}, 0, -1),
        Arguments.of("first", new int[] {7, 8, 9}, 7, 0),
        Arguments.of("last", new int[] {7, 8, 9}, 9, 2),
        Arguments.of("duplicates", new int[] {3, 5, 3, 5}, 5, 1),
        Arguments.of("all-same", new int[] {2, 2, 2}, 2, 0),
        Arguments.of("negative", new int[] {0, -1, -2}, -2, 2),
        Arguments.of("limit", new int[] {2147483647, Integer.MIN_VALUE}, Integer.MIN_VALUE, 1),
        Arguments.of("limit-absent", new int[] {2147483647}, Integer.MIN_VALUE, -1));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void indexOf(String name, int[] items, int value, int want) {
    int[] items0 = items.clone();
    assertEquals(want, IndexOf.indexOf(items, value));
    assertArrayEquals(items0, items);
  }
}
index_of.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

#include "index_of.h"

#include <stddef.h>

ptrdiff_t index_of(const int *items, size_t n, int value) {
    for (size_t i = 0; i < n; i++) {
        if (items[i] == value) {
            return (ptrdiff_t)i;
        }
    }
    return -1;
}
index_of.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

#ifndef INDEX_OF_H
#define INDEX_OF_H

#include <stddef.h>

// index_of returns the first index of value in the n items, or -1 if it is
// not there. The result is a ptrdiff_t, a signed type, so -1 stays -1.
ptrdiff_t index_of(const int *items, size_t n, int value);

#endif
test_index_of.c 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

#include "index_of.h"

#include <limits.h>
#include <stddef.h>
#include <stdio.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

// C has no empty array, so an empty list is the array {0} with a count of 0.
#define CHECK(name, n, items, value, want)              \
    do {                                                \
        const int x[] = items;                          \
        if (index_of(x, n, value) != (want)) {          \
            fprintf(stderr, "case %s failed\n", name); \
            failures++;                                 \
        }                                               \
    } while (0)

int main(void) {
    CHECK("middle", 3, L(4, 7, 1), 7, 1);
    CHECK("absent", 3, L(4, 7, 1), 9, -1);
    CHECK("empty", 0, L(0), 0, -1);
    CHECK("single", 1, L(5), 5, 0);
    CHECK("single-absent", 1, L(5), 0, -1);
    CHECK("first", 3, L(7, 8, 9), 7, 0);
    CHECK("last", 3, L(7, 8, 9), 9, 2);
    CHECK("duplicates", 4, L(3, 5, 3, 5), 5, 1);
    CHECK("all-same", 3, L(2, 2, 2), 2, 0);
    CHECK("negative", 3, L(0, -1, -2), -2, 2);
    CHECK("limit", 2, L(INT_MAX, INT_MIN), INT_MIN, 1);
    CHECK("limit-absent", 1, L(INT_MAX), INT_MIN, -1);
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
IndexOf.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

public static class IndexOf
{
    // Returns the first index of value in items, or -1 if it is not there.
    // For an int[], the lower bound is 0, so Array.IndexOf gives -1.
    public static int Of(int[] items, int value) => Array.IndexOf(items, value);
}
IndexOfTests.cs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

using Xunit;

public sealed class IndexOfTests
{
    public static TheoryData<string, int[], int, int> Cases => new()
    {
        { "middle", new int[] { 4, 7, 1 }, 7, 1 },
        { "absent", new int[] { 4, 7, 1 }, 9, -1 },
        { "empty", new int[0], 0, -1 },
        { "single", new int[] { 5 }, 5, 0 },
        { "single-absent", new int[] { 5 }, 0, -1 },
        { "first", new int[] { 7, 8, 9 }, 7, 0 },
        { "last", new int[] { 7, 8, 9 }, 9, 2 },
        { "duplicates", new int[] { 3, 5, 3, 5 }, 5, 1 },
        { "all-same", new int[] { 2, 2, 2 }, 2, 0 },
        { "negative", new int[] { 0, -1, -2 }, -2, 2 },
        { "limit", new int[] { 2147483647, int.MinValue }, int.MinValue, 1 },
        { "limit-absent", new int[] { 2147483647 }, int.MinValue, -1 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] items, int value, int want)
    {
        Assert.NotNull(name);
        var items0 = (int[])items.Clone();
        Assert.Equal(want, IndexOf.Of(items, value));
        Assert.Equal(items0, items);
    }
}
index_of.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

/**
 * Returns the first index of value in items, or -1 if it is not there.
 * @param {number[]} items
 * @param {number} value
 * @returns {number}
 */
export function indexOf(items, value) {
  return items.indexOf(value);
}
index_of.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

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

import { indexOf } from "./index_of.js";

const cases = [
  ["middle", [4, 7, 1], 7, 1],
  ["absent", [4, 7, 1], 9, -1],
  ["empty", [], 0, -1],
  ["single", [5], 5, 0],
  ["single-absent", [5], 0, -1],
  ["first", [7, 8, 9], 7, 0],
  ["last", [7, 8, 9], 9, 2],
  ["duplicates", [3, 5, 3, 5], 5, 1],
  ["all-same", [2, 2, 2], 2, 0],
  ["negative", [0, -1, -2], -2, 2],
  ["limit", [2147483647, -2147483648], -2147483648, 1],
  ["limit-absent", [2147483647], -2147483648, -1],
];

for (const [name, items, value, want] of cases) {
  test(name, () => {
    const items0 = [...items];
    assert.equal(indexOf(items, value), want);
    assert.deepEqual(items, items0);
  });
}
index_of.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

export function indexOf(items: readonly number[], value: number): number {
  return items.indexOf(value);
}
index_of.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

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

import { indexOf } from "./index_of.ts";

const cases: [string, number[], number, number][] = [
  ["middle", [4, 7, 1], 7, 1],
  ["absent", [4, 7, 1], 9, -1],
  ["empty", [], 0, -1],
  ["single", [5], 5, 0],
  ["single-absent", [5], 0, -1],
  ["first", [7, 8, 9], 7, 0],
  ["last", [7, 8, 9], 9, 2],
  ["duplicates", [3, 5, 3, 5], 5, 1],
  ["all-same", [2, 2, 2], 2, 0],
  ["negative", [0, -1, -2], -2, 2],
  ["limit", [2147483647, -2147483648], -2147483648, 1],
  ["limit-absent", [2147483647], -2147483648, -1],
];

for (const [name, items, value, want] of cases) {
  test(name, () => {
    const items0 = [...items];
    assert.equal(indexOf(items, value), want);
    assert.deepEqual(items, items0);
  });
}
index_of.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

// Package indexof finds the position of a value in a slice.
package indexof

import "slices"

// IndexOf returns the first index of value in items, or -1 if it is not there.
func IndexOf(items []int, value int) int {
	return slices.Index(items, value)
}
index_of_test.go 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

package indexof

import (
	"math"
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	items []int
	value int
	want  int
}{
	{"middle", []int{4, 7, 1}, 7, 1},
	{"absent", []int{4, 7, 1}, 9, -1},
	{"empty", []int{}, 0, -1},
	{"single", []int{5}, 5, 0},
	{"single-absent", []int{5}, 0, -1},
	{"first", []int{7, 8, 9}, 7, 0},
	{"last", []int{7, 8, 9}, 9, 2},
	{"duplicates", []int{3, 5, 3, 5}, 5, 1},
	{"all-same", []int{2, 2, 2}, 2, 0},
	{"negative", []int{0, -1, -2}, -2, 2},
	{"limit", []int{2147483647, math.MinInt32}, math.MinInt32, 1},
	{"limit-absent", []int{2147483647}, math.MinInt32, -1},
}

func TestIndexOf(t *testing.T) {
	for _, c := range cases {
		items0 := slices.Clone(c.items)
		if got := IndexOf(c.items, c.value); got != c.want {
			t.Errorf("%s: got %d, want %d", c.name, got, c.want)
		}
		if !slices.Equal(c.items, items0) {
			t.Errorf("%s: the input changed", c.name)
		}
	}
}
index_of.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

/// Returns the first index of value in items, or -1 if it is not there.
///
/// Rust code would often return the `Option<usize>` from `position` as it
/// is. This function gives -1 to match the contract of the task.
pub fn index_of(items: &[i32], value: i32) -> i64 {
    match items.iter().position(|&x| x == value) {
        Some(i) => i as i64,
        None => -1,
    }
}
tests/index_of_test.rs 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/find-the-index-of-a-value/.

use algo_find_the_index_of_a_value::index_of;

#[test]
fn cases() {
    let cases: &[(&str, &[i32], i32, i64)] = &[
        ("middle", &[4, 7, 1], 7, 1),
        ("absent", &[4, 7, 1], 9, -1),
        ("empty", &[], 0, -1),
        ("single", &[5], 5, 0),
        ("single-absent", &[5], 0, -1),
        ("first", &[7, 8, 9], 7, 0),
        ("last", &[7, 8, 9], 9, 2),
        ("duplicates", &[3, 5, 3, 5], 5, 1),
        ("all-same", &[2, 2, 2], 2, 0),
        ("negative", &[0, -1, -2], -2, 2),
        ("limit", &[2147483647, i32::MIN], i32::MIN, 1),
        ("limit-absent", &[2147483647], i32::MIN, -1),
    ];
    for &(name, items, value, want) in cases {
        assert_eq!(index_of(items, value), want, "{name}");
    }
}
index_of.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-the-index-of-a-value/.

# index_of VALUE ITEM...
# Prints the first index of VALUE among the items, counted from 0, and
# returns 0. Prints nothing and returns 1 if VALUE is not there. The index is
# printed, not returned, because a return status is only 0 to 255.
index_of() {
  local value=$1 i=0 item
  shift
  for item in "$@"; do
    if [[ $item == "$value" ]]; then
      printf '%s\n' "$i"
      return 0
    fi
    i=$((i + 1))
  done
  return 1
}
test_index_of.bats 24 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/find-the-index-of-a-value/.

bats_require_minimum_version 1.5.0

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

@test "middle" { got=$(index_of 7 4 7 1) || return 1; [ "$got" = 1 ]; }
@test "absent" { if index_of 9 4 7 1 >/dev/null; then return 1; fi; got=$(index_of 9 4 7 1 || true); [ -z "$got" ]; }
@test "empty" { if index_of 0  >/dev/null; then return 1; fi; got=$(index_of 0  || true); [ -z "$got" ]; }
@test "single" { got=$(index_of 5 5) || return 1; [ "$got" = 0 ]; }
@test "single-absent" { if index_of 0 5 >/dev/null; then return 1; fi; got=$(index_of 0 5 || true); [ -z "$got" ]; }
@test "first" { got=$(index_of 7 7 8 9) || return 1; [ "$got" = 0 ]; }
@test "last" { got=$(index_of 9 7 8 9) || return 1; [ "$got" = 2 ]; }
@test "duplicates" { got=$(index_of 5 3 5 3 5) || return 1; [ "$got" = 1 ]; }
@test "all-same" { got=$(index_of 2 2 2 2) || return 1; [ "$got" = 0 ]; }
@test "negative" { got=$(index_of -2 0 -1 -2) || return 1; [ "$got" = 2 ]; }
@test "limit" { got=$(index_of -2147483648 2147483647 -2147483648) || return 1; [ "$got" = 1 ]; }
@test "limit-absent" { if index_of -2147483648 2147483647 >/dev/null; then return 1; fi; got=$(index_of -2147483648 2147483647 || true); [ -z "$got" ]; }
@test "past-255" { got=$(index_of x $(seq 300) x) || return 1; [ "$got" = 300 ]; }
@test "pattern" { got=$(index_of "*" a "*") || return 1; [ "$got" = 1 ]; }

References

  1. The Python Standard Library, Built-in Types, sequence.index()
  2. MDN Web Docs, Array.prototype.indexOf(), Return value
  3. MDN Web Docs, Array.prototype.findIndex(), Description
  4. Java SE 25 API, Interface List, indexOf(Object o)
  5. .NET API reference, Array.IndexOf Method, IndexOf(Array, Object), Returns
  6. Go standard library, package slices, func Index
  7. Rust standard library, Trait Iterator, position and rposition
  8. cppreference.com, std::find, Description
  9. cppreference.com, std::distance, Description
  10. Bash Reference Manual, 3.7.5 Exit Status
  11. MDN Web Docs, Array.prototype.splice(), Parameters, start
  12. Java SE 25 API, Class Arrays, binarySearch(int[] a, int key)
  13. .NET API reference, Double.Equals Method, Remarks, NaN
  14. The Go Programming Language Specification, Index expressions
  15. cppreference.com, C implicit conversions, Integer conversions

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