Imports System
Imports System.Collections.Generic
'
' A sparse array stores only non‑zero values.
' Dictionary(Of Integer, Integer) is a natural fit:
' - Keys represent indices that actually exist
' - Values represent stored data
' - Lookup and insertion are fast
'
Module SparseArrayDemo
'
' buildDense:
' Converts sparse → dense.
'
' Steps:
' 1. Find the maximum index in the sparse structure
' 2. Allocate a dense array of size maxIndex + 1
' 3. Fill with zeros (VB.NET does this automatically)
' 4. Copy sparse values into their positions
'
Function BuildDense(sa As Dictionary(Of Integer, Integer)) As Integer()
Dim maxIndex As Integer = 0
' Find largest index
For Each kvp In sa
If kvp.Key > maxIndex Then
maxIndex = kvp.Key
End If
Next
' Allocate dense array
Dim dense(maxIndex) As Integer
' Copy sparse values
For Each kvp In sa
dense(kvp.Key) = kvp.Value
Next
Return dense
End Function
Sub Main()
'
' Sparse entries (zero values omitted)
'
Dim sa As New Dictionary(Of Integer, Integer) From {
{2, 10},
{10, 7},
{8, 42},
{3, 5}
}
Dim dense() As Integer = BuildDense(sa)
Console.WriteLine("Dense array:")
Console.Write("[ ")
For Each v In dense
Console.Write(v & " ")
Next
Console.WriteLine("]")
End Sub
End Module
' run:
' Dense array:
' [ 0 0 10 5 0 0 0 0 42 0 7 ]
'