0

comps.Contains doesn't return TRUE even though comps contains it.

I debugged it step by step and I can't see where the problem is.

By the way the purpose of the code is to show the pairs that sum up to SUM value. (If the sum is 5 and theres 1 and 4 then the code should return 1 and 4)

Public Function getPairs(ByVal array As ArrayList, ByVal sum As Integer)
    Dim comps, pairs As New ArrayList
    For index = 0 To array.Count - 1
        If (comps.Contains(array(index)) = True) Then
            pairs.Add(array(index))
        Else
            comps.Add(sum - array(index))
        End If
    Next
    Return pairs
End Function

Sub Main()
    ' 1,3,2,5,46,6,7,4
    ' k = 5
    'Dim arraylist As New ArrayList()
    Console.Write("Enter your array :")
    Dim arraylist As New ArrayList
    arraylist.AddRange(Console.ReadLine().Split(","))
    Console.Write("Enter the sum:")
    Dim sum As Integer = Console.ReadLine()
    getPairs(arraylist, sum)
    Console.ReadKey()
End Sub
0

3 Answers 3

1

The ArrayList you populate from user input contains strings (results from splitting the user input string). The comps ArrayList contains integers (results from subtraction). When it tries to find the string "2" in the ArrayList that contains a 2, it fails.

You should convert your user input to integers so that you are comparing the same data types.

Sign up to request clarification or add additional context in comments.

2 Comments

I changed If (comps.Contains(array(index)) = True) Then To This: If (comps.Contains((array(index).ToString))) Then And debugged it, both array and the comps values are String but it still returns False. (Instead of changing users input's type I changed the array's)
The issue is reversed, array already has strings, comps has integers.
1

First, turn on Option Strict. Tools Menu -> Options -> Projects and Solutions -> VB Defaults. This will point out problems with your code and help you to avoid runtime errors.

ArrayList is not used much in new code but is around for backward compatibility. List(Of T) is a better choice for new code.

Module Module1
    Sub Main()
        ' 1,3,2,5,46,6,7,4
        ' k = 5
        'Dim arraylist As New ArrayList()
        Console.Write("Enter your array :")
        Dim arraylist As New ArrayList
        'Option Strict would not allow this line to compile
        '.Split takes a Char, the same c tells the compiler that "," is a Char
        arraylist.AddRange(Console.ReadLine().Split(","c))
        Console.Write("Enter the sum:")
        'Option Strict would not allow a string to be dumped into an integer
        Dim sum As Integer
        Dim Pairs As New ArrayList
        If Integer.TryParse(Console.ReadLine, sum) Then
            'Your Function returns an array list but you
            'throw it away by not setting up a variable to receive it
            Pairs = getPairs(arraylist, sum)
        Else
            Console.WriteLine("Program aborted. Sum was not a number.")
        End If
        For Each item In Pairs
            Console.WriteLine(item)
        Next
        Console.ReadKey()
    End Sub
    'Functions need a return data type in the declaration
    Public Function getPairs(ByVal array As ArrayList, ByVal sum As Integer) As ArrayList
        Dim comps, pairs As New ArrayList
        For index = 0 To array.Count - 1
            'I don't see how this can ever be true since comps is empty
            If comps.Contains(array(index)) Then 'Since .Contains returns a Boolean, no = True is necessary
                pairs.Add(array(index))
            Else
                'Ideally each item in array should be tested to see if it is a number
                'You will get an exception if CInt fails
                comps.Add(sum - CInt(array(index)))
                'You never use the comps ArrayList
            End If
        Next
        'The pairs ArrayList is empty
        Return pairs
    End Function
End Module

I don't see how this code could accomplish what you describe as your goal. I think you should start again. Talk through how you would accomplish your task. Then write it out on paper, not in code. Then you will see more clearly how to code your project.

2 Comments

comps starts empty, but is added to as the for loop runs.
... but the advice to turn on Option Strict is solid, as is the comment about ArrayList being obsolete, and using TryParse() (my answer is lazy about the parsing) :)
0

The big problem is the original code is this line:

Dim comps, pairs As New ArrayList

That code creates two ArrayList reference variables, but only one ArrayList object. comps remains null/Nothing.

But beyond that, the ArrayList type has been dead since .Net 2.0 came out back in 2005... more than 10 years now. It only exists today for backwards compatibility with old code. Don't use it!

This is better practice, especially in conjunction with Option Strict and Option Infer:

Public Function getPairs(ByVal items As IEnumerable(Of Integer), ByVal sum As Integer) As IEnumerable(Of Integer)
    Dim comps As New HashSet(Of Integer)()
    Dim result As New List(Of Integer)()

    For Each item As Integer In items
        If Not comps.Add(item) Then
           result.Add(sum - item)
        End If
    Next
    Return result
End Function

Sub Main()
    Console.Write("Enter your array: ")
    Dim input As String = Console.ReadLine()

    Dim list As List(Of Integer) = input.Split(",").Select(Function(item) CInt(item)).ToList()

    Console.Write("Enter the sum: ")
    Dim sum As Integer = CInt(Console.ReadLine())

    Dim pairs = getPairs(list, sum).Select(Function(s) s.ToString())
    Console.WriteLine("Pairs are: {0}", String.Join(", " pairs))

    Console.ReadKey()
End Sub

1 Comment

Thank you for your answer and suggestions. HashSet seems to be solving my problem. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.