Click here to Skip to main content
15,884,836 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was asked about this question in interview:
Integers in an array are unique and increasingly sorted. Write a function to find an integer from the array who equals to its index. E.g. in the array {-3, -1, 1, 3, 5}, the number 3 equals its index 3.

Any ideas?
Posted
Updated 28-Sep-15 17:58pm
v2
Comments
PIEBALDconsult 28-Sep-15 23:59pm    
Zero-based or one-based indices?
Every member of the array equals its index if you provide the right base.
CPallini 29-Sep-15 3:21am    
That's pretty trivial. What is your doubt about?

VB
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        
        Dim numbers = New Integer() {-3, -1, 1, 3, 5}


        MsgBox(Find_Index_Value_Same_As_Array_Value(numbers))



    End Sub

    Private Function Find_Index_Value_Same_As_Array_Value(ByVal _Array() As Integer) As Integer



        Find_Index_Value_Same_As_Array_Value = -1




        '--- Find The Max Number For The Array Index

        Dim _Max As Integer = UBound(_Array)

        Dim _My_Counter As Integer = 0

        For _My_Counter = 0 To _Max
            If _My_Counter = _Array(_My_Counter) Then
                Find_Index_Value_Same_As_Array_Value = _Array(_My_Counter)
                Exit Function
            End If
        Next

        

    End Function
 
Share this answer
 
v2
C#
int[] numbers = { -3, -1, 1, 3, 5 };

int[] results = numbers.Where((nbr, i) => i == nbr).ToArray();
string message = results.Length == 0
? "Nothing found"
: string.Format("Found {0}. First is at index {1}", results.Length, results[0]);
          Console.WriteLine(message);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900