Programming Search⌘K

Taskintro

Loop with a step or downward

Also called count down, countdown loop, downward for loop, loop with a step, step by 2, count by n, negative step, range with step, step_by, Loops/Downward for, Loops/For with a specified step.

Count from a start to a stop by a step that can be negative, include the stop when the loop reaches it, and keep the counter from overflowing near the largest integer.

Task

Count from start to stop by step. The function count_by(start, stop, step) returns start, start + step, start + 2 * step and so on, while the value has not passed stop. The value stop is in the result when the loop reaches it. For example, count_by(10, 0, -1) is the countdown [10, 9, ..., 0], and count_by(1, 10, 3) is [1, 4, 7, 10].

start, stop and step are 32-bit signed integers, step is not 0, and the result has at most 10000 values. A positive step counts up, and a negative step counts down. The task joins two Rosetta Code tasks: a countdown from 10 to 01, and a loop whose step is greater than one2.

Solutions

Language Up Down
Python range(start, stop + 1, step) range(start, stop - 1, step)
Rust (start..=stop).step_by(k) (stop..=start).rev().step_by(k)
JavaScript, TypeScript, Java, C#, C, C++, Go i <= stop; i += step i >= stop; i += step
Bash ((i <= stop)) ((i >= stop))
  • Python. For a positive step, a range holds start + step*i while it is < stop, and for a negative step, while it is > stop3. So the solution moves the end one past stop, in the direction of the step.
  • Rust. step_by makes an iterator "starting at the same point, but stepping by the given amount at each iteration"4. Its step is a usize, so it cannot be negative. To count down, the solution reverses the range first.
  • JavaScript, TypeScript, Java, C#, C, C++ and Go. The test depends on the sign of the step: i <= stop when it counts up, i >= stop when it counts down. The counter is a 64-bit integer, so i + step cannot overflow.
  • Bash. The arithmetic for uses the same tests. Brace expansion also takes a step, {x..y..incr}, where "incr, an optional increment, is an integer"5, but it does not work with variables.

Edge cases

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

  • uneven, past-stop and down-by-three: the step does not always land on stop. The loop stops at the last value before it passes stop.
  • empty-up and empty-down: the step goes away from stop, so the result is empty. A loop with the wrong test for the direction runs forever or not at all.
  • single: start equals stop, so the result has one value, for any step.
  • negative: the values cross 0.
  • limit-up and limit-down: stop is near the largest or the smallest 32-bit integer. The next value after the last one does not fit in 32 bits. With a 32-bit counter, it wraps around, and the test i <= stop stays true.
  • big-step: the step is the largest 32-bit integer, so the second value is past stop.

Pitfalls

  • Python range stops one before stop, also when it counts down. For a negative step, "the constraints are i >= 0 and r[i] > stop"3, so range(10, 0, -1) ends at 1. A step of 0 is an error: "If step is zero, ValueError is raised"3.
print(list(range(10, 0, -1)))
print(list(range(10, -1, -1)))
try:
    range(1, 10, 0)
except ValueError as e:
    print("ValueError:", e)
Output
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
ValueError: range() arg 3 must not be zero
  • Rust 10..=0 is empty. A RangeInclusive "is empty unless start <= end"6, so it cannot count down. Reverse an upward range. step_by "will panic if the given step is 0"4.
fn main() {
    let empty: Vec<i32> = (10..=0).collect();
    let down: Vec<i32> = (1..=10).rev().step_by(3).collect();
    let up: Vec<i32> = (1..=10).step_by(3).collect();
    println!("{empty:?} {down:?} {up:?}");
}
Output
[] [10, 7, 4, 1] [1, 4, 7, 10]
  • A 32-bit counter wraps near the limit. In Java, "If an integer addition overflows, then the result is the low-order bits of the mathematical sum"7. In C#, outside a checked context, "the result is truncated by discarding any high-order bits that don't fit in the destination type"8. So a loop with int i and i <= stop near the largest int wraps to a negative number and does not end. The program below stops it after four passes:
public class Main {
  public static void main(String[] args) {
    int passes = 0;
    StringBuilder out = new StringBuilder();
    for (int i = 2147483640; i <= 2147483647; i += 5) {
      out.append(i).append(passes < 3 ? " " : "");
      if (++passes == 4) {
        break;
      }
    }
    System.out.println(out);
    StringBuilder ok = new StringBuilder();
    for (long i = 2147483640; i <= 2147483647; i += 5) {
      ok.append(i).append(" ");
    }
    System.out.println(ok.toString().strip());
  }
}
Output
2147483640 2147483645 -2147483646 -2147483641
2147483640 2147483645
  • The test must match the direction. With a negative step, i <= stop is false at once when start > stop, and true forever when start < stop. See infinite loops and off-by-one errors.

