How to flatten a 2D array into a sorted one-dimensional array in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "sort"
)

// Function that flattens a 2D int slice and returns a sorted 1D slice
func flattenAndSort(array2d [][]int) []int {

    // 1. Count total number of elements
    total := 0
    for _, row := range array2d {
        total += len(row)
    }

    // 2. Allocate the result slice
    result := make([]int, 0, total)

    // 3. Flatten the 2D slice into the 1D slice
    for _, row := range array2d {
        result = append(result, row...)
    }

    // 4. Sort the flattened slice
    sort.Ints(result)

    return result
}

func main() {
    array2d := [][]int{
        {4, 5, 3},
        {30, 20},
        {10},
        {1, 2, 6, 7, 8},
    }

    // Call the function
    arr := flattenAndSort(array2d)

    // Print result as comma-separated values
    for i, v := range arr {
        if i > 0 {
            fmt.Print(", ")
        }
        fmt.Print(v)
    }
    fmt.Println()
}



/*
run:

1, 2, 3, 4, 5, 6, 7, 8, 10, 20, 30

*/

 



answered 2 hours ago by avibootz

Related questions

...