package main
import (
"fmt"
"sort"
)
/*
Find the N smallest values in a 2D array.
Approach:
1. Flatten the 2D array into a single slice.
2. Sort the slice.
3. Take the first N values.
Go's standard library provides a fast, reliable sort implementation,
and slices make the flattening step straightforward.
*/
// Flatten converts a 2D array into a 1D slice.
func Flatten(matrix [][]int) []int {
flat := make([]int, 0, len(matrix)*len(matrix[0]))
for _, row := range matrix {
for _, value := range row {
flat = append(flat, value)
}
}
return flat
}
// SmallestN returns the N smallest values from a 2D array.
func SmallestN(matrix [][]int, n int) []int {
flat := Flatten(matrix)
// Sort ascending
sort.Ints(flat)
// Guard against n > len(flat)
if n > len(flat) {
n = len(flat)
}
return flat[:n]
}
func main() {
matrix := [][]int{
{42, 12, 85, 3},
{7, 99, 15, 23},
{64, 1, 18, 30},
{3, 55, 11, 90},
}
n := 5
values := SmallestN(matrix, n)
fmt.Printf("The %d smallest values:\n", n)
for _, v := range values {
fmt.Printf("%d ", v)
}
fmt.Println()
}
/*
run:
The 5 smallest values:
1 3 3 7 11
*/