#
# 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.
#
# Ruby's built‑in methods make this approach expressive
# and efficient for typical workloads.
#
# Flatten a 2D array into a 1D array
def flatten(matrix)
# matrix.flatten works because the array is only 2 levels deep
matrix.flatten
end
# Extract the N smallest values
def smallest_n(matrix, n)
flat = flatten(matrix)
# Sort ascending
sorted = flat.sort
# Return the first N values
sorted.take(n)
end
# Main
matrix = [
[42, 12, 85, 3],
[ 7, 99, 15, 23],
[64, 1, 18, 30],
[ 3, 55, 11, 90]
]
n = 5
values = smallest_n(matrix, n)
puts "The #{n} smallest values:"
puts values.join(" ")
#
# run:
#
# The 5 smallest values:
# 1 3 3 7 11
#