How to print all distinct 4 elements from an array that have the same given sum in VB.NET

1 Answer

0 votes
Imports System

Public Class [MyClass]
    Public Shared Sub getDistinct4Elements(ByVal arr As Integer(), ByVal sum As Integer)
        Array.Sort(arr)
		
        Dim size As Integer = arr.Length

        For i As Integer = 0 To size - 4
    		For j As Integer = i + 1 To size - 3
                Dim k As Integer = sum - (arr(i) + arr(j))
                Dim fromstart As Integer = j + 1
                Dim fromend As Integer = size - 1

                While fromstart < fromend
        			If arr(fromstart) + arr(fromend) < k Then
                        fromstart += 1
                    ElseIf arr(fromstart) + arr(fromend) > k Then
                        fromend -= 1
                    Else
                        Console.Write(arr(i) & ", " & arr(j) & ", ")
                        Console.WriteLine(arr(fromstart) & ", " & arr(fromend))
                        fromstart += 1
                        fromend -= 1
                    End If
                End While
            Next
        Next
    End Sub

    Public Shared Sub Main(ByVal args As String())
        Dim arr As Integer() = New Integer() {4, 8, 1, 5, 9, 0, 3, 7}

        Dim sum As Integer = 18

        getDistinct4Elements(arr, sum)
    End Sub
End Class




' run:
'
' 0, 1, 8, 9
' 0, 3, 7, 8
' 0, 4, 5, 9
' 1, 3, 5, 9
' 1, 4, 5, 8
' 

 



answered Aug 20, 2022 by avibootz
...