Programming Search⌘K

Taskcore

Build a string efficiently

Also called string builder, StringBuilder, strings.Builder, append to a string in a loop, string concatenation in a loop, accumulate a string.

Build a long string from many pieces in a loop with a builder, a buffer that grows, or a list and one join, and not with a + that copies the whole result on each step.

Task

Build a long string from many small pieces. The function number_line(n) returns the numbers 1 to n with a comma between each two, so number_line(5) is "1,2,3,4,5" and number_line(0) is the empty string. The code makes the pieces one at a time in a loop.

A loop of s = s + piece on an immutable string copies the whole result on each step. For n pieces, the copies add up to O(n²) characters. A builder keeps one buffer with free space at the end, so an append copies only the new piece, and the buffer grows by a factor when it is full. Then the cost of all the appends is O(n). A list of pieces and one join at the end has the same cost.

Solutions

Language Tool
Python a list and str.join, or io.StringIO
JavaScript, TypeScript an array and join
Java StringBuilder
C# StringBuilder
Go strings.Builder
Rust String with push, push_str and write!
C a buffer that keeps its length and grows with realloc
C++ std::string with +=
Bash an array and "${parts[*]}"
  • Python. "Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length"1. The documentation says that "you can build a list and use str.join() at the end"1, and the code does that. io.StringIO is "A text stream using an in-memory text buffer"2, and it is the other choice.
  • JavaScript and TypeScript. join "returns a new string that is the concatenation of all elements in this array, separated by commas or a specified separator string"3. The code pushes each number to an array and joins once.
  • Java. "Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger"4. append(int) writes the digits, and toString makes the result.
  • C#. "The String object is immutable"5, and the .NET documentation says that "using the StringBuilder class can boost performance when concatenating many strings together in a loop"5. The code appends each number with ToString(CultureInfo.InvariantCulture), so the culture cannot change the digits.
  • Go. "A Builder is used to efficiently build a string using Builder.Write methods. It minimizes memory copying. The zero value is ready to use"6. The code calls WriteByte for the comma and WriteString for the digits.
  • Rust. A String is a builder. String::with_capacity "creates an empty String, but one with an initial buffer that can hold at least capacity bytes"7. The code uses write! from std::fmt::Write, which formats the number into the buffer and makes no temporary String.
  • C. C has no builder. strcat finds the end of the destination on each call, because "The character src[0] replaces the null terminator at the end of dest"8, so a loop of strcat calls reads the result again on each step. The code keeps the length and the capacity in a struct, writes at the end with memcpy, and doubles the capacity with realloc when the buffer is full9. The caller frees the result.
  • C++. std::string grows like a builder. The complexity of push_back is "Amortized constant"10, and reserve can make the buffer large enough before the loop11. The code appends with += and std::to_string.
  • Bash. "If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS variable"12. The function collects the numbers in an array, sets a local IFS to a comma and prints "${parts[*]}".

Edge cases

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

  • zero: the loop does not run, and the result is the empty string. A join of an empty list gives the empty string in every language.
  • one: one number and no comma. Code that writes a comma after each number and does not remove the last one fails here.
  • nine, ten, hundred and hundred-and-one: the numbers get one more digit at 10 and at 100, so the result grows faster after each of these points.
  • thousand and large: number_line(1000) has 3892 characters. Each test file also checks number_line(100000), which has 588894 characters, by its length and its two ends. A solution that copies the whole result on each step copies about 29 thousand million characters for it and fails the time limit.

Pitfalls

  • Python join takes only strings. It raises TypeError for an int, so convert each item first. io.StringIO collects the pieces, and getvalue returns "a str containing the entire contents of the buffer"2:
import io

nums = [1, 2, 3]
try:
    print(",".join(nums))
except TypeError as e:
    print("TypeError:", e)
print(",".join(map(str, nums)))

buf = io.StringIO()
for n in nums:
    buf.write(f"{n};")
print(buf.getvalue())
Output
TypeError: sequence item 0: expected str instance, int found
1,2,3
1;2;3;
  • JavaScript join changes some items. "If an element is undefined or null, it is converted to an empty string"3, and an array item is converted with its own join, so it brings its own commas:
console.log([1, null, 3, undefined].join());
console.log([1, [2, 3], 4].join(";"));
console.log(["a"].join("-"));
console.log([].join("-") === "");
Output
1,,3,
1;2,3;4
a
true
  • Java char values are numbers. 'a' + 'b' is an addition of two char values, so append gets the int 195. new StringBuilder('x') calls the constructor that takes an int, and it "Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument"4, so the builder is empty and its capacity is 120, the code of x:
