Taskintro
Loop over nested loops
Also called nested loops, loop over a grid, search a 2D array, break out of nested loops, labeled break, break outer loop, row and column loop, Loops/Nested.
Search a grid with a loop inside a loop, stop both loops at the first match, and know which break leaves only the inner loop.
- Evidence
- Code in 10 languages
Task
Search a grid of numbers for a value. The function find_in_grid(grid, target) loops over the rows, and for each row over the columns, and returns the row and the column of the first cell that equals target. If no cell matches, it returns (-1, -1). For example, in [[1, 2, 3], [4, 5, 6]] the value 5 is at (1, 1).
grid has 0 to 100 rows, and each row has 0 to 100 integers. The rows can have different lengths. "First" means in row-major order: each cell of row 0 comes before each cell of row 1. The Rosetta Code task searches a two-dimensional array in the same way, and asks how to break out of the nested loops1.
Solutions
| Language | Stop both loops |
|---|---|
| Java, JavaScript, TypeScript | outer: before the outer loop, break outer; |
| Go | outer: before the outer loop, break outer |
| Rust | 'outer: before the outer loop, break 'outer; |
| Python, C#, C, C++ | return from inside the inner loop |
| Bash | break 2 |
- Java. A break with a label "attempts to transfer control to the enclosing labeled statement (§14.7) that has the same Identifier as its label"2. The solution labels the outer loop and breaks to it.
- JavaScript and TypeScript. "You can jump to this label using a break or continue statement nested within the labeled statement"3.
- Go.
breakcan take the label of an enclosing loop, and "that is the one whose execution terminates"4. - Rust. "You can optionally specify a loop label on a loop that you can then use with break or continue to specify that those keywords apply to the labeled loop instead of the innermost loop"5.
- C#. "In nested loops, the break statement terminates only the innermost loop that contains it"6. The search is a function of its own, so
returnleaves both loops. Python, C and C++ usereturnin the same way. - Bash. "If n is supplied, break exits the nth enclosing loop"7, so
break 2leaves both loops. The function takes the target and then each row as one string of numbers, and prints the row and the column.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
first-cellandlast-cell: the match is in the first or the last cell, so the loops must include both ends.row-major: the value is at(0, 2)and at(1, 0). The row loop is the outer loop, so the result is(0, 2). A loop with the column outside would give(1, 0).missing: no cell matches, so both loops run to the end.empty-gridandempty-rows: the inner loop runs 0 times for an empty row. The search goes on to the next row.ragged: the rows have different lengths. The inner loop uses the length of its own row, not of row 0.negative: the grid and the target can be negative.
Pitfalls
- A plain
breakleaves only the inner loop. In Python,break"terminates the nearest enclosing loop"8. The outer loop goes on, so the code below finds 3 in each row, not only once. Theelseof aforloop runs "if no break occurred"9, and abreakafter it stops the outer loop too. A function withreturnis easier to read:
grid = [[1, 2], [3, 4], [3, 5]]
found = []
for r, row in enumerate(grid):
for c, x in enumerate(row):
if x == 3:
found.append((r, c))
break
print(found)
for r, row in enumerate(grid):
for c, x in enumerate(row):
if x == 3:
break
else:
continue
break
print(r, c)
[(1, 0), (2, 0)]
1 0
- In Go,
breakinside aswitchleaves theswitch. An unlabeledbreakends the innermostfor,switchorselectstatement4. In the first loop below, thebreakends theswitch, so the loops visit all 4 cells. The labeledbreakstops after 2 cells:
package main
import "fmt"
func main() {
grid := [][]int{{1, 2}, {3, 4}}
n := 0
for _, row := range grid {
for _, x := range row {
n++
switch {
case x == 2:
break
}
}
}
m := 0
outer:
for _, row := range grid {
for _, x := range row {
m++
switch {
case x == 2:
break outer
}
}
}
fmt.Println(n, m)
}
4 2
- Bash
breakalso leaves one loop. Withoutn, the outer loop goes on to the next row:
for row in "1 2" "3 4"; do
for x in $row; do
if ((x == 2)); then break; fi
echo "a $x"
done
done
for row in "1 2" "3 4"; do
for x in $row; do
if ((x == 2)); then break 2; fi
echo "b $x"
done
done
a 1
a 3
a 4
b 1
Related tasks
- Loop with an index: one index for one list.
- Loop over a collection: one loop over one list.
- Loop over several collections at once: one loop that walks several lists side by side.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-nested-loops/.
def find_in_grid(grid: list[list[int]], target: int) -> tuple[int, int]:
"""Return (row, column) of the first cell that equals target, or (-1, -1)."""
for r, row in enumerate(grid):
for c, x in enumerate(row):
if x == target:
# return leaves both loops. break would leave only the inner one.
return (r, c)
return (-1, -1)
test_find_in_grid.py 25 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-nested-loops/.
import pytest
from find_in_grid import find_in_grid
CASES = {
"middle": (([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 5), (1, 1)),
"first-twenty": (([[3, 8, 12], [5, 20, 20], [20, 1, 4]], 20), (1, 1)),
"first-cell": (([[9, 1], [2, 3]], 9), (0, 0)),
"last-cell": (([[1, 2], [3, 9]], 9), (1, 1)),
"row-major": (([[1, 2, 9], [9, 3, 4]], 9), (0, 2)),
"missing": (([[1, 2], [3, 4]], 9), (-1, -1)),
"empty-grid": (([], 1), (-1, -1)),
"empty-rows": (([[], [], [5]], 5), (2, 0)),
"ragged": (([[1], [2, 3, 4], [5, 6]], 6), (2, 1)),
"negative": (([[-1, -2], [-3, -4]], -3), (1, 0)),
}
@pytest.mark.parametrize("name", CASES)
def test_find_in_grid(name):
args, want = CASES[name]
assert find_in_grid(*args) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
#include "find_in_grid.hpp"
#include <cstddef>
#include <utility>
#include <vector>
std::pair<int, int> find_in_grid(const std::vector<std::vector<int>> &grid, int target) {
for (std::size_t r = 0; r < grid.size(); r++) {
for (std::size_t c = 0; c < grid[r].size(); c++) {
if (grid[r][c] == target) {
// return leaves both loops. break would leave only the inner one.
return {static_cast<int>(r), static_cast<int>(c)};
}
}
}
return {-1, -1};
}
find_in_grid.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
#pragma once
#include <utility>
#include <vector>
// find_in_grid returns the row and the column of the first cell that equals
// target, or {-1, -1} when no cell matches.
std::pair<int, int> find_in_grid(const std::vector<std::vector<int>> &grid, int target);
test_find_in_grid.cpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
#include "find_in_grid.hpp"
#include <iostream>
#include <string_view>
#include <utility>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<std::vector<int>> &grid, int target,
std::pair<int, int> want) {
if (find_in_grid(grid, target) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("middle", {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 5, {1, 1});
check("first-twenty", {{3, 8, 12}, {5, 20, 20}, {20, 1, 4}}, 20, {1, 1});
check("first-cell", {{9, 1}, {2, 3}}, 9, {0, 0});
check("last-cell", {{1, 2}, {3, 9}}, 9, {1, 1});
check("row-major", {{1, 2, 9}, {9, 3, 4}}, 9, {0, 2});
check("missing", {{1, 2}, {3, 4}}, 9, {-1, -1});
check("empty-grid", {}, 1, {-1, -1});
check("empty-rows", {{}, {}, {5}}, 5, {2, 0});
check("ragged", {{1}, {2, 3, 4}, {5, 6}}, 6, {2, 1});
check("negative", {{-1, -2}, {-3, -4}}, -3, {1, 0});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
final class FindInGrid {
private FindInGrid() {}
/** Returns {row, column} of the first cell that equals target, or {-1, -1}. */
static int[] findInGrid(int[][] grid, int target) {
int[] found = {-1, -1};
outer:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
if (grid[r][c] == target) {
found = new int[] {r, c};
// The label makes break leave both loops.
break outer;
}
}
}
return found;
}
}
FindInGridTest.java 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
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 FindInGridTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("middle", new int[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 5, new int[] {1, 1}),
Arguments.of("first-twenty", new int[][] {{3, 8, 12}, {5, 20, 20}, {20, 1, 4}}, 20, new int[] {1, 1}),
Arguments.of("first-cell", new int[][] {{9, 1}, {2, 3}}, 9, new int[] {0, 0}),
Arguments.of("last-cell", new int[][] {{1, 2}, {3, 9}}, 9, new int[] {1, 1}),
Arguments.of("row-major", new int[][] {{1, 2, 9}, {9, 3, 4}}, 9, new int[] {0, 2}),
Arguments.of("missing", new int[][] {{1, 2}, {3, 4}}, 9, new int[] {-1, -1}),
Arguments.of("empty-grid", new int[][] {}, 1, new int[] {-1, -1}),
Arguments.of("empty-rows", new int[][] {{}, {}, {5}}, 5, new int[] {2, 0}),
Arguments.of("ragged", new int[][] {{1}, {2, 3, 4}, {5, 6}}, 6, new int[] {2, 1}),
Arguments.of("negative", new int[][] {{-1, -2}, {-3, -4}}, -3, new int[] {1, 0}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void findInGrid(String name, int[][] grid, int target, int[] want) {
assertArrayEquals(want, FindInGrid.findInGrid(grid, target), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
#include "find_in_grid.h"
cell find_in_grid(const int *const *rows, const size_t *lens, size_t n, int target) {
for (size_t r = 0; r < n; r++) {
for (size_t c = 0; c < lens[r]; c++) {
if (rows[r][c] == target) {
// return leaves both loops. break would leave only the inner one.
return (cell){(int)r, (int)c};
}
}
}
return (cell){-1, -1};
}
find_in_grid.h 18 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
#ifndef FIND_IN_GRID_H
#define FIND_IN_GRID_H
#include <stddef.h>
typedef struct {
int row;
int col;
} cell;
// find_in_grid searches n rows. Row r has lens[r] numbers at rows[r]. It returns
// the row and the column of the first cell that equals target, or {-1, -1}.
cell find_in_grid(const int *const *rows, const size_t *lens, size_t n, int target);
#endif
test_find_in_grid.c 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
#include "find_in_grid.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *name, const int *const *rows, const size_t *lens, size_t n, int target, int row,
int col) {
cell got = find_in_grid(rows, lens, n, target);
if (got.row != row || got.col != col) {
fprintf(stderr, "case %s failed: got (%d, %d)\n", name, got.row, got.col);
failures++;
}
}
int main(void) {
static const int m0[] = {1, 2, 3}, m1[] = {4, 5, 6}, m2[] = {7, 8, 9};
const int *middle[] = {m0, m1, m2};
const size_t three3[] = {3, 3, 3};
check("middle", middle, three3, 3, 5, 1, 1);
static const int t0[] = {3, 8, 12}, t1[] = {5, 20, 20}, t2[] = {20, 1, 4};
const int *twenty[] = {t0, t1, t2};
check("first-twenty", twenty, three3, 3, 20, 1, 1);
static const int f0[] = {9, 1}, f1[] = {2, 3};
const int *first[] = {f0, f1};
const size_t two2[] = {2, 2};
check("first-cell", first, two2, 2, 9, 0, 0);
static const int l0[] = {1, 2}, l1[] = {3, 9};
const int *last[] = {l0, l1};
check("last-cell", last, two2, 2, 9, 1, 1);
static const int r0[] = {1, 2, 9}, r1[] = {9, 3, 4};
const int *rowmajor[] = {r0, r1};
const size_t three2[] = {3, 3};
check("row-major", rowmajor, three2, 2, 9, 0, 2);
static const int s0[] = {1, 2}, s1[] = {3, 4};
const int *missing[] = {s0, s1};
check("missing", missing, two2, 2, 9, -1, -1);
check("empty-grid", NULL, NULL, 0, 1, -1, -1);
static const int e2[] = {5};
const int *emptyrows[] = {NULL, NULL, e2};
const size_t elens[] = {0, 0, 1};
check("empty-rows", emptyrows, elens, 3, 5, 2, 0);
static const int g0[] = {1}, g1[] = {2, 3, 4}, g2[] = {5, 6};
const int *ragged[] = {g0, g1, g2};
const size_t glens[] = {1, 3, 2};
check("ragged", ragged, glens, 3, 6, 2, 1);
static const int n0[] = {-1, -2}, n1[] = {-3, -4};
const int *negative[] = {n0, n1};
check("negative", negative, two2, 2, -3, 1, 0);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
public static class FindInGrid
{
// Returns (row, column) of the first cell that equals target, or (-1, -1).
public static (int Row, int Col) Of(int[][] grid, int target)
{
for (int r = 0; r < grid.Length; r++)
{
for (int c = 0; c < grid[r].Length; c++)
{
if (grid[r][c] == target)
{
// return leaves both loops. break would leave only the inner one.
return (r, c);
}
}
}
return (-1, -1);
}
}
FindInGridTests.cs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
using Xunit;
public sealed class FindInGridTests
{
public static TheoryData<string, int[][], int, int, int> Cases => new()
{
{ "middle", new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9 } }, 5, 1, 1 },
{ "first-twenty", new[] { new[] { 3, 8, 12 }, new[] { 5, 20, 20 }, new[] { 20, 1, 4 } }, 20, 1, 1 },
{ "first-cell", new[] { new[] { 9, 1 }, new[] { 2, 3 } }, 9, 0, 0 },
{ "last-cell", new[] { new[] { 1, 2 }, new[] { 3, 9 } }, 9, 1, 1 },
{ "row-major", new[] { new[] { 1, 2, 9 }, new[] { 9, 3, 4 } }, 9, 0, 2 },
{ "missing", new[] { new[] { 1, 2 }, new[] { 3, 4 } }, 9, -1, -1 },
{ "empty-grid", new int[0][], 1, -1, -1 },
{ "empty-rows", new[] { new int[0], new int[0], new[] { 5 } }, 5, 2, 0 },
{ "ragged", new[] { new[] { 1 }, new[] { 2, 3, 4 }, new[] { 5, 6 } }, 6, 2, 1 },
{ "negative", new[] { new[] { -1, -2 }, new[] { -3, -4 } }, -3, 1, 0 },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[][] grid, int target, int row, int col)
{
Assert.NotNull(name);
Assert.Equal((row, col), FindInGrid.Of(grid, target));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
/**
* Returns [row, column] of the first cell that equals target, or [-1, -1].
* @param {number[][]} grid
* @param {number} target
* @returns {[number, number]}
*/
export function findInGrid(grid, target) {
let found = [-1, -1];
outer: for (let r = 0; r < grid.length; r++) {
for (let c = 0; c < grid[r].length; c++) {
if (grid[r][c] === target) {
found = [r, c];
// The label makes break leave both loops.
break outer;
}
}
}
return found;
}
find_in_grid.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { findInGrid } from "./find_in_grid.js";
const cases = [
["middle", [[1, 2, 3], [4, 5, 6], [7, 8, 9]], 5, [1, 1]],
["first-twenty", [[3, 8, 12], [5, 20, 20], [20, 1, 4]], 20, [1, 1]],
["first-cell", [[9, 1], [2, 3]], 9, [0, 0]],
["last-cell", [[1, 2], [3, 9]], 9, [1, 1]],
["row-major", [[1, 2, 9], [9, 3, 4]], 9, [0, 2]],
["missing", [[1, 2], [3, 4]], 9, [-1, -1]],
["empty-grid", [], 1, [-1, -1]],
["empty-rows", [[], [], [5]], 5, [2, 0]],
["ragged", [[1], [2, 3, 4], [5, 6]], 6, [2, 1]],
["negative", [[-1, -2], [-3, -4]], -3, [1, 0]],
];
for (const [name, grid, target, want] of cases) {
test(name, () => {
assert.deepEqual(findInGrid(grid, target), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
export function findInGrid(grid: readonly (readonly number[])[], target: number): [number, number] {
let found: [number, number] = [-1, -1];
outer: for (let r = 0; r < grid.length; r++) {
for (let c = 0; c < grid[r].length; c++) {
if (grid[r][c] === target) {
found = [r, c];
// The label makes break leave both loops.
break outer;
}
}
}
return found;
}
find_in_grid.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { findInGrid } from "./find_in_grid.ts";
const cases: [string, number[][], number, [number, number]][] = [
["middle", [[1, 2, 3], [4, 5, 6], [7, 8, 9]], 5, [1, 1]],
["first-twenty", [[3, 8, 12], [5, 20, 20], [20, 1, 4]], 20, [1, 1]],
["first-cell", [[9, 1], [2, 3]], 9, [0, 0]],
["last-cell", [[1, 2], [3, 9]], 9, [1, 1]],
["row-major", [[1, 2, 9], [9, 3, 4]], 9, [0, 2]],
["missing", [[1, 2], [3, 4]], 9, [-1, -1]],
["empty-grid", [], 1, [-1, -1]],
["empty-rows", [[], [], [5]], 5, [2, 0]],
["ragged", [[1], [2, 3, 4], [5, 6]], 6, [2, 1]],
["negative", [[-1, -2], [-3, -4]], -3, [1, 0]],
];
for (const [name, grid, target, want] of cases) {
test(name, () => {
assert.deepEqual(findInGrid(grid, target), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
// Package findingrid searches a grid with nested loops.
package findingrid
// FindInGrid returns the row and the column of the first cell that equals
// target, or -1, -1 when no cell matches.
func FindInGrid(grid [][]int, target int) (int, int) {
row, col := -1, -1
outer:
for r, cells := range grid {
for c, x := range cells {
if x == target {
row, col = r, c
// The label makes break leave both loops.
break outer
}
}
}
return row, col
}
find_in_grid_test.go 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
package findingrid
import "testing"
var cases = []struct {
name string
grid [][]int
target int
row, col int
}{
{"middle", [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 5, 1, 1},
{"first-twenty", [][]int{{3, 8, 12}, {5, 20, 20}, {20, 1, 4}}, 20, 1, 1},
{"first-cell", [][]int{{9, 1}, {2, 3}}, 9, 0, 0},
{"last-cell", [][]int{{1, 2}, {3, 9}}, 9, 1, 1},
{"row-major", [][]int{{1, 2, 9}, {9, 3, 4}}, 9, 0, 2},
{"missing", [][]int{{1, 2}, {3, 4}}, 9, -1, -1},
{"empty-grid", [][]int{}, 1, -1, -1},
{"empty-rows", [][]int{{}, {}, {5}}, 5, 2, 0},
{"ragged", [][]int{{1}, {2, 3, 4}, {5, 6}}, 6, 2, 1},
{"negative", [][]int{{-1, -2}, {-3, -4}}, -3, 1, 0},
}
func TestFindInGrid(t *testing.T) {
for _, c := range cases {
if r, col := FindInGrid(c.grid, c.target); r != c.row || col != c.col {
t.Errorf("%s: got (%d, %d), want (%d, %d)", c.name, r, col, c.row, c.col)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
/// Returns (row, column) of the first cell that equals target, or (-1, -1).
pub fn find_in_grid(grid: &[Vec<i32>], target: i32) -> (isize, isize) {
let mut found = (-1, -1);
'outer: for (r, row) in grid.iter().enumerate() {
for (c, &x) in row.iter().enumerate() {
if x == target {
found = (r as isize, c as isize);
// The label makes break leave both loops.
break 'outer;
}
}
}
found
}
tests/find_in_grid_test.rs 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-nested-loops/.
use algo_loop_over_nested_loops::find_in_grid;
#[test]
fn cases() {
let cases: Vec<(&str, Vec<Vec<i32>>, i32, (isize, isize))> = vec![
("middle", vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]], 5, (1, 1)),
("first-twenty", vec![vec![3, 8, 12], vec![5, 20, 20], vec![20, 1, 4]], 20, (1, 1)),
("first-cell", vec![vec![9, 1], vec![2, 3]], 9, (0, 0)),
("last-cell", vec![vec![1, 2], vec![3, 9]], 9, (1, 1)),
("row-major", vec![vec![1, 2, 9], vec![9, 3, 4]], 9, (0, 2)),
("missing", vec![vec![1, 2], vec![3, 4]], 9, (-1, -1)),
("empty-grid", vec![], 1, (-1, -1)),
("empty-rows", vec![vec![], vec![], vec![5]], 5, (2, 0)),
("ragged", vec![vec![1], vec![2, 3, 4], vec![5, 6]], 6, (2, 1)),
("negative", vec![vec![-1, -2], vec![-3, -4]], -3, (1, 0)),
];
for (name, grid, target, want) in cases {
assert_eq!(find_in_grid(&grid, target), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-nested-loops/.
# find_in_grid TARGET ROW...
# Each ROW is one string of numbers split by spaces. Prints the row and the
# column of the first cell that equals TARGET, or "-1 -1".
find_in_grid() {
local target=$1 row_text r=0 c x found="-1 -1"
shift
local -a cells
for row_text in "$@"; do
read -r -a cells <<<"$row_text"
c=0
for x in "${cells[@]}"; do
if ((x == target)); then
found="$r $c"
# break 2 leaves both loops. break would leave only the inner one.
break 2
fi
((c += 1))
done
((r += 1))
done
printf '%s\n' "$found"
}
test_find_in_grid.bats 28 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-nested-loops/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/find_in_grid.sh"
}
check() { # check WANT TARGET ROW...
local want=$1
shift
local got
got=$(find_in_grid "$@"; printf x)
[ "$got" = "$want"$'\n'x ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "middle" { check "1 1" 5 "1 2 3" "4 5 6" "7 8 9"; }
@test "first-twenty" { check "1 1" 20 "3 8 12" "5 20 20" "20 1 4"; }
@test "first-cell" { check "0 0" 9 "9 1" "2 3"; }
@test "last-cell" { check "1 1" 9 "1 2" "3 9"; }
@test "row-major" { check "0 2" 9 "1 2 9" "9 3 4"; }
@test "missing" { check "-1 -1" 9 "1 2" "3 4"; }
@test "empty-grid" { check "-1 -1" 1; }
@test "empty-rows" { check "2 0" 5 "" "" "5"; }
@test "ragged" { check "2 1" 6 "1" "2 3 4" "5 6"; }
@test "negative" { check "1 0" -3 "-1 -2" "-3 -4"; }
References
- Loops/Nested, Rosetta Code (the RosettaCodeData mirror), Task
- The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.15 The break Statement
- Labeled statement, MDN Web Docs, Description
- The Go Programming Language Specification, Break statements
- Control Flow, The Rust Programming Language, Disambiguating with Loop Labels
- Jump statements, C# language reference, The break statement
- Bash Reference Manual, 4.1 Bourne Shell Builtins
- Simple statements, The Python Language Reference, 7.9 The break statement
- More Control Flow Tools, The Python Tutorial, 4.5 else Clauses on Loops
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 36PTCF Edit this page History Report an error Markdown