Code

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

count_by.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-with-a-step/.

def count_by(start: int, stop: int, step: int) -> list[int]:
    """Return start, start + step, ... while the value has not passed stop."""
    # range stops before its end, so move the end one past stop.
    end = stop + 1 if step > 0 else stop - 1
    out = []
    for i in range(start, end, step):
        out.append(i)
    return out
test_count_by.py 27 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-with-a-step/.

import pytest

from count_by import count_by

CASES = {
    "by-two": ((2, 8, 2), [2, 4, 6, 8]),
    "down": ((10, 0, -1), [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]),
    "uneven": ((1, 10, 3), [1, 4, 7, 10]),
    "past-stop": ((0, 9, 4), [0, 4, 8]),
    "down-by-three": ((10, 1, -3), [10, 7, 4, 1]),
    "empty-up": ((5, 1, 1), []),
    "empty-down": ((1, 5, -1), []),
    "single": ((3, 3, 7), [3]),
    "negative": ((-3, 3, 2), [-3, -1, 1, 3]),
    "limit-up": ((2147483640, 2147483647, 5), [2147483640, 2147483645]),
    "limit-down": ((-2147483640, -2147483648, -5), [-2147483640, -2147483645]),
    "big-step": ((0, 10, 2147483647), [0]),
}


@pytest.mark.parametrize("name", CASES)
def test_count_by(name):
    args, want = CASES[name]
    assert count_by(*args) == want
count_by.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

#include "count_by.hpp"

#include <vector>

std::vector<int> count_by(int start, int stop, int step) {
    std::vector<int> out;
    // A long long counter: with an int, i + step can overflow, which is undefined.
    for (long long i = start; step > 0 ? i <= stop : i >= stop; i += step) {
        out.push_back(static_cast<int>(i));
    }
    return out;
}
count_by.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

#pragma once

#include <vector>

// count_by returns start, start + step, ... while the value has not passed
// stop. step must not be 0.
std::vector<int> count_by(int start, int stop, int step);
test_count_by.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

#include "count_by.hpp"

#include <climits>
#include <iostream>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view name, int start, int stop, int step, const std::vector<int> &want) {
    if (count_by(start, stop, step) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("by-two", 2, 8, 2, {2, 4, 6, 8});
    check("down", 10, 0, -1, {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0});
    check("uneven", 1, 10, 3, {1, 4, 7, 10});
    check("past-stop", 0, 9, 4, {0, 4, 8});
    check("down-by-three", 10, 1, -3, {10, 7, 4, 1});
    check("empty-up", 5, 1, 1, {});
    check("empty-down", 1, 5, -1, {});
    check("single", 3, 3, 7, {3});
    check("negative", -3, 3, 2, {-3, -1, 1, 3});
    check("limit-up", 2147483640, INT_MAX, 5, {2147483640, 2147483645});
    check("limit-down", -2147483640, INT_MIN, -5, {-2147483640, -2147483645});
    check("big-step", 0, 10, INT_MAX, {0});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
CountBy.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

import java.util.ArrayList;
import java.util.List;

final class CountBy {
  private CountBy() {}

  /** Returns start, start + step, ... while the value has not passed stop. */
  static List<Integer> countBy(int start, int stop, int step) {
    List<Integer> out = new ArrayList<>();
    // A long counter: with an int, i + step can wrap past Integer.MAX_VALUE.
    for (long i = start; step > 0 ? i <= stop : i >= stop; i += step) {
      out.add((int) i);
    }
    return out;
  }
}
CountByTest.java 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

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 CountByTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("by-two", 2, 8, 2, List.of(2, 4, 6, 8)),
        Arguments.of("down", 10, 0, -1, List.of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)),
        Arguments.of("uneven", 1, 10, 3, List.of(1, 4, 7, 10)),
        Arguments.of("past-stop", 0, 9, 4, List.of(0, 4, 8)),
        Arguments.of("down-by-three", 10, 1, -3, List.of(10, 7, 4, 1)),
        Arguments.of("empty-up", 5, 1, 1, List.of()),
        Arguments.of("empty-down", 1, 5, -1, List.of()),
        Arguments.of("single", 3, 3, 7, List.of(3)),
        Arguments.of("negative", -3, 3, 2, List.of(-3, -1, 1, 3)),
        Arguments.of("limit-up", 2147483640, 2147483647, 5, List.of(2147483640, 2147483645)),
        Arguments.of("limit-down", -2147483640, Integer.MIN_VALUE, -5, List.of(-2147483640, -2147483645)),
        Arguments.of("big-step", 0, 10, 2147483647, List.of(0)));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void countBy(String name, int start, int stop, int step, List<Integer> want) {
    assertEquals(want, CountBy.countBy(start, stop, step), name);
  }
}
count_by.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