public class Main {
  public static void main(String[] args) {
    StringBuilder a = new StringBuilder();
    a.append('a' + 'b');
    a.append(',').append("" + 'a' + 'b');
    System.out.println(a);

    StringBuilder b = new StringBuilder('x');
    System.out.println("[" + b + "] capacity " + b.capacity());

    StringBuilder c = new StringBuilder(1000);
    System.out.println("capacity " + c.capacity() + ", length " + c.length());
  }
}
Output
195,ab
[] capacity 120
capacity 1000, length 0
  • C# += in a loop. "Each + or += operation creates a new string, because strings are immutable"13. Use one StringBuilder for the whole loop, and call ToString once at the end.
  • Go strings.Builder must not be copied. The documentation says "Do not copy a non-zero Builder"6. A write to a copy panics:
package main

import (
	"fmt"
	"strings"
)

func main() {
	var a strings.Builder
	a.WriteString("abc")
	b := a // a copy of a Builder that is not empty
	defer func() {
		fmt.Println("panic:", recover())
	}()
	fmt.Println(b.String())
	b.WriteString("def")
}
Output
abc
panic: strings: illegal use of non-zero Builder copied by value
  • C strcat in a loop reads the result again on each step. For the 1000 numbers, the loop of strcat calls reads 1893996 bytes to find the end of a result of 3892 bytes. A pointer to the end reads none:
#include <stdio.h>
#include <string.h>

static char buf[4096];

int main(void) {
    // strcat finds the end of buf on each call, so it reads all the bytes
    // that are already there. A pointer to the end does not.
    size_t scanned = 0;
    buf[0] = '\0';
    for (int i = 1; i <= 1000; i++) {
        char d[16];
        snprintf(d, sizeof d, i > 1 ? ",%d" : "%d", i);
        scanned += strlen(buf);
        strcat(buf, d);
    }
    printf("strcat: %zu bytes, %zu bytes read to find the end\n", strlen(buf), scanned);

    char *end = buf;
    for (int i = 1; i <= 1000; i++) {
        end += snprintf(end, sizeof buf - (size_t)(end - buf), i > 1 ? ",%d" : "%d", i);
    }
    printf("end pointer: %zu bytes, 0 bytes read to find the end\n", (size_t)(end - buf));
}
Output
strcat: 3892 bytes, 1893996 bytes read to find the end
end pointer: 3892 bytes, 0 bytes read to find the end
  • Rust: reserve when you know the size. With a capacity that is large enough, the appends are "all done without reallocating"7. Without it, a push "may make the string reallocate"7 when the buffer is full:
use std::fmt::Write;

fn main() {
    let n = 1000;
    let mut s = String::with_capacity(3892);
    let cap = s.capacity();
    for i in 1..=n {
        if i > 1 {
            s.push(',');
        }
        write!(s, "{i}").unwrap();
    }
    println!("length {}, enough capacity at the start: {}", s.len(), cap >= 3892);
    println!("reallocated: {}", s.capacity() != cap);
}
Output
length 3892, enough capacity at the start: true
reallocated: false
  • Bash "${parts[*]}" uses only the first character of IFS. With IFS=', ', the separator is a comma with no space. When IFS is not set, the separator is a space. Set IFS in a function with local, or in a subshell, so the change does not affect the rest of the script:
parts=(1 2 3)
IFS=', '
echo "${parts[*]}"
echo "${parts[@]}"
unset IFS
echo "${parts[*]}"
(IFS=-; echo "${parts[*]}")
echo "${parts[*]}"
Output
1,2,3
1 2 3
1 2 3
1-2-3
1 2 3

Code

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

number_line.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/build-a-string-efficiently/.


def number_line(n: int) -> str:
    """Return the numbers 1 to n, separated by commas."""
    # A str is immutable, so the code collects the parts in a list and
    # joins them once at the end.
    parts = []
    for i in range(1, n + 1):
        parts.append(str(i))
    return ",".join(parts)
test_number_line.py 39 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/build-a-string-efficiently/.

import pytest

from number_line import number_line

CASES = {
    "zero": (0, ""),
    "one": (1, "1"),
    "three": (3, "1,2,3"),
    "five": (5, "1,2,3,4,5"),
    "seven": (7, "1,2,3,4,5,6,7"),
    "nine": (9, "1,2,3,4,5,6,7,8,9"),
    "ten": (10, "1,2,3,4,5,6,7,8,9,10"),
}

