Slasher
Slasher

Reputation: 618

Finding the last repetition index of element in array

How do you retrieve the last repetition index of element in array in C#?

For example you have: int[] array = { 3, 5, 7, 8, 3, 4, 3 , 9 };

And you are searching for element 3 where index of last repetition is 6.

This is what i have for finding first repetition:

public static int Search(int[] array, int value)
{
    for (int i = 0; i < array.Length; i++)
    {
        if (value == array[i])
        {
            return i;
        }
    }
    return -1;
}

PS: I can't use any functions or methods. I'm allowed to use only arrays.

Upvotes: 0

Views: 115

Answers (3)

muhihsan
muhihsan

Reputation: 2350

Try to search from behind. If you search from the first element of the array, you'll definitely need to search until the end of the array. If you search from behind, you can return the value directly once you find it.

public static int search(int lem, int[] a)
{
    for (int i = a.Length - 1; i >= 0; i--) 
    {
        if (lem == a[i])
        {
            return i;
        }
    }
     return -1; 
}

Upvotes: 4

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186748

Your question is vague one. If you're looking for any duplicate (not necessary 3) I suggest using HashSet<int> (C# implementation):

int[] array = { 3, 5, 7, 8, 3, 4, 3, 9 };

HashSet<int> used = new HashSet<int>();

int last = -1;

for (int i = 0; i < array.Length; ++i)
  if (!used.Add(array[i])) // failed to add to the set, array[i] is a duplicate
    last = i;

Console.Write(last); 

In case you're looking just for the last ocurrence of 3, try looping backward:

   int last = -1;

   for (int i = array.Length - 1; i >= 0; --i)
     if (array[i] == 3) {
       last = i;

       break;
     } 

Upvotes: 1

Dmitry Pavlushin
Dmitry Pavlushin

Reputation: 612

If you know how to find first repetition, why don't you use array.Reverse(), use the known algorythm, and then subtract found value form array.Length?

But if you want just a single method call, you can modify your solution, to not return the value until it finishes looping through an array:

public static int search(int lem, int[] a)
{
    int j = -1;
    for (int i = 0; i < a.Length; i++) 
    {
        if (lem == a[i])
        {
            j = i;
        }
    }
    return j; 
}

Upvotes: 0

Related Questions