Taskintro
Loop over several collections at once
Also called loop over multiple arrays, iterate over three lists, parallel iteration, lockstep loop, zip three lists, loop over arrays simultaneously, Loop over multiple arrays simultaneously.
Walk three lists side by side in one loop, join the items at each index, and stop at the end of the shortest list instead of reading past the end of one.
- Evidence
- Code in 10 languages
Task
Loop over three lists at the same time, and join the items that have the same index. The function zip_join(lower, upper, digits) returns, for each index i, the string lower[i] + upper[i] + digits[i]. This is the example of the Rosetta Code task: the lists (a, b, c), (A, B, C) and (1, 2, 3) give aA1, bB2 and cC31.
lower and upper are lists of strings, and digits is a list of 32-bit signed integers. Each list has 0 to 1000 items. The lists can have different lengths, and the task asks what happens then1. Here the loop stops at the end of the shortest list, so the result has as many items as the shortest list.
Solutions
| Language | One loop over three lists |
|---|---|
| Python | for a, b, d in zip(lower, upper, digits): |
| C# | foreach (var (a, b, d) in lower.Zip(upper, digits)) |
| Rust | for ((a, b), d) in lower.iter().zip(upper).zip(digits) |
| C++ | for (auto [a, b, d] : std::views::zip(lower, upper, digits)) |
| Go | for i := range min(len(lower), len(upper), len(digits)) |
| JavaScript, TypeScript, Java, C | an index from 0 to the smallest length |
| Bash | three array names, an index to the smallest length |
- Python.
ziptakes any number of lists. "By default, zip() stops when the shortest iterable is exhausted"2. - C#. One overload of
Ziptakes three sequences and "Produces a sequence of tuples with elements from the three specified sequences"3. "If the sequences do not have the same number of elements, the method merges sequences until it reaches the end of one of them"3. - Rust.
zipjoins two iterators, "returning a tuple where the first element comes from the first iterator, and the second element comes from the second iterator"4. For three lists, the solution zips twice, so each item is a pair inside a pair. - C++.
zip_viewmakes a view "whose i th element is a tuple-like value consisting of the i th elements of all views", and "The size of produced view is the minimum of sizes of all adapted views"5. - Go. The built-in
mintakes "a fixed number of arguments of ordered types"6, so one call gives the smallest of the three lengths. - JavaScript, TypeScript, Java and C. The solution calculates the smallest length first, and then uses an index that is in all three lists.
- Bash. A function cannot take three arrays as arguments, so it takes the names of the arrays. A nameref is "a reference to another variable"7, and the function reads the arrays through three namerefs. It prints one string on each line.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
shorter-firstandshorter-last: the shortest list is the first or the last one. The result has one item in both cases.one-emptyandall-empty: when one list is empty, the result is empty.negative: a negative number keeps its sign, so the string isaA-5.empty-strings: an empty string adds nothing, so"" + "A" + 1isA1.
Pitfalls
- An index loop with the length of one list reads past the end of a shorter list. In JavaScript, the missing item is
undefined, and+turns it into text. Use the smallest length:
const lower = ["a", "b", "c"];
const upper = ["A", "B"];
const digits = [1, 2, 3];
const out = [];
for (let i = 0; i < lower.length; i++) {
out.push(lower[i] + upper[i] + digits[i]);
}
console.log(out.join(" "));
const n = Math.min(lower.length, upper.length, digits.length);
console.log(n);
aA1 bB2 cundefined3
2
- Python
zipdrops the extra items without an error. If the lists must have the same length, usestrict=True: "If strict is True and one of the iterables is exhausted before the others, a ValueError is raised"2.
lower = ["a", "b", "c"]
upper = ["A", "B", "C"]
digits = [1, 2]
print([f"{a}{b}{d}" for a, b, d in zip(lower, upper, digits)])
try:
list(zip(lower, upper, digits, strict=True))
except ValueError:
print("ValueError")
['aA1', 'bB2']
ValueError
- Rust
zipof three lists gives nested pairs. Eachzipmakes a pair4, so the secondzipmakes a pair whose first part is a pair. The pattern must be((a, b), d), not(a, b, d):
fn main() {
let lower = ["a", "b"];
let upper = ["A", "B"];
let digits = [1, 2, 3];
let items: Vec<_> = lower.iter().zip(upper.iter()).zip(digits.iter()).collect();
println!("{items:?}");
}
[(("a", "A"), 1), (("b", "B"), 2)]
Related tasks
- Zip two lists: pair the items of two lists.
- Loop with an index: one list, with the index.
- Loop over a collection: one list, without the index.
- Loop over nested loops: a loop inside a loop, not 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-several-collections-at-once/.
def zip_join(lower: list[str], upper: list[str], digits: list[int]) -> list[str]:
"""Join the items at each index, up to the end of the shortest list."""
out = []
# zip stops at the end of the shortest list.
for a, b, d in zip(lower, upper, digits):
out.append(f"{a}{b}{d}")
return out
test_zip_join.py 23 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
import pytest
from zip_join import zip_join
CASES = {
"rosetta": ((["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]), ["aA1", "bB2", "cC3"]),
"words": ((["x", "y"], ["X", "Y"], [10, 20]), ["xX10", "yY20"]),
"shorter-first": ((["a"], ["A", "B"], [1, 2, 3]), ["aA1"]),
"shorter-last": ((["a", "b", "c"], ["A", "B", "C"], [1]), ["aA1"]),
"one-empty": ((["a", "b"], [], [1, 2]), []),
"all-empty": (([], [], []), []),
"negative": ((["a"], ["A"], [-5]), ["aA-5"]),
"empty-strings": ((["", "b"], ["A", ""], [1, 2]), ["A1", "b2"]),
}
@pytest.mark.parametrize("name", CASES)
def test_zip_join(name):
args, want = CASES[name]
assert zip_join(*args) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
#include "zip_join.hpp"
#include <ranges>
#include <string>
#include <vector>
std::vector<std::string> zip_join(const std::vector<std::string> &lower, const std::vector<std::string> &upper,
const std::vector<int> &digits) {
std::vector<std::string> out;
// views::zip stops at the end of the shortest range.
for (auto [a, b, d] : std::views::zip(lower, upper, digits)) {
out.push_back(a + b + std::to_string(d));
}
return out;
}
zip_join.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
#pragma once
#include <string>
#include <vector>
// zip_join joins the items at each index, up to the end of the shortest list.
std::vector<std::string> zip_join(const std::vector<std::string> &lower, const std::vector<std::string> &upper,
const std::vector<int> &digits);
test_zip_join.cpp 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
#include "zip_join.hpp"
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<std::string> &lower, const std::vector<std::string> &upper,
const std::vector<int> &digits, const std::vector<std::string> &want) {
if (zip_join(lower, upper, digits) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("rosetta", {"a", "b", "c"}, {"A", "B", "C"}, {1, 2, 3}, {"aA1", "bB2", "cC3"});
check("words", {"x", "y"}, {"X", "Y"}, {10, 20}, {"xX10", "yY20"});
check("shorter-first", {"a"}, {"A", "B"}, {1, 2, 3}, {"aA1"});
check("shorter-last", {"a", "b", "c"}, {"A", "B", "C"}, {1}, {"aA1"});
check("one-empty", {"a", "b"}, {}, {1, 2}, {});
check("all-empty", {}, {}, {}, {});
check("negative", {"a"}, {"A"}, {-5}, {"aA-5"});
check("empty-strings", {"", "b"}, {"A", ""}, {1, 2}, {"A1", "b2"});
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-several-collections-at-once/.
import java.util.ArrayList;
import java.util.List;
final class ZipJoin {
private ZipJoin() {}
/** Joins the items at each index, up to the end of the shortest list. */
static List<String> zipJoin(String[] lower, String[] upper, int[] digits) {
List<String> out = new ArrayList<>();
// An index past the end of a shorter array would throw.
int n = Math.min(lower.length, Math.min(upper.length, digits.length));
for (int i = 0; i < n; i++) {
out.add(lower[i] + upper[i] + digits[i]);
}
return out;
}
}
ZipJoinTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
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 ZipJoinTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("rosetta", new String[] {"a", "b", "c"}, new String[] {"A", "B", "C"}, new int[] {1, 2, 3},
List.of("aA1", "bB2", "cC3")),
Arguments.of("words", new String[] {"x", "y"}, new String[] {"X", "Y"}, new int[] {10, 20},
List.of("xX10", "yY20")),
Arguments.of("shorter-first", new String[] {"a"}, new String[] {"A", "B"}, new int[] {1, 2, 3},
List.of("aA1")),
Arguments.of("shorter-last", new String[] {"a", "b", "c"}, new String[] {"A", "B", "C"}, new int[] {1},
List.of("aA1")),
Arguments.of("one-empty", new String[] {"a", "b"}, new String[] {}, new int[] {1, 2}, List.of()),
Arguments.of("all-empty", new String[] {}, new String[] {}, new int[] {}, List.of()),
Arguments.of("negative", new String[] {"a"}, new String[] {"A"}, new int[] {-5}, List.of("aA-5")),
Arguments.of("empty-strings", new String[] {"", "b"}, new String[] {"A", ""}, new int[] {1, 2},
List.of("A1", "b2")));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void zipJoin(String name, String[] lower, String[] upper, int[] digits, List<String> want) {
assertEquals(want, ZipJoin.zipJoin(lower, upper, digits), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
#include "zip_join.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
size_t zip_join(const char *const *lower, size_t nl, const char *const *upper, size_t nu, const int *digits,
size_t nd, char **out) {
// An index past the end of a shorter array is undefined behavior.
size_t n = nl < nu ? nl : nu;
n = n < nd ? n : nd;
for (size_t i = 0; i < n; i++) {
// 12 bytes hold any int in decimal with its sign, and 1 more holds the 0.
size_t size = strlen(lower[i]) + strlen(upper[i]) + 13;
out[i] = malloc(size);
if (out[i] == NULL) {
for (size_t j = 0; j < i; j++) {
free(out[j]);
}
return (size_t)-1;
}
snprintf(out[i], size, "%s%s%d", lower[i], upper[i], digits[i]);
}
return n;
}
zip_join.h 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
#ifndef ZIP_JOIN_H
#define ZIP_JOIN_H
#include <stddef.h>
// zip_join joins lower[i], upper[i] and the decimal form of digits[i] for each
// index i below the smallest of the three lengths. It writes a new string for
// each index to out, which must have room for the smallest length, and returns
// the number of strings. The caller frees each string. It returns (size_t)-1
// when malloc fails.
size_t zip_join(const char *const *lower, size_t nl, const char *const *upper, size_t nu, const int *digits,
size_t nd, char **out);
#endif
test_zip_join.c 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
#include "zip_join.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, const char *const *lower, size_t nl, const char *const *upper, size_t nu,
const int *digits, size_t nd, const char *const *want, size_t nw) {
char *out[8];
size_t n = zip_join(lower, nl, upper, nu, digits, nd, out);
int ok = n == nw;
for (size_t i = 0; ok && i < n; i++) {
ok = strcmp(out[i], want[i]) == 0;
}
if (n != (size_t)-1) {
for (size_t i = 0; i < n; i++) {
free(out[i]);
}
}
if (!ok) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
}
#define LEN(a) (sizeof(a) / sizeof((a)[0]))
int main(void) {
const char *abc[] = {"a", "b", "c"}, *ABC[] = {"A", "B", "C"};
const int d123[] = {1, 2, 3};
const char *w_rosetta[] = {"aA1", "bB2", "cC3"};
check("rosetta", abc, 3, ABC, 3, d123, 3, w_rosetta, LEN(w_rosetta));
const char *xy[] = {"x", "y"}, *XY[] = {"X", "Y"};
const int d1020[] = {10, 20};
const char *w_words[] = {"xX10", "yY20"};
check("words", xy, 2, XY, 2, d1020, 2, w_words, LEN(w_words));
const char *aA1[] = {"aA1"};
check("shorter-first", abc, 1, ABC, 2, d123, 3, aA1, 1);
check("shorter-last", abc, 3, ABC, 3, d123, 1, aA1, 1);
check("one-empty", abc, 2, NULL, 0, d123, 2, NULL, 0);
check("all-empty", NULL, 0, NULL, 0, NULL, 0, NULL, 0);
const int neg[] = {-5};
const char *w_neg[] = {"aA-5"};
check("negative", abc, 1, ABC, 1, neg, 1, w_neg, 1);
const char *es_l[] = {"", "b"}, *es_u[] = {"A", ""};
const char *w_es[] = {"A1", "b2"};
check("empty-strings", es_l, 2, es_u, 2, d123, 2, w_es, LEN(w_es));
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
using System.Globalization;
public static class ZipJoin
{
// Joins the items at each index, up to the end of the shortest list.
public static List<string> Of(IEnumerable<string> lower, IEnumerable<string> upper, IEnumerable<int> digits)
{
var result = new List<string>();
// Zip with three sequences stops at the end of the shortest one.
foreach (var (a, b, d) in lower.Zip(upper, digits))
{
result.Add(a + b + d.ToString(CultureInfo.InvariantCulture));
}
return result;
}
}
ZipJoinTests.cs 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
using Xunit;
public sealed class ZipJoinTests
{
public static TheoryData<string, string[], string[], int[], string[]> Cases => new()
{
{ "rosetta", new[] { "a", "b", "c" }, new[] { "A", "B", "C" }, new[] { 1, 2, 3 }, new[] { "aA1", "bB2", "cC3" } },
{ "words", new[] { "x", "y" }, new[] { "X", "Y" }, new[] { 10, 20 }, new[] { "xX10", "yY20" } },
{ "shorter-first", new[] { "a" }, new[] { "A", "B" }, new[] { 1, 2, 3 }, new[] { "aA1" } },
{ "shorter-last", new[] { "a", "b", "c" }, new[] { "A", "B", "C" }, new[] { 1 }, new[] { "aA1" } },
{ "one-empty", new[] { "a", "b" }, new string[0], new[] { 1, 2 }, new string[0] },
{ "all-empty", new string[0], new string[0], new int[0], new string[0] },
{ "negative", new[] { "a" }, new[] { "A" }, new[] { -5 }, new[] { "aA-5" } },
{ "empty-strings", new[] { "", "b" }, new[] { "A", "" }, new[] { 1, 2 }, new[] { "A1", "b2" } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, string[] lower, string[] upper, int[] digits, string[] want)
{
Assert.NotNull(name);
Assert.Equal(want, ZipJoin.Of(lower, upper, digits));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
/**
* Joins the items at each index, up to the end of the shortest list.
* @param {string[]} lower
* @param {string[]} upper
* @param {number[]} digits
* @returns {string[]}
*/
export function zipJoin(lower, upper, digits) {
const out = [];
// An index past the end of a shorter list would give undefined.
const n = Math.min(lower.length, upper.length, digits.length);
for (let i = 0; i < n; i++) {
out.push(`${lower[i]}${upper[i]}${digits[i]}`);
}
return out;
}
zip_join.test.js 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { zipJoin } from "./zip_join.js";
const cases = [
["rosetta", ["a", "b", "c"], ["A", "B", "C"], [1, 2, 3], ["aA1", "bB2", "cC3"]],
["words", ["x", "y"], ["X", "Y"], [10, 20], ["xX10", "yY20"]],
["shorter-first", ["a"], ["A", "B"], [1, 2, 3], ["aA1"]],
["shorter-last", ["a", "b", "c"], ["A", "B", "C"], [1], ["aA1"]],
["one-empty", ["a", "b"], [], [1, 2], []],
["all-empty", [], [], [], []],
["negative", ["a"], ["A"], [-5], ["aA-5"]],
["empty-strings", ["", "b"], ["A", ""], [1, 2], ["A1", "b2"]],
];
for (const [name, lower, upper, digits, want] of cases) {
test(name, () => {
assert.deepEqual(zipJoin(lower, upper, digits), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
export function zipJoin(lower: readonly string[], upper: readonly string[], digits: readonly number[]): string[] {
const out: string[] = [];
// An index past the end of a shorter list would give undefined.
const n = Math.min(lower.length, upper.length, digits.length);
for (let i = 0; i < n; i++) {
out.push(`${lower[i]}${upper[i]}${digits[i]}`);
}
return out;
}
zip_join.test.ts 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { zipJoin } from "./zip_join.ts";
const cases: [string, string[], string[], number[], string[]][] = [
["rosetta", ["a", "b", "c"], ["A", "B", "C"], [1, 2, 3], ["aA1", "bB2", "cC3"]],
["words", ["x", "y"], ["X", "Y"], [10, 20], ["xX10", "yY20"]],
["shorter-first", ["a"], ["A", "B"], [1, 2, 3], ["aA1"]],
["shorter-last", ["a", "b", "c"], ["A", "B", "C"], [1], ["aA1"]],
["one-empty", ["a", "b"], [], [1, 2], []],
["all-empty", [], [], [], []],
["negative", ["a"], ["A"], [-5], ["aA-5"]],
["empty-strings", ["", "b"], ["A", ""], [1, 2], ["A1", "b2"]],
];
for (const [name, lower, upper, digits, want] of cases) {
test(name, () => {
assert.deepEqual(zipJoin(lower, upper, digits), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
// Package zipjoin walks three slices side by side.
package zipjoin
import "strconv"
// ZipJoin joins the items at each index, up to the end of the shortest slice.
func ZipJoin(lower, upper []string, digits []int32) []string {
out := []string{}
// An index past the end of a shorter slice would panic.
n := min(len(lower), len(upper), len(digits))
for i := range n {
out = append(out, lower[i]+upper[i]+strconv.Itoa(int(digits[i])))
}
return out
}
zip_join_test.go 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
package zipjoin
import (
"slices"
"testing"
)
var cases = []struct {
name string
lower, upper []string
digits []int32
want []string
}{
{"rosetta", []string{"a", "b", "c"}, []string{"A", "B", "C"}, []int32{1, 2, 3}, []string{"aA1", "bB2", "cC3"}},
{"words", []string{"x", "y"}, []string{"X", "Y"}, []int32{10, 20}, []string{"xX10", "yY20"}},
{"shorter-first", []string{"a"}, []string{"A", "B"}, []int32{1, 2, 3}, []string{"aA1"}},
{"shorter-last", []string{"a", "b", "c"}, []string{"A", "B", "C"}, []int32{1}, []string{"aA1"}},
{"one-empty", []string{"a", "b"}, []string{}, []int32{1, 2}, []string{}},
{"all-empty", []string{}, []string{}, []int32{}, []string{}},
{"negative", []string{"a"}, []string{"A"}, []int32{-5}, []string{"aA-5"}},
{"empty-strings", []string{"", "b"}, []string{"A", ""}, []int32{1, 2}, []string{"A1", "b2"}},
}
func TestZipJoin(t *testing.T) {
for _, c := range cases {
if got := ZipJoin(c.lower, c.upper, c.digits); !slices.Equal(got, c.want) {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
/// Joins the items at each index, up to the end of the shortest slice.
pub fn zip_join(lower: &[&str], upper: &[&str], digits: &[i32]) -> Vec<String> {
let mut out = Vec::new();
// Two zips make a pair inside a pair: ((a, b), d).
for ((a, b), d) in lower.iter().zip(upper).zip(digits) {
out.push(format!("{a}{b}{d}"));
}
out
}
tests/zip_join_test.rs 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
use algo_loop_over_several_collections_at_once::zip_join;
#[test]
fn cases() {
let cases: &[(&str, &[&str], &[&str], &[i32], &[&str])] = &[
("rosetta", &["a", "b", "c"], &["A", "B", "C"], &[1, 2, 3], &["aA1", "bB2", "cC3"]),
("words", &["x", "y"], &["X", "Y"], &[10, 20], &["xX10", "yY20"]),
("shorter-first", &["a"], &["A", "B"], &[1, 2, 3], &["aA1"]),
("shorter-last", &["a", "b", "c"], &["A", "B", "C"], &[1], &["aA1"]),
("one-empty", &["a", "b"], &[], &[1, 2], &[]),
("all-empty", &[], &[], &[], &[]),
("negative", &["a"], &["A"], &[-5], &["aA-5"]),
("empty-strings", &["", "b"], &["A", ""], &[1, 2], &["A1", "b2"]),
];
for &(name, lower, upper, digits, want) in cases {
assert_eq!(zip_join(lower, upper, digits), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
# zip_join LOWER UPPER DIGITS
# Takes the names of three arrays. For each index below the smallest length,
# prints the three items joined, one string on each line.
zip_join() {
# Namerefs read the arrays of the caller. The long names avoid a clash with
# the names that the caller passes.
local -n zip_join_l=$1 zip_join_u=$2 zip_join_d=$3
local n=${#zip_join_l[@]} i
((${#zip_join_u[@]} < n)) && n=${#zip_join_u[@]}
((${#zip_join_d[@]} < n)) && n=${#zip_join_d[@]}
for ((i = 0; i < n; i++)); do
printf '%s\n' "${zip_join_l[i]}${zip_join_u[i]}${zip_join_d[i]}"
done
}
test_zip_join.bats 50 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-over-several-collections-at-once/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/zip_join.sh"
}
check() { # check WANT... (the arrays are lower, upper and digits)
local got want
# The x keeps the trailing newlines, which $(...) removes.
got=$(zip_join lower upper digits; printf x)
want=$(if (($# > 0)); then printf '%s\n' "$@"; fi; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "rosetta" {
lower=(a b c) upper=(A B C) digits=(1 2 3)
check aA1 bB2 cC3
}
@test "words" {
lower=(x y) upper=(X Y) digits=(10 20)
check xX10 yY20
}
@test "shorter-first" {
lower=(a) upper=(A B) digits=(1 2 3)
check aA1
}
@test "shorter-last" {
lower=(a b c) upper=(A B C) digits=(1)
check aA1
}
@test "one-empty" {
lower=(a b) upper=() digits=(1 2)
check
}
@test "all-empty" {
lower=() upper=() digits=()
check
}
@test "negative" {
lower=(a) upper=(A) digits=(-5)
check aA-5
}
@test "empty-strings" {
lower=("" b) upper=(A "") digits=(1 2)
check A1 b2
}
References
- Loop over multiple arrays simultaneously, Rosetta Code (the RosettaCodeData mirror), Task
- Built-in Functions, The Python Standard Library, zip()
- Enumerable.Zip Method, .NET API reference, Zip<TFirst,TSecond,TThird>
- Iterator in std::iter, The Rust Standard Library, zip
- std::ranges::zip_view, std::views::zip, cppreference.com, Description
- The Go Programming Language Specification, Min and max
- Bash Reference Manual, 3.4 Shell Parameters
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 MW1A52 Edit this page History Report an error Markdown