# Long results: the length, the start and the end.
LONG = {
    "hundred": (100, 291, ",99,100"),
    "hundred-and-one": (101, 295, ",100,101"),
    "thousand": (1000, 3892, ",999,1000"),
    "large": (100000, 588894, ",99999,100000"),
}


@pytest.mark.parametrize("name", CASES)
def test_exact(name):
    n, want = CASES[name]
    assert number_line(n) == want


@pytest.mark.parametrize("name", LONG)
def test_long(name):
    n, size, end = LONG[name]
    got = number_line(n)
    assert len(got) == size
    assert got.startswith("1,2,3,")
    assert got.endswith(end)
number_line.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

#include "number_line.hpp"

std::string number_line(int n) {
    // std::string grows its buffer when it is full, so each += is amortized
    // O(1), and std::to_string makes the digits of each number.
    std::string r;
    for (int i = 1; i <= n; i++) {
        if (i > 1) {
            r += ',';
        }
        r += std::to_string(i);
    }
    return r;
}
number_line.hpp 9 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

#pragma once

#include <string>

// number_line returns the numbers 1 to n, separated by commas.
std::string number_line(int n);
test_number_line.cpp 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

#include "number_line.hpp"

#include <cstddef>
#include <iostream>
#include <string>
#include <string_view>

static int failures = 0;

static void check(std::string_view name, int n, std::string_view want) {
    std::string got = number_line(n);
    if (got != want) {
        std::cerr << "case " << name << ": got [" << got << "], want [" << want << "]\n";
        failures++;
    }
}

// check_long checks the length, the start and the end of a long result.
static void check_long(std::string_view name, int n, std::size_t size, std::string_view end) {
    std::string got = number_line(n);
    if (got.size() != size || !got.starts_with("1,2,3,") || !got.ends_with(end)) {
        std::cerr << "case " << name << ": got a length of " << got.size() << "\n";
        failures++;
    }
}

