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,753 questions

55,518 answers

573 users

How to build sparse array in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

/*
    A sparse array stores only non‑zero values.
    Go's map[int]int is a natural fit:
      - Keys represent indices that actually exist
      - Values represent stored data
      - Lookup and insertion are fast
*/

type SparseArray map[int]int
type DenseArray []int

/*
    buildDense:
    Converts sparse → dense.

    Steps:
    1. Find the maximum index in the sparse structure
    2. Allocate a dense slice of size maxIndex + 1
    3. Fill with zeros (Go does this automatically)
    4. Copy sparse values into their positions
*/
func buildDense(sa SparseArray) DenseArray {
    var maxIndex int = 0

    // Find largest index
    for index := range sa {
        if index > maxIndex {
            maxIndex = index
        }
    }

    // Allocate dense slice filled with zeros
    dense := make(DenseArray, maxIndex+1)

    // Copy sparse values
    for index, value := range sa {
        dense[index] = value
    }

    return dense
}

func main() {
    // Sparse entries (zero values omitted)
    sa := SparseArray{
        2:  10,
        10: 7,
        8:  42,
        3:  5,
    }

    dense := buildDense(sa)

    fmt.Println("Dense array:")
    fmt.Print("[ ")
    for _, v := range dense {
        fmt.Print(v, " ")
    }
    fmt.Println("]")
}


/*
run:

Dense array:
[ 0 0 10 5 0 0 0 0 42 0 7 ]

*/

 



answered 2 days ago by avibootz
...