How to calculate the products of (jagged) uneven-sized matrix columns in VB.NET

2 Answers

0 votes
' matrix = [
'     [1, 2, 3],
'     [4, 5],
'     [6, 7, 8, 9]
' ]

Imports System
Imports System.Linq
Imports System.Collections.Generic

Module Program

    Function ColumnProducts(matrix As Integer()()) As Integer()
        ' Determine the maximum number of columns in any row
        Dim maxCols = matrix.Max(Function(row) row.Length)

        Dim products As New List(Of Integer)

        For col = 0 To maxCols - 1
            ' Collect values that exist in this column
            Dim colValues = matrix.
                Where(Function(row) col < row.Length).
                Select(Function(row) row(col))

            ' Multiply them together
            Dim product = colValues.Aggregate(1, Function(acc, v) acc * v)
            products.Add(product)
        Next

        Return products.ToArray()
    End Function

    Sub Main()
        Dim matrix As Integer()() = {
            New Integer() {1, 2, 3},
            New Integer() {4, 5},
            New Integer() {6, 7, 8, 9}
        }

        Dim result = ColumnProducts(matrix)

        Console.WriteLine("Column products: " & String.Join(", ", result))
    End Sub

End Module


' run:
'
'  Column products: 24, 70, 24, 9
'

 



answered Feb 12 by avibootz
0 votes
Imports System
Imports System.Linq
Imports System.Collections.Generic

Module Program

    Function ColumnProducts(matrix As Integer()()) As Integer()
        ' Determine the maximum number of columns in any row
        Dim maxCols = matrix.Max(Function(row) row.Length)

        Dim products As New List(Of Integer)

        For col = 0 To maxCols - 1
            ' Collect values that exist in this column
            Dim colValues = matrix.
                Where(Function(row) col < row.Length).
                Select(Function(row) row(col))

            ' Multiply them together
            Dim product = colValues.Aggregate(1, Function(acc, v) acc * v)
            products.Add(product)
        Next

        Return products.ToArray()
    End Function

    Sub Main()
        Dim matrix As Integer()() = {
            New Integer() {1, 2, 3},
            New Integer() {4, 5},
            New Integer() {6, 7, 8, 9}
        }

        Dim result = ColumnProducts(matrix)

        Console.WriteLine("Column products: " & String.Join(", ", result))
    End Sub

End Module



' run:
'
'  Column products: 24, 70, 24, 9
'

 



answered Feb 12 by avibootz
...