Taskintro
Create a two-dimensional array
Also called 2d array, two-dimensional list, matrix of zeros, grid of values, list of lists, nested array, jagged array, array of arrays.
Make a grid of rows and columns filled with one value, with a separate list for each row, and avoid the rows that share one list.
- Evidence
- Code in 10 languages
Task
Make a grid with rows rows and cols columns, with value in each cell. The function grid(rows, cols, value) returns a list of rows, and each row is a list of cols items. For example, grid(2, 3, 0) is [[0, 0, 0], [0, 0, 0]].
Each row must be a separate list. After g[0][0] = 1, the cell g[1][0] must keep its value. Each value is a 32-bit signed integer, and rows and cols are from 0 to 100.
Solutions
| Language | A grid with a separate list for each row |
|---|---|
| Python | [[value] * cols for _ in range(rows)] |
| JavaScript, TypeScript | Array.from({ length: rows }, () => new Array(cols).fill(value)) |
| Java | new int[rows][cols], then Arrays.fill(row, value) for each row |
| C# | new int[rows][] and a loop that makes each row, or new int[rows, cols] |
| Go | make([][]int, rows) and a loop that makes each row |
| Rust | vec![vec![value; cols]; rows] |
| C | one block of rows * cols items, with the index i * cols + j |
| C++ | std::vector<std::vector<int>>(rows, std::vector<int>(cols, value)) |
| Bash | one line for each row, or one array with the index i * cols + j |
- Python. The FAQ gives the comprehension
A = [[None] * w for i in range(h)]1. The expression[value] * colsruns once for each row, so each row is a new list. - JavaScript. For
Array.from,mapFnis "A function to call on every element of the array"2. The function returns a new row each time. - Java.
new int[rows][cols]makes the outer array and one array for each row, with 0 in each cell.Arrays.fill"Assigns the specified int value to each element of the specified array of ints"3. - C#. "An array can be single-dimensional, multidimensional, or jagged"4. A multidimensional array,
int[,], is one block with one length for each dimension. A jagged array,int[][], is an array of rows, and the rows can have different lengths. The solution makes a jagged array, so that each row is a list as in the contract. - Go. "Like arrays, slices are always one-dimensional but may be composed to construct higher-dimensional objects"5. For a slice of slices, "the inner slices must be initialized individually"5, so the loop makes each row.
- Rust.
vec![elem; n]"will use clone to duplicate an expression"6. The clone of aVecis a new vector, so the rows do not share storage. - C. A function cannot return an array, and the column count of
int a[rows][cols]must be known to index it. The solution returns one block with the rows in order, which is the row-major layout of a C array. The cell at rowiand columnjis at the indexi * cols + j. - C++. The constructor with a count and a value "Constructs a vector with count copies of elements with value value"7. The value is a row, so each copy is a separate vector.
- Bash. "Bash provides one-dimensional indexed and associative array variables"8. The solution prints one line for each row. A program can also keep the grid in one array with the index
i * cols + j.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
no-rows: zero rows give an empty list, and the column count does not matter.no-cols: two rows with zero columns give two empty rows,[[], []]. This is not the same as an empty list. In C, the block has no items, and the row count is lost, so the caller must keeprowsandcols.one-cell,one-rowandone-col: a grid can have one row or one column. The order of the arguments matters:grid(1, 4, 2)has 1 row of 4 items, andgrid(4, 1, 2)has 4 rows of 1 item.negative,min-intandmax-int: the value can be any 32-bit signed integer.- Each test also sets
g[0][0]to a different value and checks thatg[1][0]does not change. This test finds rows that share one list. The concept page multidimensional array compares the layouts.
Pitfalls
- Python
[[0] * 3] * 2repeats one row. Fors * n, "items in the sequence s are not copied; they are referenced multiple times"9. The FAQ says that "replicating a list with * doesn’t create copies, it only creates references to the existing objects"1. So a change to one row shows in each row. Use a comprehension:
g = [[0] * 3] * 2
g[0][0] = 1
print(g)
h = [[0] * 3 for _ in range(2)]
h[0][0] = 1
print(h)
[[1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0]]
- JavaScript fill with an array repeats one row. For
fill, "if value is an object, each slot in the array will reference that object"10. An array is an object, sonew Array(2).fill(new Array(3).fill(0))has one row in two slots.Array.fromwith a function makes a new row for each slot:
const g = new Array(2).fill(new Array(3).fill(0));
g[0][0] = 1;
console.log(g, g[0] === g[1]);
const h = Array.from({ length: 2 }, () => new Array(3).fill(0));
h[0][0] = 1;
console.log(h, h[0] === h[1]);
[ [ 1, 0, 0 ], [ 1, 0, 0 ] ] true
[ [ 1, 0, 0 ], [ 0, 0, 0 ] ] false
- Java clone of a two-dimensional array copies only the outer array. "A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared"11. So a change to a cell of the clone changes the original. Clone each row to make a deep copy:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] g = new int[2][3];
int[][] shallow = g.clone();
shallow[0][0] = 1;
System.out.println(Arrays.deepToString(g));
int[][] deep = new int[g.length][];
for (int i = 0; i < g.length; i++) {
deep[i] = g[i].clone();
}
deep[1][0] = 2;
System.out.println(Arrays.deepToString(g) + " " + Arrays.deepToString(deep));
}
}
[[1, 0, 0], [0, 0, 0]]
[[1, 0, 0], [0, 0, 0]] [[1, 0, 0], [2, 0, 0]]
- C#
new int[2][]has no rows. "A jagged array is an array of arrays, and each member array has the default value of null"4. Sog[0][0]throwsNullReferenceExceptionuntil the code makes each row. A multidimensional array,new int[2, 3], has all its cells at once:
int[][] g = new int[2][];
try
{
g[0][0] = 1;
}
catch (NullReferenceException)
{
Console.WriteLine("NullReferenceException");
}
for (var i = 0; i < g.Length; i++)
{
g[i] = new int[3];
}
g[0][0] = 1;
Console.WriteLine(string.Join(" | ", g.Select(row => string.Join(",", row))));
int[,] m = new int[2, 3];
m[0, 0] = 1;
Console.WriteLine($"{m.GetLength(0)} {m.GetLength(1)} {m[0, 0]}");
NullReferenceException
1,0,0 | 0,0,0
2 3 1
- Go rows cut from one slice can write into the next row. A program can make all the rows from one slice of
rows * colsitems, so that the grid is one block. But a row fromcells[0:3]has the capacity of the rest of the block, soappendto the row writes into the next row. The full slice expressiona[low : high : max]"controls the resulting slice's capacity by setting it to max - low"5, socells[0:3:3]makesappendcopy the row:
package main
import "fmt"
func main() {
cells := make([]int, 6)
g := [][]int{cells[0:3], cells[3:6]}
g[0] = append(g[0], 9)
fmt.Println(g[1])
cells = make([]int, 6)
h := [][]int{cells[0:3:3], cells[3:6:6]}
h[0] = append(h[0], 9)
fmt.Println(h[1], h[0])
}
[9 0 0]
[0 0 0] [0 0 0 9]
- Rust
vec!puts the count after the value. The macro can "Create a Vec from a given element and size"6, asvec![elem; n]. Invec![vec![0; 3]; 2], the inner 3 is the number of columns and the outer 2 is the number of rows, so the grid has 2 rows of 3. Check the lengths when the grid is not square:
fn main() {
let g = vec![vec![0; 3]; 2];
println!("{} rows, {} columns", g.len(), g[0].len());
let mut h = vec![vec![0; 3]; 2];
h[0][0] = 1;
println!("{h:?}");
}
2 rows, 3 columns
[[1, 0, 0], [0, 0, 0]]
- C
int **is not a two-dimensional array. Anint a[2][3]is one block of 6intitems, and "a multidimensional array is converted to a pointer to its first element, e.g., pointer to the first row"12. That pointer has the typeint (*)[3], notint **. A function for the array takesint (*a)[3]orint a[][3], so it knows the length of a row. The output is from a machine with 4-byteint:
#include <stddef.h>
#include <stdio.h>
static int sum(size_t rows, int (*a)[3]) {
int s = 0;
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < 3; j++) {
s += a[i][j];
}
}
return s;
}
int main(void) {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
printf("%zu %zu\n", sizeof a, sizeof a[0]);
printf("%td\n", (char *)&a[1][0] - (char *)&a[0][0]);
printf("%d\n", sum(2, a));
return 0;
}
24 12
12
21
- C++ a vector of rows with a count only has empty rows. The constructor with only a count "Constructs a vector with count default-inserted objects of T"7, and a default-inserted vector is empty. So
std::vector<std::vector<int>> g(2)has 2 rows with no items, andg[0][0]is undefined behavior. Pass the row too:
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> g(2);
std::cout << g.size() << " " << g[0].size() << "\n";
std::vector<std::vector<int>> h(2, std::vector<int>(3, 0));
h[0][0] = 1;
std::cout << h.size() << " " << h[0].size() << " " << h[0][0] << " " << h[1][0] << "\n";
}
2 0
2 3 1 0
- Bash
a[0,1]is not a cell of a grid. "Indexed arrays are referenced using arithmetic expressions that must expand to an integer"8. In an arithmetic expression, the comma is an operator, and0,1has the value 1. Soa[0,1]anda[1,1]are the same item,a[1]. In an associative array, the key0,1is a string, so each cell has its own key:
a=()
a[0,1]=x
a[1,1]=y
echo "${#a[@]} ${!a[@]} ${a[1]}"
declare -A g
g[0,1]=x
g[1,1]=y
echo "${#g[@]} ${g[0,1]} ${g[1,1]}"
1 1 y
2 x y
Related tasks
- Create an array: make an array of one dimension with a given length.
- Get the length of an array: get the number of rows and the number of columns.
- Iterate in chunks: split a list into rows of a fixed size.
- Flatten a nested list: join the rows into one list.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
def grid(rows: int, cols: int, value: int) -> list[list[int]]:
"""Return rows lists of cols items, each item value. No two rows share a list."""
# The comprehension makes a new row for each row. [[value] * cols] * rows
# would repeat one row object.
return [[value] * cols for _ in range(rows)]
test_grid.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
import pytest
from grid import grid
CASES = {
"two-by-three": (2, 3, 0, [[0, 0, 0], [0, 0, 0]]),
"three-by-one": (3, 1, 7, [[7], [7], [7]]),
"no-rows": (0, 3, 1, []),
"no-cols": (2, 0, 1, [[], []]),
"one-cell": (1, 1, 5, [[5]]),
"one-row": (1, 4, 2, [[2, 2, 2, 2]]),
"one-col": (4, 1, 2, [[2], [2], [2], [2]]),
"negative": (2, 2, -3, [[-3, -3], [-3, -3]]),
"min-int": (2, 2, -2147483648, [[-2147483648, -2147483648], [-2147483648, -2147483648]]),
"max-int": (1, 2, 2147483647, [[2147483647, 2147483647]]),
}
@pytest.mark.parametrize("name", CASES)
def test_grid(name):
rows, cols, value, want = CASES[name]
got = grid(rows, cols, value)
assert got == want
if rows >= 2 and cols >= 1:
got[0][0] = value ^ 1
assert got[1][0] == value
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
#include "grid.hpp"
#include <cstddef>
#include <vector>
std::vector<std::vector<int>> grid(std::size_t rows, std::size_t cols, int value) {
// The outer vector holds rows copies of one row, and each copy is a
// separate vector.
return std::vector<std::vector<int>>(rows, std::vector<int>(cols, value));
}
grid.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
#pragma once
#include <cstddef>
#include <vector>
// grid returns rows vectors of cols items, each item value.
std::vector<std::vector<int>> grid(std::size_t rows, std::size_t cols, int value);
test_grid.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
#include "grid.hpp"
#include <climits>
#include <cstddef>
#include <iostream>
#include <string_view>
#include <vector>
using Grid = std::vector<std::vector<int>>;
static int failures = 0;
static void check(std::string_view name, std::size_t rows, std::size_t cols, int value, const Grid &want) {
Grid got = grid(rows, cols, value);
bool ok = got == want;
if (ok && rows >= 2 && cols >= 1) {
got[0][0] = value ^ 1;
ok = got[1][0] == value;
}
if (!ok) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("two-by-three", 2, 3, 0, Grid{std::vector<int>{0, 0, 0}, std::vector<int>{0, 0, 0}});
check("three-by-one", 3, 1, 7, Grid{std::vector<int>{7}, std::vector<int>{7}, std::vector<int>{7}});
check("no-rows", 0, 3, 1, Grid{});
check("no-cols", 2, 0, 1, Grid{std::vector<int>{}, std::vector<int>{}});
check("one-cell", 1, 1, 5, Grid{std::vector<int>{5}});
check("one-row", 1, 4, 2, Grid{std::vector<int>{2, 2, 2, 2}});
check("one-col", 4, 1, 2, Grid{std::vector<int>{2}, std::vector<int>{2}, std::vector<int>{2}, std::vector<int>{2}});
check("negative", 2, 2, -3, Grid{std::vector<int>{-3, -3}, std::vector<int>{-3, -3}});
check("min-int", 2, 2, INT_MIN, Grid{std::vector<int>{INT_MIN, INT_MIN}, std::vector<int>{INT_MIN, INT_MIN}});
check("max-int", 1, 2, INT_MAX, Grid{std::vector<int>{INT_MAX, INT_MAX}});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
import java.util.Arrays;
final class Grid {
private Grid() {}
/** Returns rows arrays of cols items, each item value. No two rows share an array. */
static int[][] grid(int rows, int cols, int value) {
// new int[rows][cols] makes a separate array for each row, filled with 0.
int[][] g = new int[rows][cols];
for (int[] row : g) {
Arrays.fill(row, value);
}
return g;
}
}
GridTest.java 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
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 GridTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("two-by-three", 2, 3, 0, new int[][] {{0, 0, 0}, {0, 0, 0}}),
Arguments.of("three-by-one", 3, 1, 7, new int[][] {{7}, {7}, {7}}),
Arguments.of("no-rows", 0, 3, 1, new int[][] {}),
Arguments.of("no-cols", 2, 0, 1, new int[][] {{}, {}}),
Arguments.of("one-cell", 1, 1, 5, new int[][] {{5}}),
Arguments.of("one-row", 1, 4, 2, new int[][] {{2, 2, 2, 2}}),
Arguments.of("one-col", 4, 1, 2, new int[][] {{2}, {2}, {2}, {2}}),
Arguments.of("negative", 2, 2, -3, new int[][] {{-3, -3}, {-3, -3}}),
Arguments.of("min-int", 2, 2, Integer.MIN_VALUE, new int[][] {{Integer.MIN_VALUE, Integer.MIN_VALUE}, {Integer.MIN_VALUE, Integer.MIN_VALUE}}),
Arguments.of("max-int", 1, 2, 2147483647, new int[][] {{2147483647, 2147483647}}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void grid(String name, int rows, int cols, int value, int[][] want) {
int[][] got = Grid.grid(rows, cols, value);
assertTrue(Arrays.deepEquals(want, got), name);
if (rows >= 2 && cols >= 1) {
got[0][0] = value ^ 1;
assertEquals(value, got[1][0]);
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
#include "grid.h"
#include <stdint.h>
#include <stdlib.h>
int *grid(size_t rows, size_t cols, int value) {
if (cols != 0 && rows > SIZE_MAX / sizeof(int) / cols) {
return NULL;
}
size_t n = rows * cols;
// malloc(0) may return NULL, so ask for at least one item.
int *g = malloc((n > 0 ? n : 1) * sizeof *g);
if (g == NULL) {
return NULL;
}
for (size_t k = 0; k < n; k++) {
g[k] = value;
}
return g;
}
grid.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
#ifndef GRID_H
#define GRID_H
#include <stddef.h>
// grid returns one block of rows * cols ints, each set to value, in row-major
// order: the item at row i and column j is at index i * cols + j. The caller
// must free it. It returns NULL when the size overflows or malloc fails.
int *grid(size_t rows, size_t cols, int value);
#endif
test_grid.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
#include "grid.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
static int failures = 0;
static void check(const char *name, size_t rows, size_t cols, int value) {
int *g = grid(rows, cols, value);
int ok = g != NULL;
for (size_t i = 0; ok && i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
if (g[i * cols + j] != value) {
ok = 0;
}
}
}
if (ok && rows >= 2 && cols >= 1) {
g[0] = value ^ 1;
ok = g[cols] == value;
}
if (!ok) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
free(g);
}
int main(void) {
check("two-by-three", 2, 3, 0);
check("three-by-one", 3, 1, 7);
check("no-rows", 0, 3, 1);
check("no-cols", 2, 0, 1);
check("one-cell", 1, 1, 5);
check("one-row", 1, 4, 2);
check("one-col", 4, 1, 2);
check("negative", 2, 2, -3);
check("min-int", 2, 2, INT_MIN);
check("max-int", 1, 2, INT_MAX);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
public static class Grid
{
// Returns a jagged array: rows arrays of cols items, each item value.
// new int[rows][] leaves every row null, so the loop makes each row.
public static int[][] Make(int rows, int cols, int value)
{
var g = new int[rows][];
for (var i = 0; i < rows; i++)
{
g[i] = new int[cols];
Array.Fill(g[i], value);
}
return g;
}
}
GridTests.cs 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
using Xunit;
public sealed class GridTests
{
public static TheoryData<string, int, int, int, int[][]> Cases => new()
{
{ "two-by-three", 2, 3, 0, new int[][] { new int[] { 0, 0, 0 }, new int[] { 0, 0, 0 } } },
{ "three-by-one", 3, 1, 7, new int[][] { new int[] { 7 }, new int[] { 7 }, new int[] { 7 } } },
{ "no-rows", 0, 3, 1, new int[0][] },
{ "no-cols", 2, 0, 1, new int[][] { new int[0], new int[0] } },
{ "one-cell", 1, 1, 5, new int[][] { new int[] { 5 } } },
{ "one-row", 1, 4, 2, new int[][] { new int[] { 2, 2, 2, 2 } } },
{ "one-col", 4, 1, 2, new int[][] { new int[] { 2 }, new int[] { 2 }, new int[] { 2 }, new int[] { 2 } } },
{ "negative", 2, 2, -3, new int[][] { new int[] { -3, -3 }, new int[] { -3, -3 } } },
{ "min-int", 2, 2, int.MinValue, new int[][] { new int[] { int.MinValue, int.MinValue }, new int[] { int.MinValue, int.MinValue } } },
{ "max-int", 1, 2, 2147483647, new int[][] { new int[] { 2147483647, 2147483647 } } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int rows, int cols, int value, int[][] want)
{
Assert.NotNull(name);
var got = Grid.Make(rows, cols, value);
Assert.Equal(want.Length, got.Length);
for (var i = 0; i < want.Length; i++)
{
Assert.Equal(want[i], got[i]);
}
if (rows >= 2 && cols >= 1)
{
got[0][0] = value ^ 1;
Assert.Equal(value, got[1][0]);
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
/**
* Returns rows arrays of cols items, each item value. No two rows share an array.
* @param {number} rows
* @param {number} cols
* @param {number} value
* @returns {number[][]}
*/
export function grid(rows, cols, value) {
// The function makes a new row for each row. new Array(rows).fill(row)
// would put one row object in every slot.
return Array.from({ length: rows }, () => new Array(cols).fill(value));
}
grid.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { grid } from "./grid.js";
const cases = [
["two-by-three", 2, 3, 0, [[0, 0, 0], [0, 0, 0]]],
["three-by-one", 3, 1, 7, [[7], [7], [7]]],
["no-rows", 0, 3, 1, []],
["no-cols", 2, 0, 1, [[], []]],
["one-cell", 1, 1, 5, [[5]]],
["one-row", 1, 4, 2, [[2, 2, 2, 2]]],
["one-col", 4, 1, 2, [[2], [2], [2], [2]]],
["negative", 2, 2, -3, [[-3, -3], [-3, -3]]],
["min-int", 2, 2, -2147483648, [[-2147483648, -2147483648], [-2147483648, -2147483648]]],
["max-int", 1, 2, 2147483647, [[2147483647, 2147483647]]],
];
for (const [name, rows, cols, value, want] of cases) {
test(name, () => {
const got = grid(rows, cols, value);
assert.deepEqual(got, want);
if (rows >= 2 && cols >= 1) {
got[0][0] = value ^ 1;
assert.equal(got[1][0], value);
}
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
export function grid(rows: number, cols: number, value: number): number[][] {
// The function makes a new row for each row. new Array(rows).fill(row)
// would put one row object in every slot.
return Array.from({ length: rows }, () => new Array<number>(cols).fill(value));
}
grid.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { grid } from "./grid.ts";
const cases: [string, number, number, number, number[][]][] = [
["two-by-three", 2, 3, 0, [[0, 0, 0], [0, 0, 0]]],
["three-by-one", 3, 1, 7, [[7], [7], [7]]],
["no-rows", 0, 3, 1, []],
["no-cols", 2, 0, 1, [[], []]],
["one-cell", 1, 1, 5, [[5]]],
["one-row", 1, 4, 2, [[2, 2, 2, 2]]],
["one-col", 4, 1, 2, [[2], [2], [2], [2]]],
["negative", 2, 2, -3, [[-3, -3], [-3, -3]]],
["min-int", 2, 2, -2147483648, [[-2147483648, -2147483648], [-2147483648, -2147483648]]],
["max-int", 1, 2, 2147483647, [[2147483647, 2147483647]]],
];
for (const [name, rows, cols, value, want] of cases) {
test(name, () => {
const got = grid(rows, cols, value);
assert.deepEqual(got, want);
if (rows >= 2 && cols >= 1) {
got[0][0] = value ^ 1;
assert.equal(got[1][0], value);
}
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
// Package twodarray makes a two-dimensional slice.
package twodarray
// Grid returns rows slices of cols items, each item value. No two rows share
// an array.
func Grid(rows, cols, value int) [][]int {
g := make([][]int, rows)
for i := range g {
row := make([]int, cols)
for j := range row {
row[j] = value
}
g[i] = row
}
return g
}
grid_test.go 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
package twodarray
import (
"slices"
"testing"
)
var cases = []struct {
name string
rows, cols, value int
want [][]int
}{
{"two-by-three", 2, 3, 0, [][]int{{0, 0, 0}, {0, 0, 0}}},
{"three-by-one", 3, 1, 7, [][]int{{7}, {7}, {7}}},
{"no-rows", 0, 3, 1, [][]int{}},
{"no-cols", 2, 0, 1, [][]int{{}, {}}},
{"one-cell", 1, 1, 5, [][]int{{5}}},
{"one-row", 1, 4, 2, [][]int{{2, 2, 2, 2}}},
{"one-col", 4, 1, 2, [][]int{{2}, {2}, {2}, {2}}},
{"negative", 2, 2, -3, [][]int{{-3, -3}, {-3, -3}}},
{"min-int", 2, 2, -2147483648, [][]int{{-2147483648, -2147483648}, {-2147483648, -2147483648}}},
{"max-int", 1, 2, 2147483647, [][]int{{2147483647, 2147483647}}},
}
func TestGrid(t *testing.T) {
for _, c := range cases {
got := Grid(c.rows, c.cols, c.value)
if !slices.EqualFunc(got, c.want, slices.Equal[[]int]) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
if c.rows >= 2 && c.cols >= 1 {
got[0][0] = c.value ^ 1
if got[1][0] != c.value {
t.Errorf("%s: the rows share an array", c.name)
}
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
/// Returns rows vectors of cols items, each item value.
pub fn grid(rows: usize, cols: usize, value: i32) -> Vec<Vec<i32>> {
// vec! clones the inner vector for each row, so the rows do not share storage.
vec![vec![value; cols]; rows]
}
tests/grid_test.rs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
use algo_create_a_two_dimensional_array::grid;
#[test]
fn cases() {
let want: Vec<Vec<i32>> = vec![vec![0, 0, 0], vec![0, 0, 0]];
assert_eq!(grid(2, 3, 0), want, "two-by-three");
let want: Vec<Vec<i32>> = vec![vec![7], vec![7], vec![7]];
assert_eq!(grid(3, 1, 7), want, "three-by-one");
let want: Vec<Vec<i32>> = vec![];
assert_eq!(grid(0, 3, 1), want, "no-rows");
let want: Vec<Vec<i32>> = vec![vec![], vec![]];
assert_eq!(grid(2, 0, 1), want, "no-cols");
let want: Vec<Vec<i32>> = vec![vec![5]];
assert_eq!(grid(1, 1, 5), want, "one-cell");
let want: Vec<Vec<i32>> = vec![vec![2, 2, 2, 2]];
assert_eq!(grid(1, 4, 2), want, "one-row");
let want: Vec<Vec<i32>> = vec![vec![2], vec![2], vec![2], vec![2]];
assert_eq!(grid(4, 1, 2), want, "one-col");
let want: Vec<Vec<i32>> = vec![vec![-3, -3], vec![-3, -3]];
assert_eq!(grid(2, 2, -3), want, "negative");
let want: Vec<Vec<i32>> = vec![vec![i32::MIN, i32::MIN], vec![i32::MIN, i32::MIN]];
assert_eq!(grid(2, 2, i32::MIN), want, "min-int");
let want: Vec<Vec<i32>> = vec![vec![2147483647, 2147483647]];
assert_eq!(grid(1, 2, 2147483647), want, "max-int");
}
#[test]
fn rows_are_separate() {
let mut g = grid(2, 3, 0);
g[0][0] = 1;
assert_eq!(g[1][0], 0);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
# grid ROWS COLS VALUE
# Prints ROWS lines, one for each row, with COLS copies of VALUE separated by
# spaces. Bash arrays have one dimension, so a program keeps a grid as lines,
# as one array with the index row * cols + col, or as an associative array.
grid() {
local rows=$1 cols=$2 value=$3 i j
local -a row=()
for ((j = 0; j < cols; j++)); do
row+=("$value")
done
for ((i = 0; i < rows; i++)); do
printf '%s\n' "${row[*]}"
done
}
test_grid.bats 34 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-two-dimensional-array/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/grid.sh"
}
lines() { # lines ROW...: prints each row on a line, and nothing for no rows
if (($# > 0)); then printf '%s\n' "$@"; fi
}
check() { # check ROWS COLS VALUE -- ROW...
local rows=$1 cols=$2 value=$3
shift 4
local got want
# The x keeps the trailing newlines, which $(...) removes.
got=$(grid "$rows" "$cols" "$value"; printf x)
want=$(lines "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "two-by-three" { check 2 3 0 -- "0 0 0" "0 0 0"; }
@test "three-by-one" { check 3 1 7 -- "7" "7" "7"; }
@test "no-rows" { check 0 3 1 --; }
@test "no-cols" { check 2 0 1 -- "" ""; }
@test "one-cell" { check 1 1 5 -- "5"; }
@test "one-row" { check 1 4 2 -- "2 2 2 2"; }
@test "one-col" { check 4 1 2 -- "2" "2" "2" "2"; }
@test "negative" { check 2 2 -3 -- "-3 -3" "-3 -3"; }
@test "min-int" { check 2 2 -2147483648 -- "-2147483648 -2147483648" "-2147483648 -2147483648"; }
@test "max-int" { check 1 2 2147483647 -- "2147483647 2147483647"; }
References
- Python Programming FAQ, How do I create a multidimensional list?
- MDN Web Docs, Array.from(), Parameters
- Java SE 25 API, Class Arrays, fill(int[] a, int val)
- C# language reference, Arrays, Array overview and Jagged arrays
- The Go Programming Language Specification, Slice types and Slice expressions
- Rust standard library, macro vec, Description
- cppreference.com, std::vector constructor, Description
- Bash Reference Manual, 6.7 Arrays
- The Python Standard Library, Built-in Types, Common Sequence Operations, note 2
- MDN Web Docs, Array.prototype.fill(), Parameters
- The Java Language Specification, Java SE 25 Edition, 10.7 Array Members
- cppreference.com, C array declaration, Multidimensional 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 9WX5NJ Edit this page History Report an error Markdown