How to count and print triplets from an array with sum smaller than a given value in VB.NET

1 Answer

0 votes
Imports System

Public Class Program
    Public Shared Sub Main(ByVal args As String())
        Dim array As Integer() = New Integer() {4, 5, 2, 8, 1, 3, 8, 7, 10}
        Dim size As Integer = array.Length
        Dim sum As Integer = 11
        Dim count As Integer = 0

        For i As Integer = 0 To size - 2 - 1
            For j As Integer = i + 1 To size - 1 - 1
                For k As Integer = j + 1 To size - 1
                    If array(i) + array(j) + array(k) < sum Then
                        count += 1
                        Console.Write(count & ": ")
                        Console.Write(array(i) & ",")
                        Console.Write(array(j) & ",")
                        Console.WriteLine(array(k))
                    End If
                Next
            Next
        Next

        Console.Write("Number of Triplets = " & count)
    End Sub
End Class




' run:
'
' 1: 4,5,1
' 2: 4,2,1
' 3: 4,2,3
' 4: 4,1,3
' 5: 5,2,1
' 6: 5,2,3
' 7: 5,1,3
' 8: 2,1,3
' 9: 2,1,7
' Number of Triplets = 9
' 

 



answered Sep 16, 2022 by avibootz
...