How to multiply every N consecutive items in a list with VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Module Program

    Function ProductsNConsecutiveItems(lst As List(Of Integer),
                                       nConsecutiveItems As Integer) As List(Of Integer)

        Dim products As New List(Of Integer)()

        If nConsecutiveItems <= 0 OrElse lst.Count < nConsecutiveItems Then
            Return products   ' empty
        End If

        Dim outSize As Integer = lst.Count - nConsecutiveItems + 1

        For i As Integer = 0 To outSize - 1
            Dim prod As Integer = 1

            ' Multiply lst(i) * lst(i+1) * ... * lst(i+nConsecutiveItems-1)
            For j As Integer = 0 To nConsecutiveItems - 1
                prod *= lst(i + j)
            Next

            products.Add(prod)

            '
            ' Example for nConsecutiveItems = 3:
            ' 2 * 3 * 4  = 24
            ' 3 * 4 * 5  = 60
            ' 4 * 5 * 6  = 120
            ' 5 * 6 * 7  = 210
            ' 6 * 7 * 8  = 336
            ' 7 * 8 * 9  = 504
            ' 8 * 9 * 10 = 720
            '
        Next

        Return products
    End Function

    Sub Main()
        Dim lst As New List(Of Integer) From {2, 3, 4, 5, 6, 7, 8, 9, 10}
        Dim n As Integer = 3

        Dim products As List(Of Integer) = ProductsNConsecutiveItems(lst, n)

        Console.Write("[")
        For i As Integer = 0 To products.Count - 1
            Console.Write(products(i))
            If i < products.Count - 1 Then Console.Write(", ")
        Next
        Console.WriteLine("]")
    End Sub

End Module



' run:
'
' [24, 60, 120, 210, 336, 504, 720]
' 

 



answered Feb 1 by avibootz

Related questions

...