Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,683 questions

55,435 answers

573 users

How to find the N smallest values in a 2D slice in Go

1 Answer

0 votes
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 

*/

 



answered 2 days ago by avibootz

Related questions

2 answers 291 views
291 views asked Aug 27, 2020 by avibootz
1 answer 177 views
1 answer 213 views
3 answers 265 views
1 answer 196 views
...