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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to convert a 2D array to a 1D array in Go

2 Answers

0 votes
package main
 
import "fmt"
 
func convert2DArrTo1DArr(arr2d [][]int) []int {
    rows := len(arr2d)
    cols := len(arr2d[0])
 
    arr := make([]int, rows * cols)
    k := 0
 
    for i := 0; i < rows; i++ {
        for j := 0; j < cols; j++ {
            arr[k] = arr2d[i][j]
            k++
        }
    }
 
    return arr
}
 
func main() {
    arr2d := [][]int{
        {5, 6, 1, 8},
        {3, 2, 0, 4},
        {9, 8, 7, 6},
    }
 
    arr := convert2DArrTo1DArr(arr2d)
 
    for _, n := range arr {
        fmt.Print(n, " ")
    }
}
 
 
/*
run:
 
5 6 1 8 3 2 0 4 9 8 7 6
 
*/

 



answered Aug 14, 2024 by avibootz
edited Dec 27, 2024 by avibootz
0 votes
package main

import "fmt"

func main() {
    arr2d := [][]int{
        {5, 6, 1, 8},
        {3, 2, 0, 4},
        {9, 8, 7, 6},
    }

    oneDArray := convert2DArrTo1DArr(arr2d)

    fmt.Println(oneDArray)
}

func convert2DArrTo1DArr(twoDArray [][]int) []int {
    var oneDArray []int
    
    for _, row := range twoDArray {
        for _, element := range row {
            oneDArray = append(oneDArray, element)
        }
    }
    
    return oneDArray
}

 
 
/*
run:

[5 6 1 8 3 2 0 4 9 8 7 6]
   
*/

 



answered Dec 27, 2024 by avibootz

Related questions

1 answer 79 views
79 views asked Jan 10, 2025 by avibootz
1 answer 94 views
1 answer 126 views
1 answer 148 views
148 views asked Sep 4, 2020 by avibootz
...