UNPKG

agentscape

Version:

Agentscape is a library for creating agent-based simulations. It provides a simple API for defining agents and their behavior, and for defining the environment in which the agents interact. Agentscape is designed to be flexible and extensible, allowing

64 lines (56 loc) 1.91 kB
export default class Array { /** * Gets the maximum value in an array. */ public static minimizeBy<T>(arr: T[], fn: (item: T) => number): T { return arr.reduce((a, b) => fn(a) < fn(b) ? a : b) } /** * Gets the minimum value in an array. */ public static maximizeBy<T>(arr: T[], fn: (item: T) => number): T { return arr.reduce((a, b) => fn(a) > fn(b) ? a : b) } /** * Sum all the values in an array. */ public static sum(arr: number[]): number { return arr.reduce((a, b) => a + b, 0) } /** * Get the average (mean) of an array of numbers. */ public static average(arr: number[]): number { return this.sum(arr) / arr.length } /** * Performs a convolution on a 2D array. */ public static convolve2D(arr: number[][], kernel: number[][]): number[][] { const kernelSize = kernel.length const kernelRadius = Math.floor(kernelSize / 2) const result: number[][] = [] for (let i = 0; i < arr.length; i++) { result[i] = [] for (let j = 0; j < arr[0].length; j++) { result[i][j] = 0 } } for (let y = 0; y < arr.length; y++) { for (let x = 0; x < arr[0].length; x++) { for (let ky = 0; ky < kernelSize; ky++) { for (let kx = 0; kx < kernelSize; kx++) { const dx = kx - kernelRadius const dy = ky - kernelRadius const nx = x + dx const ny = y + dy if (nx >= 0 && nx < arr[0].length && ny >= 0 && ny < arr.length) { result[y][x] += arr[ny][nx] * kernel[ky][kx] } } } } } return result } }