0

I'm attempting to code a Huffman Encoding system in VB, using .NET 6. Here is the main code as it currently stands, using 'ConstructionQueue' as a priority queue to handle the nodes being added to the 'Tree' list. 'Node' is an abstract class from which 'LeafNode' and 'InternalNode' inherit; at the time this class is run, ConstructionQueue is filled with only LeafNode's. My issue is that I need to add InternalNodes to the queue during this initialization process to be handled. Here is the current code:

Public Class HuffmanTree

    Private Tree As New List(Of Node)
    
     Public Sub New(ByVal ConstructionQueue As PriorityQueue)
        Dim PairMade As Boolean = False
        Dim NodesProcessed As Integer = 0
        Dim TempWeight As Integer
        For Each Node In ConstructionQueue.QueueFrame

            If ConstructionQueue.GetFrontPointer <> 0 And ConstructionQueue.GetFrontPointer Mod 2 = 0 Then
                PairMade = True
            End If
            Tree.Insert(NodesProcessed, Node)

            If PairMade = True Then
                
                Dim TempNode As New InternalNode(ConstructionQueue.QueueFrame(ConstructionQueue.GetFrontPointer).GetWeight + TempWeight)

                TempNode.SetLeftPointer(Tree(NodesProcessed - 1))
                TempNode.SetRightPointer(Tree(NodesProcessed))    
                ConstructionQueue.Enqueue(TempNode)      
                PairMade = False
            Else
                TempWeight = Node.GetWeight    
            End If
           
            NodesProcessed += 1
            ConstructionQueue.SetFrontPointer(NodesProcessed)

        Next

    End Sub

End Class

Collection was modified; enumeration operation may not execute.

is the error I receive on the 'Next' before End Sub. I completely understand why, the issue is that I can't alter the size of the 'QueueFrame' List, but I need a method of doing this that is going to allow me to go through each node in the list whilst being able to change its size, as there will be multiple instances where I need to add to the list as I'm using it.

Does anyone know of any sort of workaround or fix to this? I'd be happy to provide any more information needed.

djv
  • 15,168
  • 7
  • 48
  • 72
  • 1
    The workaround is to not use a `For Each` loop to iterate over the list. `List(Of T)` has indexed access, so you'll need to use that instead. Keep in mind that you'll need to update your bounds for changes to the list size as you're iterating; a `For` loop may pre-compute the loop bounds (I'm not sure, I haven't tested it). – Craig Feb 25 '22 at 14:09
  • 2
    @Craig In C#, the loop boundary condition is evaluated on each iteration. In VB.NET, it is only evaluated on entry to the loop. (From my answer to [Why does a for loop behave differently when migrating VB.NET code to C#?](https://stackoverflow.com/q/52607611/1115360)) – Andrew Morton Feb 25 '22 at 16:28

0 Answers0