News for hackers. Stuff that matters.
Re:Array Iteration Interview Problem by ten_fingers on Wednesday August 01, 2012 @10:35PM (#4326916)
Here is a solution in Microsoft's Visual Basic .NET making a little use of some of .NET:

     ' ADD.VB --
     '
     ' Created at 21:34:59 on Wednesday, August 1st, 2012.

     '    Note:  There are some risks of fixed overflow
     '    depending on (1) the values of the components
     '    of arr() and (2) how the logic works for ending
     '    a For-Next loop in the case n is the largest
     '    value of Int32.

       Sub add( _
         arr() As Int32, _
         val As Int32, _
         n As Int32 )

       Dim arr_upper_bound As Int32

       Dim i As Int32

       Dim n_changes As Int32

     '    http://msdn.microsoft.com/en-us/library/system.array.getupperbound%28v=vs.100%29.aspx#Y104

       arr_upper_bound = arr.GetUpperBound( 0 )

     '    http://msdn.microsoft.com/en-us/library/cy37t14y(VS.80).aspx

       Select n

         Case n = 0

           For i = 0 To arr_upper_bound

             If arr( i ) = val Then arr( i ) = arr( i ) + 1

           Next i

         Case n > 0

           n_changes = 0

           For i = 0 To arr_upper_bound

             If arr( i ) = val Then

               arr( i ) = arr( i ) + 1

               n_changes = n_changes + 1

               If n_changes = n Then Exit Select

             End If

           Next i

         Case n < 0

           n_changes = 0

           For i = arr_upper_bound To 0 Step -1

             If arr( i ) = val Then

               arr( i ) = arr( i ) + 1

               n_changes = n_changes + 1

               If n_changes = -n Then Exit Select

             End If

           Next i

       End Select

       Return

       End Sub

There are no comments on this comment yet.