/*
Find the N smallest values in a 2D array.
Approach:
1. Flatten the 2D array into a single list.
2. Sort the list.
3. Take the first N values.
TypeScript's built‑in array methods make this approach expressive
and efficient for typical workloads.
*/
// Flatten a 2D array into a single list
function flatten(matrix: number[][]): number[] {
// matrix.flat() works because the array is only 2 levels deep
return matrix.flat();
}
// Extract the N smallest values
function smallestN(matrix: number[][], n: number): number[] {
const flat: number[] = flatten(matrix);
// Sort ascending
const sorted: number[] = [...flat].sort((a: number, b: number) => a - b);
// Return the first N values
return sorted.slice(0, n);
}
// Main
const matrix: number[][] = [
[42, 12, 85, 3],
[ 7, 99, 15, 23],
[64, 1, 18, 30],
[ 3, 55, 11, 90]
];
const n: number = 5;
const values: number[] = smallestN(matrix, n);
console.log(`The ${n} smallest values:`);
console.log(values.join(" "));
/*
run:
The 5 smallest values:
1 3 3 7 11
*/