#include "count_by.h"

#include <stdlib.h>

int *count_by(int start, int stop, int step, size_t *count) {
    // long long values: with an int, i + step can overflow, which is undefined.
    long long span = (long long)stop - start;
    size_t n = 0;
    if ((step > 0 && span >= 0) || (step < 0 && span <= 0)) {
        n = (size_t)(span / step) + 1;
    }
    // malloc(0) may return NULL, so ask for at least one value.
    int *out = malloc((n > 0 ? n : 1) * sizeof *out);
    if (out == NULL) {
        return NULL;
    }
    size_t k = 0;
    for (long long i = start; step > 0 ? i <= stop : i >= stop; i += step) {
        out[k++] = (int)i;
    }
    *count = k;
    return out;
}
count_by.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

#ifndef COUNT_BY_H
#define COUNT_BY_H

#include <stddef.h>

// count_by returns a new array of start, start + step, ... while the value has
// not passed stop, and sets *count to the number of values. step must not be 0.
// The caller must free the array. It returns NULL when malloc fails.
int *count_by(int start, int stop, int step, size_t *count);

#endif
test_count_by.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

#include "count_by.h"

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int failures = 0;

static void check(const char *name, int start, int stop, int step, const int *want, size_t n) {
    size_t count = 0;
    int *out = count_by(start, stop, step, &count);
    if (out == NULL || count != n || (n > 0 && memcmp(out, want, n * sizeof *out) != 0)) {
        fprintf(stderr, "case %s failed\n", name);
        failures++;
    }
    free(out);
}

#define CHECK(name, start, stop, step, ...)                       \
    do {                                                          \
        const int w[] = {__VA_ARGS__};                            \
        check(name, start, stop, step, w, sizeof w / sizeof w[0]); \
    } while (0)

