Taskintro
Zip two lists
Also called zip, pair the items of two lists, loop over two lists at the same time, iterate in parallel, combine two lists into pairs.
Pair the items of two lists of integers at the same index, and stop at the end of the shorter list.
- Evidence
- Code in 10 languages
Task
Pair the items of two lists of integers at the same index. The function zip_pairs(a, b) returns the pair (a[i], b[i]) for each index i that is in both lists, in index order. For example, zip_pairs([1, 2, 3], [4, 5, 6]) is [(1, 4), (2, 5), (3, 6)].
The two lists can have different lengths. Then the result stops at the end of the shorter list, so zip_pairs([1, 2, 3], [9]) is [(1, 9)]. The items are 32-bit signed integers, and each list can be empty.
Solutions
| Language | Pair the items up to the end of the shorter list |
|---|---|
| Python | list(zip(a, b)) |
| JavaScript, TypeScript | Array.from with the length Math.min(a.length, b.length) |
| Java | IntStream.range(0, Math.min(a.length, b.length)) and mapToObj |
| C# | a.Zip(b).ToArray() |
| Go | a loop to min(len(a), len(b)) |
| Rust | a.iter().copied().zip(b.iter().copied()).collect() |
| C | a loop to the smaller length, which writes to an output array |
| C++ | a loop over std::views::zip(a, b) |
| Bash | two arrays from read -ra, then a loop to the smaller length |
- The length. Python
zip, C#Zip, Rustzipand C++views::zipstop at the end of the shorter list. The other solutions calculate the smaller length first, and then use an index that is in both lists. - C. The caller gives an output array with room for the smaller length. The function returns the number of pairs.
- Bash. A function can only get strings, so each list is one argument with the items separated by spaces. The function prints one line
A_ITEM B_ITEMfor each pair.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: two empty lists give an empty list.one-empty: when one of the two lists is empty, the result is empty.shorter:[1]and[7, 8]give[(1, 7)], and[1, 2, 3]and[9]give[(1, 9)].negative: negative items stay in their pairs.extremes: -2147483648 and 2147483647 are items.duplicates: equal items stay in the result.
Pitfalls
- Python zip stops at the shortest list without an error. "By default, zip() stops when the shortest iterable is exhausted."1 If the lists must have the same length, use
strict=True: "If strict is True and one of the iterables is exhausted before the others, a ValueError is raised."1
a = [1, 2, 3]
b = [9]
print(list(zip(a, b)))
try:
list(zip(a, b, strict=True))
except ValueError as e:
print("ValueError:", e)
[(1, 9)]
ValueError: zip() argument 2 is shorter than argument 1
- JavaScript an index past the end gives undefined. MDN shows that "Using an index number larger than the array's length" gives
undefined2. Thusa.map((x, i) => [x, b[i]])makes pairs withundefinedwhenbis shorter. Use the smaller length:
const a = [1, 2, 3];
const b = [9];
console.log(a.map((x, i) => [x, b[i]]));
const n = Math.min(a.length, b.length);
console.log(Array.from({ length: n }, (_, i) => [a[i], b[i]]));
[ [ 1, 9 ], [ 2, undefined ], [ 3, undefined ] ]
[ [ 1, 9 ] ]
- Java a list of arrays compares the arrays by reference. "All objects, including arrays, implement the methods of this class."3 The
equalsmethod ofObject"returns true if and only if x and y refer to the same object"3. In the example, two lists of equal pairs are not equal.Arrays.deepEqualscompares the items:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<int[]> x = List.of(new int[] {1, 9});
List<int[]> y = List.of(new int[] {1, 9});
System.out.println(x.equals(y));
System.out.println(Arrays.deepEquals(x.toArray(), y.toArray()));
}
}
false
true
- C# Zip runs when the result is enumerated. "This method is implemented by using deferred execution."4 In the example,
a[0] = 100changes the first pair oflazy, but not ofcopy, becauseToArraymade the pairs before the change. Also, "If the sequences do not have the same number of elements, the method merges sequences until it reaches the end of one of them."4
using System;
using System.Linq;
int[] a = { 1, 2, 3 };
int[] b = { 9 };
var lazy = a.Zip(b);
var copy = a.Zip(b).ToArray();
a[0] = 100;
Console.WriteLine(lazy.First());
Console.WriteLine(copy[0]);
(100, 9)
(1, 9)
- Go an index past the end panics. For a slice, "if x is out of range at run time, a run-time panic occurs"5. In the example, the loop over
ausesb[1], butbhas 1 item. Loop tomin(len(a), len(b)):
package main
import "fmt"
func main() {
a := []int{1, 2, 3}
b := []int{9}
defer func() {
fmt.Println("panic:", recover())
}()
for i, x := range a {
fmt.Println(x, b[i])
}
}
1 9
panic: runtime error: index out of range [1] with length 1
- Rust zip stops at the shorter iterator without an error. "If either iterator returns None, next from the zipped iterator will return None."6 If the lists must have the same length, compare the lengths:
fn main() {
let a = [1, 2, 3];
let b = [9];
let pairs: Vec<(i32, i32)> = a.iter().copied().zip(b.iter().copied()).collect();
println!("{:?}", pairs);
if a.len() != b.len() {
println!("{} items of a have no pair", a.len() - pairs.len());
}
}
[(1, 9)]
2 items of a have no pair
- C a subtraction of two size_t values does not go below 0. "Unsigned integer arithmetic is always performed modulo"7 a power of 2. In the example,
na - nbis a large number, not -2, sona - nb > 0is true andwrongis 3. Compare the two lengths with<:
#include <stddef.h>
#include <stdio.h>
int main(void) {
size_t na = 1;
size_t nb = 3;
size_t wrong = na - nb > 0 ? nb : na;
size_t right = na < nb ? na : nb;
printf("%zu %zu\n", wrong, right);
printf("%d\n", na - nb > na);
return 0;
}
3 1
1
- C++ views::zip gives references to the items. "The size of produced view is the minimum of sizes of all adapted views."8 In the example, each element of the view refers to the items of
aandb, sox = ychangesa[0]to 9:
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<int> a{1, 2, 3};
std::vector<int> b{9};
auto z = std::views::zip(a, b);
std::cout << z.size() << '\n';
for (auto [x, y] : z) {
x = y;
}
for (int x : a) {
std::cout << x << (x == a.back() ? '\n' : ' ');
}
}
1
9 2 3
- Bash
${#b}is not the number of items. "${#name[subscript]}expands to the length of${name[subscript]}. If subscript is ‘@’ or ‘*’, the expansion is the number of elements in the array."9 Also, "Referencing an array variable without a subscript is equivalent to referencing with a subscript of 0."9 Thus${#b}is the length of the text10:
#!/usr/bin/env bash
b=(10 20 30)
echo "${#b} ${#b[@]}"
2 3
Related tasks
- Map over a list: change each item of one list.
- Iterate in chunks: take the items of one list in groups.
- Compute the Cartesian product: pair each item of one list with each item of the other list.
- Partition a list: split one list into two lists.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/zip-two-lists/.
def zip_pairs(a: list[int], b: list[int]) -> list[tuple[int, int]]:
"""Return the pairs (a[i], b[i]) up to the end of the shorter list."""
return list(zip(a, b))
test_zip_pairs.py 25 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/zip-two-lists/.
import pytest
from zip_pairs import zip_pairs
CASES = {
"same-length": ([1, 2, 3], [4, 5, 6], [(1, 4), (2, 5), (3, 6)]),
"tens": ([10, 20], [30, 40], [(10, 30), (20, 40)]),
"empty": ([], [], []),
"first-empty": ([], [1, 2], []),
"second-empty": ([1, 2], [], []),
"first-shorter": ([1], [7, 8], [(1, 7)]),
"second-shorter": ([1, 2, 3], [9], [(1, 9)]),
"negative": ([-1, -2], [3, -4], [(-1, 3), (-2, -4)]),
"extremes": ([-2147483648, 2147483647], [2147483647, -2147483648], [(-2147483648, 2147483647), (2147483647, -2147483648)]),
"duplicates": ([5, 5], [5, 5], [(5, 5), (5, 5)]),
}
@pytest.mark.parametrize("name", CASES)
def test_zip_pairs(name):
a, b, want = CASES[name]
assert zip_pairs(a, b) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
#include "zip_pairs.hpp"
#include <ranges>
std::vector<std::pair<int, int>> zip_pairs(std::span<const int> a, std::span<const int> b) {
std::vector<std::pair<int, int>> out;
// views::zip stops at the end of the shorter range.
for (auto [x, y] : std::views::zip(a, b)) {
out.emplace_back(x, y);
}
return out;
}
zip_pairs.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
#pragma once
#include <span>
#include <utility>
#include <vector>
// zip_pairs returns the pairs (a[i], b[i]) up to the end of the shorter span.
std::vector<std::pair<int, int>> zip_pairs(std::span<const int> a, std::span<const int> b);
test_zip_pairs.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
#include "zip_pairs.hpp"
#include <iostream>
#include <string_view>
#include <utility>
#include <vector>
static int failures = 0;
using Pairs = std::vector<std::pair<int, int>>;
static void check(std::string_view name, const std::vector<int> &a, const std::vector<int> &b, const Pairs &want) {
if (zip_pairs(a, b) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("same-length", std::vector<int>{1, 2, 3}, std::vector<int>{4, 5, 6}, Pairs{{1, 4}, {2, 5}, {3, 6}});
check("tens", std::vector<int>{10, 20}, std::vector<int>{30, 40}, Pairs{{10, 30}, {20, 40}});
check("empty", std::vector<int>{}, std::vector<int>{}, Pairs{});
check("first-empty", std::vector<int>{}, std::vector<int>{1, 2}, Pairs{});
check("second-empty", std::vector<int>{1, 2}, std::vector<int>{}, Pairs{});
check("first-shorter", std::vector<int>{1}, std::vector<int>{7, 8}, Pairs{{1, 7}});
check("second-shorter", std::vector<int>{1, 2, 3}, std::vector<int>{9}, Pairs{{1, 9}});
check("negative", std::vector<int>{-1, -2}, std::vector<int>{3, -4}, Pairs{{-1, 3}, {-2, -4}});
check("extremes", std::vector<int>{(-2147483647 - 1), 2147483647}, std::vector<int>{2147483647, (-2147483647 - 1)}, Pairs{{(-2147483647 - 1), 2147483647}, {2147483647, (-2147483647 - 1)}});
check("duplicates", std::vector<int>{5, 5}, std::vector<int>{5, 5}, Pairs{{5, 5}, {5, 5}});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
import java.util.stream.IntStream;
final class ZipPairs {
private ZipPairs() {}
/** Returns the pairs {a[i], b[i]} up to the end of the shorter array. */
static int[][] zipPairs(int[] a, int[] b) {
int n = Math.min(a.length, b.length);
return IntStream.range(0, n).mapToObj(i -> new int[] {a[i], b[i]}).toArray(int[][]::new);
}
}
ZipPairsTest.java 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
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 ZipPairsTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("same-length", new int[] {1, 2, 3}, new int[] {4, 5, 6}, new int[][] {{1, 4}, {2, 5}, {3, 6}}),
Arguments.of("tens", new int[] {10, 20}, new int[] {30, 40}, new int[][] {{10, 30}, {20, 40}}),
Arguments.of("empty", new int[] {}, new int[] {}, new int[][] {}),
Arguments.of("first-empty", new int[] {}, new int[] {1, 2}, new int[][] {}),
Arguments.of("second-empty", new int[] {1, 2}, new int[] {}, new int[][] {}),
Arguments.of("first-shorter", new int[] {1}, new int[] {7, 8}, new int[][] {{1, 7}}),
Arguments.of("second-shorter", new int[] {1, 2, 3}, new int[] {9}, new int[][] {{1, 9}}),
Arguments.of("negative", new int[] {-1, -2}, new int[] {3, -4}, new int[][] {{-1, 3}, {-2, -4}}),
Arguments.of("extremes", new int[] {-2147483648, 2147483647}, new int[] {2147483647, -2147483648}, new int[][] {{-2147483648, 2147483647}, {2147483647, -2147483648}}),
Arguments.of("duplicates", new int[] {5, 5}, new int[] {5, 5}, new int[][] {{5, 5}, {5, 5}}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void zipPairs(String name, int[] a, int[] b, int[][] want) {
// assertArrayEquals compares the inner arrays by their items.
assertArrayEquals(want, ZipPairs.zipPairs(a, b));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
#include "zip_pairs.h"
size_t zip_pairs(const int *a, size_t na, const int *b, size_t nb, struct int_pair *out) {
// Compare the lengths. Do not subtract them: size_t is unsigned.
size_t n = na < nb ? na : nb;
for (size_t i = 0; i < n; i++) {
out[i].first = a[i];
out[i].second = b[i];
}
return n;
}
zip_pairs.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
#ifndef ZIP_PAIRS_H
#define ZIP_PAIRS_H
#include <stddef.h>
struct int_pair {
int first;
int second;
};
// zip_pairs writes the pairs {a[i], b[i]} to out for each i that is less than
// both na and nb. out must have room for the smaller of na and nb. It returns
// the number of pairs.
size_t zip_pairs(const int *a, size_t na, const int *b, size_t nb, struct int_pair *out);
#endif
test_zip_pairs.c 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
#include "zip_pairs.h"
#include <stdio.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
// An empty list has a 0 in it, because C has no empty array. The counts give
// the real lengths.
#define CHECK(name, na, ga, nb, gb, m, ...) \
do { \
const int a[] = ga; \
const int b[] = gb; \
const struct int_pair w[] = {__VA_ARGS__}; \
struct int_pair out[sizeof a / sizeof a[0] + sizeof b / sizeof b[0]]; \
const size_t want_n = m; \
size_t k = zip_pairs(a, na, b, nb, out); \
int ok = k == want_n; \
for (size_t i = 0; ok && i < want_n; i++) { \
ok = out[i].first == w[i].first && out[i].second == w[i].second; \
} \
if (!ok) { \
fprintf(stderr, "case %s failed\n", name); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("same-length", 3, L(1, 2, 3), 3, L(4, 5, 6), 3, {1, 4}, {2, 5}, {3, 6});
CHECK("tens", 2, L(10, 20), 2, L(30, 40), 2, {10, 30}, {20, 40});
CHECK("empty", 0, L(0), 0, L(0), 0, {0, 0});
CHECK("first-empty", 0, L(0), 2, L(1, 2), 0, {0, 0});
CHECK("second-empty", 2, L(1, 2), 0, L(0), 0, {0, 0});
CHECK("first-shorter", 1, L(1), 2, L(7, 8), 1, {1, 7});
CHECK("second-shorter", 3, L(1, 2, 3), 1, L(9), 1, {1, 9});
CHECK("negative", 2, L(-1, -2), 2, L(3, -4), 2, {-1, 3}, {-2, -4});
CHECK("extremes", 2, L((-2147483647 - 1), 2147483647), 2, L(2147483647, (-2147483647 - 1)), 2, {(-2147483647 - 1), 2147483647}, {2147483647, (-2147483647 - 1)});
CHECK("duplicates", 2, L(5, 5), 2, L(5, 5), 2, {5, 5}, {5, 5});
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
using System.Linq;
public static class ZipPairs
{
// Pairs returns the pairs (a[i], b[i]) up to the end of the shorter array.
public static (int First, int Second)[] Pairs(int[] a, int[] b)
{
// Zip stops at the end of the shorter sequence.
return a.Zip(b).ToArray();
}
}
ZipPairsTests.cs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
using Xunit;
public sealed class ZipPairsTests
{
public static TheoryData<string, int[], int[], (int, int)[]> Cases => new()
{
{ "same-length", new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new (int, int)[] { (1, 4), (2, 5), (3, 6) } },
{ "tens", new int[] { 10, 20 }, new int[] { 30, 40 }, new (int, int)[] { (10, 30), (20, 40) } },
{ "empty", new int[0], new int[0], new (int, int)[0] },
{ "first-empty", new int[0], new int[] { 1, 2 }, new (int, int)[0] },
{ "second-empty", new int[] { 1, 2 }, new int[0], new (int, int)[0] },
{ "first-shorter", new int[] { 1 }, new int[] { 7, 8 }, new (int, int)[] { (1, 7) } },
{ "second-shorter", new int[] { 1, 2, 3 }, new int[] { 9 }, new (int, int)[] { (1, 9) } },
{ "negative", new int[] { -1, -2 }, new int[] { 3, -4 }, new (int, int)[] { (-1, 3), (-2, -4) } },
{ "extremes", new int[] { -2147483648, 2147483647 }, new int[] { 2147483647, -2147483648 }, new (int, int)[] { (-2147483648, 2147483647), (2147483647, -2147483648) } },
{ "duplicates", new int[] { 5, 5 }, new int[] { 5, 5 }, new (int, int)[] { (5, 5), (5, 5) } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[] a, int[] b, (int, int)[] want)
{
Assert.NotNull(name);
Assert.Equal(want, ZipPairs.Pairs(a, b));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
/**
* @param {number[]} a
* @param {number[]} b
* @returns {[number, number][]}
*/
export function zipPairs(a, b) {
// Stop at the end of the shorter array. An index past the end gives undefined.
const n = Math.min(a.length, b.length);
return Array.from({ length: n }, (_, i) => [a[i], b[i]]);
}
zip_pairs.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { zipPairs } from "./zip_pairs.js";
const cases = [
["same-length", [1, 2, 3], [4, 5, 6], [[1, 4], [2, 5], [3, 6]]],
["tens", [10, 20], [30, 40], [[10, 30], [20, 40]]],
["empty", [], [], []],
["first-empty", [], [1, 2], []],
["second-empty", [1, 2], [], []],
["first-shorter", [1], [7, 8], [[1, 7]]],
["second-shorter", [1, 2, 3], [9], [[1, 9]]],
["negative", [-1, -2], [3, -4], [[-1, 3], [-2, -4]]],
["extremes", [-2147483648, 2147483647], [2147483647, -2147483648], [[-2147483648, 2147483647], [2147483647, -2147483648]]],
["duplicates", [5, 5], [5, 5], [[5, 5], [5, 5]]],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
assert.deepEqual(zipPairs(a, b), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
export function zipPairs(a: readonly number[], b: readonly number[]): [number, number][] {
// Stop at the end of the shorter array. An index past the end gives undefined.
const n = Math.min(a.length, b.length);
return Array.from({ length: n }, (_, i) => [a[i], b[i]] as [number, number]);
}
zip_pairs.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { zipPairs } from "./zip_pairs.ts";
const cases: [string, number[], number[], [number, number][]][] = [
["same-length", [1, 2, 3], [4, 5, 6], [[1, 4], [2, 5], [3, 6]]],
["tens", [10, 20], [30, 40], [[10, 30], [20, 40]]],
["empty", [], [], []],
["first-empty", [], [1, 2], []],
["second-empty", [1, 2], [], []],
["first-shorter", [1], [7, 8], [[1, 7]]],
["second-shorter", [1, 2, 3], [9], [[1, 9]]],
["negative", [-1, -2], [3, -4], [[-1, 3], [-2, -4]]],
["extremes", [-2147483648, 2147483647], [2147483647, -2147483648], [[-2147483648, 2147483647], [2147483647, -2147483648]]],
["duplicates", [5, 5], [5, 5], [[5, 5], [5, 5]]],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
assert.deepEqual(zipPairs(a, b), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
// Package zippairs pairs the items of two slices.
package zippairs
// ZipPairs returns the pairs {a[i], b[i]} up to the end of the shorter slice.
func ZipPairs(a, b []int) [][2]int {
n := min(len(a), len(b))
out := make([][2]int, n)
for i := range n {
out[i] = [2]int{a[i], b[i]}
}
return out
}
zip_pairs_test.go 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
package zippairs
import (
"slices"
"testing"
)
var cases = []struct {
name string
a []int
b []int
want [][2]int
}{
{"same-length", []int{1, 2, 3}, []int{4, 5, 6}, [][2]int{{1, 4}, {2, 5}, {3, 6}}},
{"tens", []int{10, 20}, []int{30, 40}, [][2]int{{10, 30}, {20, 40}}},
{"empty", []int{}, []int{}, [][2]int{}},
{"first-empty", []int{}, []int{1, 2}, [][2]int{}},
{"second-empty", []int{1, 2}, []int{}, [][2]int{}},
{"first-shorter", []int{1}, []int{7, 8}, [][2]int{{1, 7}}},
{"second-shorter", []int{1, 2, 3}, []int{9}, [][2]int{{1, 9}}},
{"negative", []int{-1, -2}, []int{3, -4}, [][2]int{{-1, 3}, {-2, -4}}},
{"extremes", []int{-2147483648, 2147483647}, []int{2147483647, -2147483648}, [][2]int{{-2147483648, 2147483647}, {2147483647, -2147483648}}},
{"duplicates", []int{5, 5}, []int{5, 5}, [][2]int{{5, 5}, {5, 5}}},
}
func TestZipPairs(t *testing.T) {
for _, c := range cases {
if got := ZipPairs(c.a, c.b); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
/// Returns the pairs (a[i], b[i]) up to the end of the shorter slice.
pub fn zip_pairs(a: &[i32], b: &[i32]) -> Vec<(i32, i32)> {
// zip stops when one of the two iterators has no more items.
a.iter().copied().zip(b.iter().copied()).collect()
}
tests/zip_pairs_test.rs 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/zip-two-lists/.
use algo_zip_two_lists::zip_pairs;
#[test]
fn cases() {
let cases: Vec<(&str, &[i32], &[i32], Vec<(i32, i32)>)> = vec![
("same-length", &[1, 2, 3], &[4, 5, 6], vec![(1, 4), (2, 5), (3, 6)]),
("tens", &[10, 20], &[30, 40], vec![(10, 30), (20, 40)]),
("empty", &[], &[], vec![]),
("first-empty", &[], &[1, 2], vec![]),
("second-empty", &[1, 2], &[], vec![]),
("first-shorter", &[1], &[7, 8], vec![(1, 7)]),
("second-shorter", &[1, 2, 3], &[9], vec![(1, 9)]),
("negative", &[-1, -2], &[3, -4], vec![(-1, 3), (-2, -4)]),
("extremes", &[-2147483648, 2147483647], &[2147483647, -2147483648], vec![(-2147483648, 2147483647), (2147483647, -2147483648)]),
("duplicates", &[5, 5], &[5, 5], vec![(5, 5), (5, 5)]),
];
for (name, a, b, want) in cases {
assert_eq!(zip_pairs(a, b), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/zip-two-lists/.
# zip_pairs "A_ITEMS" "B_ITEMS"
# Each argument is a list of items, separated by spaces. Prints one line
# "A_ITEM B_ITEM" for each index that is in both lists, in index order.
zip_pairs() {
local -a a b
read -ra a <<<"$1"
read -ra b <<<"$2"
# ${#a[@]} is the number of items. ${#a} is the length of the first item.
local n=${#a[@]} i
if ((${#b[@]} < n)); then
n=${#b[@]}
fi
for ((i = 0; i < n; i++)); do
printf '%s %s\n' "${a[i]}" "${b[i]}"
done
}
test_zip_pairs.bats 29 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/zip-two-lists/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/zip_pairs.sh"
}
check() { # check WANT A_ITEMS B_ITEMS
local want got
# %b turns each \n in WANT into a newline. The x keeps the trailing
# newlines, which $(...) removes.
want=$(printf '%b' "$1"; printf x)
got=$(zip_pairs "$2" "$3"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "same-length" { check "1 4\n2 5\n3 6\n" "1 2 3" "4 5 6"; }
@test "tens" { check "10 30\n20 40\n" "10 20" "30 40"; }
@test "empty" { check "" "" ""; }
@test "first-empty" { check "" "" "1 2"; }
@test "second-empty" { check "" "1 2" ""; }
@test "first-shorter" { check "1 7\n" "1" "7 8"; }
@test "second-shorter" { check "1 9\n" "1 2 3" "9"; }
@test "negative" { check "-1 3\n-2 -4\n" "-1 -2" "3 -4"; }
@test "extremes" { check "-2147483648 2147483647\n2147483647 -2147483648\n" "-2147483648 2147483647" "2147483647 -2147483648"; }
@test "duplicates" { check "5 5\n5 5\n" "5 5" "5 5"; }
References
- The Python Standard Library, Built-in Functions, zip()
- MDN Web Docs, Array, Examples, Access an array item by its index
- Java SE 25 API, Class Object, equals(Object)
- .NET API reference, Enumerable.Zip method, Remarks
- The Go Programming Language Specification, Index expressions
- Rust standard library, trait Iterator, zip
- cppreference.com, Arithmetic operators (C), Overflows
- cppreference.com, std::ranges::zip_view, std::views::zip, Description
- 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.
| 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 MK0C11 Edit this page History Report an error Markdown