arrays
Complete
Summary
Concept of a buffer
js
// initialisation
const x = [1, 2, 3];
// indexing
const a = x[1];
// assignment
x[4] = 4;
// length
array_length(x); // 5
Concept
An array is a sequence of elements
Elements in the array can be initialised, assigned or indexed
Random access -> constant time read and write, except if writing to an index larger than array length
Application
Array processing functions
Main idea:
- iterate through the elements in the array
js
function map_array(f, arr) {
const len = array_length(arr);
function iter(i) {
if (i < len) {
arr[i] = f(arr[i]);
iter(i + 1);
}
}
iter(0);
}
const seq = [3, 1, 5];
map_array(x => 2 * x, seq);
seq; // -> [6, 2, 10]; destructive operation
function array_1_to_n(n) {
const a = [];
function iter(i) {
if (i < n) {
a[i] = i + 1;
iter(i + 1);
}
}
iter(0);
return a;
}
array_1_to_n(3); // -> [1, 2, 3]
Matricies as 2d arrays, 3 by 4 matrix
js
const matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
Note
Some programming languages, ie. Python, do not allow assignment to indexes out of the range of the array
In Source/JS, the value is assigned regardless if the index is already initialised, any in-between indices are left as undefined