-1

I am looking to write a simple and easy method that will allow me to find a pair of duplicates in an array and display the index number of which the pair would exist.

So far I only have the Method Header to work with and an example of output

int Duplicates (int[] testArray){

int[] testArray = {1,5,6,8,9,4,4,6,3,2};
}

the only thing I would like to be returned is the index location of the adjacent pair, i.e 5 in this case which would be (4,4). If there are no adjacent pairs I would also like to be able to print "no duplicate pairs found"

can anyone help me get started as I have no idea how one would even start to work on something like this.

1
  • 8
    Are you familiar with the concept of for/while loops? Did you try to use one of them? Can you show what is your initial approach and explain how it failed? If you give more details on these in your question, you are likely to get answers more specially suited for you
    – amit
    Dec 30, 2012 at 15:39

4 Answers 4

3

Try following Linq query Demo here

int[] testArray = {1,5,6,8,9,4,4,6,3,2};

var adjacentDuplicate = testArray
    .Skip(1)
    .Where((value,index) => value == testArray[index])
    .Distinct();

if (adjacentDuplicate.Any() )
{    
    // Print adjacentDuplicate
}
else
{
   // No duplicates found.
}

EDIT

Following is the LINQ query for index of duplicates.

var adjacentIndex = testArray
    .Skip(1)
    .Select((value,index) => value == testArray[index] ? index : -1)
    .Where (x=> x!= -1);
10
  • 2
    Surely, value == testArray[index] will always be true. Dec 30, 2012 at 15:51
  • No, index is shifted by 1 due to Skip(1) statement. See here
    – Tilak
    Dec 30, 2012 at 15:53
  • @AshBurlaczenko It seems you miss the Skip(1) part.
    – L.B
    Dec 30, 2012 at 15:54
  • To be fair, the question asked for the index of the pair, not the pair itself. Dec 30, 2012 at 16:00
  • @IchabodClay, I missed it first. Updated the answer for index also.
    – Tilak
    Dec 30, 2012 at 16:06
1

The only drawback I can think of in this LINQ query is that it uses -1 as a discarded value. In case of indexes it's always true, but I usually wouldn't recommend doing it. What it does is check if the next element of the array is the same of the current one, return the current index if true, -1 otherwise, then select only the indexes greater than zero.

int[] testArray = {1, 5, 6, 8, 9, 4, 4, 6, 3, 2, 2};
var duplicateIndexes = testArray.
            Select((value, index) => testArray.Length > index + 1 &&
                                     testArray[index + 1] == value ? index : -1).
            Where(index => index > 0).
            ToArray();
1
  • Eve,your syntax are very much smart syntax.Thank you for the syntax.remove testArray.Length > index + 1 portion from the above syntax show me error Index was outside the bounds of the array.why this happen?
    – shamim
    Nov 17, 2014 at 15:15
0

Its quite simple when you break the problem down, you have to look at each element, then compare it to the next. The only major gotcha is that you will run out of array if you compare the index of the last element to the index + 1, this will cause an array out of bounds exception, this is why we check our position

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Misc
{
    class Program
    {
        static int duplicates(int[] array)
        {
            for (int i = 0; i < array.Length-1; i++)
            {
                if (array[i] == array[i+1])
                {
                    return i;
                }
            }
            return -1;
        }

        static void Main(string[] args)
        {
            int[] testArray = { 1, 5, 6, 8, 9, 4, 4, 6, 3, 2 };
            Console.WriteLine(duplicates(testArray));
            Console.ReadKey(); // block 
        }
    }
}
5
  • 2
    Why the if (i == array.Length) continue;? The code wont even hit that point. Dec 30, 2012 at 15:46
  • Its easier to grok this way. Dec 30, 2012 at 15:47
  • Also note: 0 will be returned for two cases: (1) no dupe [0,1,2]. (2): dupe in first element [0,0,1]
    – amit
    Dec 30, 2012 at 15:47
  • { 1, 5, 6, 8, 9, 4, 2, 6, 3, 2 }; Would throw exception IndexOutOfRange
    – L.B
    Dec 30, 2012 at 15:49
  • This will return only the index of the first duplicate! Change the return type of the method to IEnumerable<int>, use yield return i; within the loop and drop the final return -1;. Dec 30, 2012 at 16:22
-1
int previousValue = -1; //set it to something you're not expecting

for (int i=0; i <testArray.Count; i++) {
    int currentValue = testArray[i];

    if (currentValue.equals(previousValue) {
      //we have a duplicate
       duplicateList.add(i); //for the position of the duplicate
    }
    previousValue = currentValue;
}

if (duplicateList.Count == 0) {
   //no duplicates found
} else {
   return duplicateList.toArray();
}

Explanation - we're going to go through this by going through them one at a time.

The for loop will increment the value i by one each time until it goes through the whole of the array.

At each step, the current value will checked with the previous value. If they are the same, this position is added to the output. Then the previous value becomes the last current value, and the loop continues.

5
  • 2
    -1. Code without any attempt to explain how to approach it - to someone who seems to be lacking the understanding of what a for loop is. I'll remove the -1 if you add textual explanation on your solution. Your code also lacks indentation.
    – amit
    Dec 30, 2012 at 15:42
  • Added the explanation at the end, will fix the intends.
    – Haedrian
    Dec 30, 2012 at 15:44
  • @Haedrian, you shouldn't give answers to question where the OP hasn't even attempted to solve it themself. Dec 30, 2012 at 15:45
  • That's better (though it can be done by a simpler code, but that's a matter of opinion). I removed by -1.
    – amit
    Dec 30, 2012 at 15:46
  • Why are you storing the previous value? Start looping at index 1 and test for duplicates with testArray[i] == testArray[i-1]. Dec 30, 2012 at 16:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.