int main(void) {
    CHECK("by-two", 2, 8, 2, 2, 4, 6, 8);
    CHECK("down", 10, 0, -1, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
    CHECK("uneven", 1, 10, 3, 1, 4, 7, 10);
    CHECK("past-stop", 0, 9, 4, 0, 4, 8);
    CHECK("down-by-three", 10, 1, -3, 10, 7, 4, 1);
    check("empty-up", 5, 1, 1, NULL, 0);
    check("empty-down", 1, 5, -1, NULL, 0);
    CHECK("single", 3, 3, 7, 3);
    CHECK("negative", -3, 3, 2, -3, -1, 1, 3);
    CHECK("limit-up", 2147483640, INT_MAX, 5, 2147483640, 2147483645);
    CHECK("limit-down", -2147483640, INT_MIN, -5, -2147483640, -2147483645);
    CHECK("big-step", 0, 10, INT_MAX, 0);
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
CountBy.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

public static class CountBy
{
    // Returns start, start + step, ... while the value has not passed stop.
    public static List<int> Of(int start, int stop, int step)
    {
        var result = new List<int>();
        // A long counter: with an int, i + step can wrap past int.MaxValue.
        for (long i = start; step > 0 ? i <= stop : i >= stop; i += step)
        {
            result.Add((int)i);
        }
        return result;
    }
}
CountByTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

using Xunit;

public sealed class CountByTests
{
    public static TheoryData<string, int, int, int, int[]> Cases => new()
    {
        { "by-two", 2, 8, 2, new int[] { 2, 4, 6, 8 } },
        { "down", 10, 0, -1, new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 } },
        { "uneven", 1, 10, 3, new int[] { 1, 4, 7, 10 } },
        { "past-stop", 0, 9, 4, new int[] { 0, 4, 8 } },
        { "down-by-three", 10, 1, -3, new int[] { 10, 7, 4, 1 } },
        { "empty-up", 5, 1, 1, new int[0] },
        { "empty-down", 1, 5, -1, new int[0] },
        { "single", 3, 3, 7, new int[] { 3 } },
        { "negative", -3, 3, 2, new int[] { -3, -1, 1, 3 } },
        { "limit-up", 2147483640, 2147483647, 5, new int[] { 2147483640, 2147483645 } },
        { "limit-down", -2147483640, int.MinValue, -5, new int[] { -2147483640, -2147483645 } },
        { "big-step", 0, 10, 2147483647, new int[] { 0 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int start, int stop, int step, int[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, CountBy.Of(start, stop, step));
    }
}
count_by.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

/**
 * Returns start, start + step, ... while the value has not passed stop.
 * @param {number} start
 * @param {number} stop
 * @param {number} step a number that is not 0
 * @returns {number[]}
 */
export function countBy(start, stop, step) {
  const out = [];
  // The test depends on the direction of the step.
  for (let i = start; step > 0 ? i <= stop : i >= stop; i += step) {
    out.push(i);
  }
  return out;
}
count_by.test.js 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

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

import { countBy } from "./count_by.js";

const cases = [
  ["by-two", 2, 8, 2, [2, 4, 6, 8]],
  ["down", 10, 0, -1, [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]],
  ["uneven", 1, 10, 3, [1, 4, 7, 10]],
  ["past-stop", 0, 9, 4, [0, 4, 8]],
  ["down-by-three", 10, 1, -3, [10, 7, 4, 1]],
  ["empty-up", 5, 1, 1, []],
  ["empty-down", 1, 5, -1, []],
  ["single", 3, 3, 7, [3]],
  ["negative", -3, 3, 2, [-3, -1, 1, 3]],
  ["limit-up", 2147483640, 2147483647, 5, [2147483640, 2147483645]],
  ["limit-down", -2147483640, -2147483648, -5, [-2147483640, -2147483645]],
  ["big-step", 0, 10, 2147483647, [0]],
];

for (const [name, start, stop, step, want] of cases) {
  test(name, () => {
    assert.deepEqual(countBy(start, stop, step), want);
  });
}
count_by.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

export function countBy(start: number, stop: number, step: number): number[] {
  const out: number[] = [];
  // The test depends on the direction of the step.
  for (let i = start; step > 0 ? i <= stop : i >= stop; i += step) {
    out.push(i);
  }
  return out;
}
count_by.test.ts 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

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

import { countBy } from "./count_by.ts";

const cases: [string, number, number, number, number[]][] = [
  ["by-two", 2, 8, 2, [2, 4, 6, 8]],
  ["down", 10, 0, -1, [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]],
  ["uneven", 1, 10, 3, [1, 4, 7, 10]],
  ["past-stop", 0, 9, 4, [0, 4, 8]],
  ["down-by-three", 10, 1, -3, [10, 7, 4, 1]],
  ["empty-up", 5, 1, 1, []],
  ["empty-down", 1, 5, -1, []],
  ["single", 3, 3, 7, [3]],
  ["negative", -3, 3, 2, [-3, -1, 1, 3]],
  ["limit-up", 2147483640, 2147483647, 5, [2147483640, 2147483645]],
  ["limit-down", -2147483640, -2147483648, -5, [-2147483640, -2147483645]],
  ["big-step", 0, 10, 2147483647, [0]],
];

for (const [name, start, stop, step, want] of cases) {
  test(name, () => {
    assert.deepEqual(countBy(start, stop, step), want);
  });
}
count_by.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

// Package countby counts from a start to a stop by a step.
package countby

// CountBy returns start, start+step, ... while the value has not passed stop.
// step must not be 0.
func CountBy(start, stop, step int32) []int32 {
	out := []int32{}
	// An int64 counter: with an int32, i+step can wrap past the largest int32.
	for i := int64(start); step > 0 && i <= int64(stop) || step < 0 && i >= int64(stop); i += int64(step) {
		out = append(out, int32(i))
	}
	return out
}
count_by_test.go 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

package countby

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

var cases = []struct {
	name              string
	start, stop, step int32
	want              []int32
}{
	{"by-two", 2, 8, 2, []int32{2, 4, 6, 8}},
	{"down", 10, 0, -1, []int32{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}},
	{"uneven", 1, 10, 3, []int32{1, 4, 7, 10}},
	{"past-stop", 0, 9, 4, []int32{0, 4, 8}},
	{"down-by-three", 10, 1, -3, []int32{10, 7, 4, 1}},
	{"empty-up", 5, 1, 1, []int32{}},
	{"empty-down", 1, 5, -1, []int32{}},
	{"single", 3, 3, 7, []int32{3}},
	{"negative", -3, 3, 2, []int32{-3, -1, 1, 3}},
	{"limit-up", 2147483640, math.MaxInt32, 5, []int32{2147483640, 2147483645}},
	{"limit-down", -2147483640, math.MinInt32, -5, []int32{-2147483640, -2147483645}},
	{"big-step", 0, 10, math.MaxInt32, []int32{0}},
}

func TestCountBy(t *testing.T) {
	for _, c := range cases {
		if got := CountBy(c.start, c.stop, c.step); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}
count_by.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

/// Returns start, start + step, ... while the value has not passed stop.
/// step must not be 0.
pub fn count_by(start: i32, stop: i32, step: i32) -> Vec<i32> {
    let mut out = Vec::new();
    // step_by takes a usize, so the sign of the step picks the direction.
    let k = step.unsigned_abs() as usize;
    if step > 0 {
        for i in (start..=stop).step_by(k) {
            out.push(i);
        }
    } else {
        // start..=stop is empty when start > stop, so reverse stop..=start.
        for i in (stop..=start).rev().step_by(k) {
            out.push(i);
        }
    }
    out
}
tests/count_by_test.rs 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-a-step/.

use algo_loop_with_a_step::count_by;

#[test]
fn cases() {
    let cases: &[(&str, i32, i32, i32, &[i32])] = &[
        ("by-two", 2, 8, 2, &[2, 4, 6, 8]),
        ("down", 10, 0, -1, &[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]),
        ("uneven", 1, 10, 3, &[1, 4, 7, 10]),
        ("past-stop", 0, 9, 4, &[0, 4, 8]),
        ("down-by-three", 10, 1, -3, &[10, 7, 4, 1]),
        ("empty-up", 5, 1, 1, &[]),
        ("empty-down", 1, 5, -1, &[]),
        ("single", 3, 3, 7, &[3]),
        ("negative", -3, 3, 2, &[-3, -1, 1, 3]),
        ("limit-up", 2147483640, i32::MAX, 5, &[2147483640, 2147483645]),
        ("limit-down", -2147483640, i32::MIN, -5, &[-2147483640, -2147483645]),
        ("big-step", 0, 10, i32::MAX, &[0]),
    ];
    for &(name, start, stop, step, want) in cases {
        assert_eq!(count_by(start, stop, step), want, "{name}");
    }
}
count_by.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-with-a-step/.

# count_by START STOP STEP
# Prints START, START + STEP, ... while the value has not passed STOP, one on
# each line. STEP must not be 0.
count_by() {
  local i
  # The test depends on the direction of the step. {$1..$2..$3} would not
  # work, because brace expansion runs before the variables expand.
  for ((i = $1; $3 > 0 ? i <= $2 : i >= $2; i += $3)); do
    printf '%s\n' "$i"
  done
}
test_count_by.bats 32 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-with-a-step/.

bats_require_minimum_version 1.5.0

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

check() { # check START STOP STEP -- WANT...
  local start=$1 stop=$2 step=$3
  shift 4
  local got want
  # The x keeps the trailing newlines, which $(...) removes.
  got=$(count_by "$start" "$stop" "$step"; 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 "by-two" { check 2 8 2 -- 2 4 6 8; }
@test "down" { check 10 0 -1 -- 10 9 8 7 6 5 4 3 2 1 0; }
@test "uneven" { check 1 10 3 -- 1 4 7 10; }
@test "past-stop" { check 0 9 4 -- 0 4 8; }
@test "down-by-three" { check 10 1 -3 -- 10 7 4 1; }
@test "empty-up" { check 5 1 1 --; }
@test "empty-down" { check 1 5 -1 --; }
@test "single" { check 3 3 7 -- 3; }
@test "negative" { check -3 3 2 -- -3 -1 1 3; }
@test "limit-up" { check 2147483640 2147483647 5 -- 2147483640 2147483645; }
@test "limit-down" { check -2147483640 -2147483648 -5 -- -2147483640 -2147483645; }
@test "big-step" { check 0 10 2147483647 -- 0; }

References

  1. Loops/Downward for, Rosetta Code (the RosettaCodeData mirror), Task
  2. Loops/For with a specified step, Rosetta Code (the RosettaCodeData mirror), Task
  3. Built-in Types, The Python Standard Library, Ranges
  4. Iterator in std::iter, The Rust Standard Library, step_by
  5. Bash Reference Manual, 3.5.1 Brace Expansion
  6. RangeInclusive in std::ops, The Rust Standard Library, Description
  7. The Java Language Specification, Java SE 25 Edition, Chapter 15, 15.18.2 Additive Operators (+ and -) for Numeric Types
  8. Arithmetic operators, C# language reference, Integer arithmetic overflow

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