int main() {
    check("zero", 0, "");
    check("one", 1, "1");
    check("three", 3, "1,2,3");
    check("five", 5, "1,2,3,4,5");
    check("seven", 7, "1,2,3,4,5,6,7");
    check("nine", 9, "1,2,3,4,5,6,7,8,9");
    check("ten", 10, "1,2,3,4,5,6,7,8,9,10");
    check_long("hundred", 100, 291, ",99,100");
    check_long("hundred-and-one", 101, 295, ",100,101");
    check_long("thousand", 1000, 3892, ",999,1000");
    check_long("large", 100000, 588894, ",99999,100000");
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
NumberLine.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

/** Builds the line of numbers 1 to n. */
public final class NumberLine {
  private NumberLine() {}

  /** Returns the numbers 1 to n, separated by commas. */
  public static String numberLine(int n) {
    // A StringBuilder appends to one buffer, so the loop does not copy the
    // whole result on each step.
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i <= n; i++) {
      if (i > 1) {
        sb.append(',');
      }
      sb.append(i);
    }
    return sb.toString();
  }
}
NumberLineTest.java 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

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

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 NumberLineTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("zero", 0, ""),
        Arguments.of("one", 1, "1"),
        Arguments.of("three", 3, "1,2,3"),
        Arguments.of("five", 5, "1,2,3,4,5"),
        Arguments.of("seven", 7, "1,2,3,4,5,6,7"),
        Arguments.of("nine", 9, "1,2,3,4,5,6,7,8,9"),
        Arguments.of("ten", 10, "1,2,3,4,5,6,7,8,9,10"));
  }

  // Long results: the length, the start and the end.
  static Stream<Arguments> longCases() {
    return Stream.of(
        Arguments.of("hundred", 100, 291, ",99,100"),
        Arguments.of("hundred-and-one", 101, 295, ",100,101"),
        Arguments.of("thousand", 1000, 3892, ",999,1000"),
        Arguments.of("large", 100000, 588894, ",99999,100000"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void exact(String name, int n, String want) {
    assertEquals(want, NumberLine.numberLine(n));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("longCases")
  void longResult(String name, int n, int size, String end) {
    String got = NumberLine.numberLine(n);
    assertEquals(size, got.length());
    assertTrue(got.startsWith("1,2,3,"));
    assertTrue(got.endsWith(end));
  }
}
number_line.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

#include "number_line.h"

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

// A buffer that keeps its length, so an append does not scan for the end,
// and that doubles its capacity when it is full.
struct buf {
    char *data;
    size_t len;
    size_t cap;
};

static int append(struct buf *b, const char *s, size_t n) {
    if (b->len + n + 1 > b->cap) {
        size_t cap = b->cap ? b->cap : 16;
        while (b->len + n + 1 > cap) {
            cap *= 2;
        }
        char *p = realloc(b->data, cap);
        if (p == NULL) {
            return -1;
        }
        b->data = p;
        b->cap = cap;
    }
    memcpy(b->data + b->len, s, n);
    b->len += n;
    b->data[b->len] = '\0';
    return 0;
}

char *number_line(int n) {
    struct buf b = {NULL, 0, 0};
    if (append(&b, "", 0) != 0) {
        return NULL;
    }
    char digits[16];
    for (int i = 1; i <= n; i++) {
        int k = snprintf(digits, sizeof digits, i > 1 ? ",%d" : "%d", i);
        if (append(&b, digits, (size_t)k) != 0) {
            free(b.data);
            return NULL;
        }
    }
    return b.data;
}
number_line.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

#ifndef NUMBER_LINE_H
#define NUMBER_LINE_H

// number_line returns the numbers 1 to n, separated by commas, in a new
// string that the caller frees. It returns NULL if an allocation fails.
char *number_line(int n);

#endif
test_number_line.c 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

#include "number_line.h"

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

static int failures = 0;

static void check(const char *name, int n, const char *want) {
    char *got = number_line(n);
    if (got == NULL || strcmp(got, want) != 0) {
        fprintf(stderr, "case %s: got [%s], want [%s]\n", name, got ? got : "NULL", want);
        failures++;
    }
    free(got);
}

// check_long checks the length, the start and the end of a long result.
static void check_long(const char *name, int n, size_t size, const char *end) {
    char *got = number_line(n);
    size_t len = got ? strlen(got) : 0;
    size_t e = strlen(end);
    if (got == NULL || len != size || strncmp(got, "1,2,3,", 6) != 0 || strcmp(got + len - e, end) != 0) {
        fprintf(stderr, "case %s: got a length of %zu, want %zu\n", name, len, size);
        failures++;
    }
    free(got);
}

int main(void) {
    check("zero", 0, "");
    check("one", 1, "1");
    check("three", 3, "1,2,3");
    check("five", 5, "1,2,3,4,5");
    check("seven", 7, "1,2,3,4,5,6,7");
    check("nine", 9, "1,2,3,4,5,6,7,8,9");
    check("ten", 10, "1,2,3,4,5,6,7,8,9,10");
    check_long("hundred", 100, 291, ",99,100");
    check_long("hundred-and-one", 101, 295, ",100,101");
    check_long("thousand", 1000, 3892, ",999,1000");
    check_long("large", 100000, 588894, ",99999,100000");
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
NumberLine.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

using System.Globalization;
using System.Text;

public static class NumberLine
{
    /// <summary>Returns the numbers 1 to n, separated by commas.</summary>
    public static string Build(int n)
    {
        // A StringBuilder appends to its buffer, so the loop does not copy
        // the whole result on each step.
        var sb = new StringBuilder();
        for (int i = 1; i <= n; i++)
        {
            if (i > 1)
            {
                sb.Append(',');
            }
            sb.Append(i.ToString(CultureInfo.InvariantCulture));
        }
        return sb.ToString();
    }
}
NumberLineTests.cs 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

using Xunit;

public sealed class NumberLineTests
{
    public static TheoryData<string, int, string> Cases => new()
    {
        { "zero", 0, "" },
        { "one", 1, "1" },
        { "three", 3, "1,2,3" },
        { "five", 5, "1,2,3,4,5" },
        { "seven", 7, "1,2,3,4,5,6,7" },
        { "nine", 9, "1,2,3,4,5,6,7,8,9" },
        { "ten", 10, "1,2,3,4,5,6,7,8,9,10" },
    };

    // Long results: the length, the start and the end.
    public static TheoryData<string, int, int, string> LongCases => new()
    {
        { "hundred", 100, 291, ",99,100" },
        { "hundred-and-one", 101, 295, ",100,101" },
        { "thousand", 1000, 3892, ",999,1000" },
        { "large", 100000, 588894, ",99999,100000" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Exact(string name, int n, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, NumberLine.Build(n));
    }

    [Theory]
    [MemberData(nameof(LongCases))]
    public void LongResult(string name, int n, int size, string end)
    {
        Assert.NotNull(name);
        string got = NumberLine.Build(n);
        Assert.Equal(size, got.Length);
        Assert.StartsWith("1,2,3,", got);
        Assert.EndsWith(end, got);
    }
}
numberLine.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

/**
 * Returns the numbers 1 to n, separated by commas.
 * @param {number} n
 * @returns {string}
 */
export function numberLine(n) {
  // Collect the parts in an array and join them once at the end.
  const parts = [];
  for (let i = 1; i <= n; i++) {
    parts.push(String(i));
  }
  return parts.join(",");
}
numberLine.test.js 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

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

const cases = [
  ["zero", 0, ""],
  ["one", 1, "1"],
  ["three", 3, "1,2,3"],
  ["five", 5, "1,2,3,4,5"],
  ["seven", 7, "1,2,3,4,5,6,7"],
  ["nine", 9, "1,2,3,4,5,6,7,8,9"],
  ["ten", 10, "1,2,3,4,5,6,7,8,9,10"],
];

// Long results: the length, the start and the end.
const long = [
  ["hundred", 100, 291, ",99,100"],
  ["hundred-and-one", 101, 295, ",100,101"],
  ["thousand", 1000, 3892, ",999,1000"],
  ["large", 100000, 588894, ",99999,100000"],
];

for (const [name, n, want] of cases) {
  test(name, () => {
    assert.equal(numberLine(n), want);
  });
}

for (const [name, n, size, end] of long) {
  test(name, () => {
    const got = numberLine(n);
    assert.equal(got.length, size);
    assert.ok(got.startsWith("1,2,3,"));
    assert.ok(got.endsWith(end));
  });
}
numberLine.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

/** Returns the numbers 1 to n, separated by commas. */
export function numberLine(n: number): string {
  // Collect the parts in an array and join them once at the end.
  const parts: string[] = [];
  for (let i = 1; i <= n; i++) {
    parts.push(String(i));
  }
  return parts.join(",");
}
numberLine.test.ts 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

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

const cases: [string, number, string][] = [
  ["zero", 0, ""],
  ["one", 1, "1"],
  ["three", 3, "1,2,3"],
  ["five", 5, "1,2,3,4,5"],
  ["seven", 7, "1,2,3,4,5,6,7"],
  ["nine", 9, "1,2,3,4,5,6,7,8,9"],
  ["ten", 10, "1,2,3,4,5,6,7,8,9,10"],
];

// Long results: the length, the start and the end.
const long: [string, number, number, string][] = [
  ["hundred", 100, 291, ",99,100"],
  ["hundred-and-one", 101, 295, ",100,101"],
  ["thousand", 1000, 3892, ",999,1000"],
  ["large", 100000, 588894, ",99999,100000"],
];

for (const [name, n, want] of cases) {
  test(name, () => {
    assert.equal(numberLine(n), want);
  });
}

for (const [name, n, size, end] of long) {
  test(name, () => {
    const got = numberLine(n);
    assert.equal(got.length, size);
    assert.ok(got.startsWith("1,2,3,"));
    assert.ok(got.endsWith(end));
  });
}
number_line.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

// Package numberline builds the line of numbers 1 to n.
package numberline

import (
	"strconv"
	"strings"
)

// NumberLine returns the numbers 1 to n, separated by commas.
func NumberLine(n int) string {
	// A strings.Builder appends to one byte slice, and String returns it
	// with no copy.
	var b strings.Builder
	for i := 1; i <= n; i++ {
		if i > 1 {
			b.WriteByte(',')
		}
		b.WriteString(strconv.Itoa(i))
	}
	return b.String()
}
number_line_test.go 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

package numberline

import (
	"strings"
	"testing"
)

func TestExact(t *testing.T) {
	cases := []struct {
		name string
		n    int
		want string
	}{
		{"zero", 0, ""},
		{"one", 1, "1"},
		{"three", 3, "1,2,3"},
		{"five", 5, "1,2,3,4,5"},
		{"seven", 7, "1,2,3,4,5,6,7"},
		{"nine", 9, "1,2,3,4,5,6,7,8,9"},
		{"ten", 10, "1,2,3,4,5,6,7,8,9,10"},
	}
	for _, c := range cases {
		if got := NumberLine(c.n); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}

// Long results: the length, the start and the end.
func TestLong(t *testing.T) {
	cases := []struct {
		name    string
		n, size int
		end     string
	}{
		{"hundred", 100, 291, ",99,100"},
		{"hundred-and-one", 101, 295, ",100,101"},
		{"thousand", 1000, 3892, ",999,1000"},
		{"large", 100000, 588894, ",99999,100000"},
	}
	for _, c := range cases {
		got := NumberLine(c.n)
		if len(got) != c.size || !strings.HasPrefix(got, "1,2,3,") || !strings.HasSuffix(got, c.end) {
			t.Errorf("%s: got a length of %d", c.name, len(got))
		}
	}
}
number_line.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

use std::fmt::Write;

/// Returns the numbers 1 to n, separated by commas.
pub fn number_line(n: u32) -> String {
    // A String grows its buffer when it is full, so each push is amortized
    // O(1). write! formats the number into the buffer with no temporary String.
    let mut s = String::new();
    for i in 1..=n {
        if i > 1 {
            s.push(',');
        }
        write!(s, "{i}").expect("a write to a String does not fail");
    }
    s
}
tests/number_line_test.rs 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/build-a-string-efficiently/.

use algo_build_a_string_efficiently::number_line;

#[test]
fn exact_cases() {
    let cases = [
        ("zero", 0, ""),
        ("one", 1, "1"),
        ("three", 3, "1,2,3"),
        ("five", 5, "1,2,3,4,5"),
        ("seven", 7, "1,2,3,4,5,6,7"),
        ("nine", 9, "1,2,3,4,5,6,7,8,9"),
        ("ten", 10, "1,2,3,4,5,6,7,8,9,10"),
    ];
    for (name, n, want) in cases {
        assert_eq!(number_line(n), want, "{name}");
    }
}

// Long results: the length, the start and the end.
#[test]
fn long_cases() {
    let cases = [
        ("hundred", 100, 291, ",99,100"),
        ("hundred-and-one", 101, 295, ",100,101"),
        ("thousand", 1000, 3892, ",999,1000"),
        ("large", 100000, 588894, ",99999,100000"),
    ];
    for (name, n, size, end) in cases {
        let got = number_line(n);
        assert_eq!(got.len(), size, "{name}");
        assert!(got.starts_with("1,2,3,"), "{name}");
        assert!(got.ends_with(end), "{name}");
    }
}
number_line.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/build-a-string-efficiently/.

# number_line N: prints the numbers 1 to N, separated by commas. The loop
# collects the numbers in an array, and "${parts[*]}" joins them with the
# first character of IFS. The IFS change is local to the function.
number_line() {
  local -a parts=()
  local i
  for ((i = 1; i <= $1; i++)); do
    parts+=("$i")
  done
  local IFS=,
  printf '%s' "${parts[*]}"
}
test_number_line.bats 35 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/build-a-string-efficiently/.

bats_require_minimum_version 1.5.0

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

check() { # check WANT N
  run number_line "$2"
  [ "$status" -eq 0 ]
  [ "$output" = "$1" ]
}

check_long() { # check_long N SIZE END: the length, the start and the end
  run number_line "$1"
  [ "$status" -eq 0 ]
  [ "${#output}" -eq "$2" ]
  [ "${output:0:6}" = "1,2,3," ]
  [ "${output: -${#3}}" = "$3" ]
}

@test "zero" { check '' 0; }
@test "one" { check '1' 1; }
@test "three" { check '1,2,3' 3; }
@test "five" { check '1,2,3,4,5' 5; }
@test "seven" { check '1,2,3,4,5,6,7' 7; }
@test "nine" { check '1,2,3,4,5,6,7,8,9' 9; }
@test "ten" { check '1,2,3,4,5,6,7,8,9,10' 10; }
@test "hundred" { check_long 100 291 ',99,100'; }
@test "hundred-and-one" { check_long 101 295 ',100,101'; }
@test "thousand" { check_long 1000 3892 ',999,1000'; }
@test "large" { check_long 100000 588894 ',99999,100000'; }

References

  1. The Python Standard Library, Built-in Types, Common Sequence Operations, note 6
  2. The Python Standard Library, io, class io.StringIO
  3. MDN Web Docs, Array.prototype.join(), Description
  4. Java SE 25 API, java.lang.StringBuilder, Class description; Constructors
  5. .NET fundamentals, Use the StringBuilder class in .NET
  6. Go standard library, package strings, type Builder
  7. The Rust Standard Library, struct String, with_capacity; impl Add<&str> for String
  8. cppreference.com, strcat, strcat_s
  9. cppreference.com, realloc
  10. cppreference.com, std::basic_string push_back, Complexity
  11. cppreference.com, std::basic_string reserve
  12. Bash Reference Manual, on the site of the Bash maintainer Chet Ramey, Arrays
  13. C# fundamentals, How to concatenate multiple strings

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