arrays

Complete

Concept

An array is a sequence of elements

  • elements in the array can be initialised, assigned or indexed
js
// initialisation
const x = [1, 2, 3];
// indexing
const a = x[1];
// assignment
x[4] = 4;
// length
array_length(x); // 5
x1234x[0]x[4]a

Random access

  • constant time read and write, except if writing to an index larger than array length

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

Application

Array processing functions

  • 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]]