9

I have written some code to remove duplicates from Integer Array. I dont want to use any inbuilt keywords/property.

Here is my logic :

int[] iArray = {1,2,3,2,3,4,3};              
int t = 0;
int arraysize = iArray.Length;
for (int m = 0; m < arraysize; m++)
{
    if (iArray[m] != iArray[t])
    {
        t++;
        iArray[t] = iArray[m];
    }
}
arraysize = t + 1;
for (int m = 0; m < arraysize; m++)
{
    Console.WriteLine(iArray[m]);
}

Output should be:

1,2,3,4

It does not give the desired output. Guys, this is not the homewok. This is Self Learning. No LINQ,Contains keyword please. Thank you for you replies.

Thanks.

Tim
  • 35,413
  • 11
  • 95
  • 121
Bokambo
  • 4,204
  • 27
  • 79
  • 130

15 Answers15

6

Since this is a homework, I would not fix your code, and give you a few notes instead:

  1. You would not be able to do it with a single loop and no built-in functions; you need two nested loops
  2. When you find a duplicate value, move the array items forward by one, and decrease the size of the "active area" of the array; you need another nested loop to do the move.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • so many people replied on this post with lots of code but i have not seen it. I liked your explanation and tried myself but still some problems. – Bokambo Aug 22 '12 at 16:27
  • int[] iArray = { 1,2,5,6,4,1,2,5,4,1,3}; int iArraySize = iArray.Length; for (int i = 0; i < iArraySize; i++) { for (int j = 1; j < iArraySize; i++) { if (iArray[j] == iArray[i]) { iArray[j] = iArray[j + 1]; iArraySize--; } else Console.WriteLine(iArray[j]); } } } – Bokambo Aug 22 '12 at 16:28
  • @user662285 Your code uses `i++` in the nested loop instead of `j++`. The code will fail when `j` is pointing at the last element because of `iArray[j + 1]`. Finally, when you do the `iArray[j] = iArray[j + 1]` override, you should decrease `j` back, otherwise you wouldn't eliminate runs of 3+ elements (as in `{1,2,2,2,3}`). – Sergey Kalinichenko Aug 22 '12 at 16:36
  • I tried your approach but still not working.I tried below thing and it worked: – Bokambo Aug 23 '12 at 04:37
  • int numDups = 0, prevIndex = 0; int iArraySize = iArray.Length; for (int i = 0; i < iArraySize; i++) { bool foundDup = false; for (int j = 0; j < i; j++) { if (iArray[j] == iArray[i]) { foundDup = true; numDups++; break; } } if (foundDup == false) { Console.WriteLine(iArray[i]); iArray[prevIndex] = iArray[i]; prevIndex++; } } – Bokambo Aug 23 '12 at 04:38
  • @user662285 It is great that you got it working! Your approach combines the two items (the nested loop and a move by one) in a single outer loop, which is quite nice. – Sergey Kalinichenko Aug 23 '12 at 04:57
3

Here's a way to do it with two nested foreach-loops:

var array = new int[] {1,2,3,2,3,4,3};  

var result = new List<int>();
foreach(var item in array)
{
    bool found = false;
    foreach(var resultItem in result)
    {
        if(resultItem == item) found = true;
    }

    if(!found)
    {
        result.Add(item);
    }
}

If you don't want to use List<int>, you need to create a temporary array with the size of the first array. Then when that has processed, you need to keep track on how many items you really found and copy those over to a new array.

Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183
2

The problem is that you are only comparing each element to the previous one. Since this is a self-learning exercise, I'm only going to give an outline of how to do it and let you work out the details.

You need two nested loops:

  • The first loop iterates over each element.
  • The second loop compares the current element to all the others you have seen so far.

Note that this requires O(n2) time.


You can do it faster using other approaches:

  • Sorting the input first: O(n log(n)) time
  • Using a HashSet or Enumerable.Distinct: O(n) time.

But these latter approaches are probably both disallowed by your requirements of not using built-in classes/methods.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

A very basic form of an algorithm accomplishing what you want:

        int[] iArray = {1,2,3,2,3,4,3};
        int[] newArray = new int[iArray.Length];          

        //initialize array with a marker
        for(int i = 0; i < newArray.length; i++){
          newArray = -1 //this shouldn't be a potential value in the original arr
        }

        bool contains = false;
        int curLength = 0;
        for (int m = 0; m < iArrayLength; m++)
        {
           contains = false;
           for(int k = 0; k < curLength; k++){
                 if(newArray[k] == iArray[m]){
                    contains = true;
                    break;
                 }
           }
           if(!contains) 
                 newArray[curLength++] = iArray[m];
        }
        for (int m = 0; m < curLength; m++)
        {
            Console.WriteLine(newArray[m]);
        }
Razvan
  • 9,925
  • 6
  • 38
  • 51
  • -1. It doesn't work (check your `contains` variable) and he never requested the data in a new array. Your overcomplicating a solution that is not even optimal (O(n^2)). – riwalk Aug 22 '12 at 13:05
  • And I'll cancel mine once you make the fix :) – riwalk Aug 22 '12 at 13:17
0

Ok, you said you don't want anything built in, so lets do everything from scratch.

There are two ways (I know of) to do this. One has complexity O(n^2) and one has complexity O(n + n*log(n)). The second is faster, but the first is easier.

The slower (but easier) solution: O(n^2)

int[] iArray = {1,2,3,2,3,4,3};
List<int> unique = new List<int>(iArray.Length);

for(int i = 0; i<iArray.length; i++)
{
    bool found = false;
    for(int prev=0; prev<i; prev++)
    {
        if(iArray[prev] == iArray[i])
        {
            found = true;
            break;
        }
    }

    if(!found)
    {
        unique.Add(iArray[i]);
    }
}

iArray = unique.ToArray();

for(int i=0; i<iArray.Length; i++)
{
    Console.WriteLine(iArray[i]);
}

The faster (but more complicated) solution: O(n + n*log(n))

int[] iArray = {1,2,3,2,3,4,3};
List<int> unique = new List<int>(iArray.Length);

// Sort the array here. Use your favorite algorithm. Sorting is so widely
// covered elsewhere that I will avoid typing it here. Complexity should 
// be O(n*log(n))

if( iArray.Length > 0)
{
    unique.Add(iArray[0]);
}

for(int i=1; i<iArray.length; i++)
{
    if(iArray[i] != iArray[i-1])
    {
        unique.Add(iArray[i]);
    }
}

iArray = unique.ToArray();

for(int i=0; i<iArray.Length; i++)
{
    Console.WriteLine(iArray[i]);
}
riwalk
  • 14,033
  • 6
  • 51
  • 68
  • Your second solution doesn't remove the duplicates from the array. It just doesn't print them. I would downvote this one again. – Razvan Aug 22 '12 at 13:14
  • @Razvan, you're technically right. He wasn't altering the array in his code (thus why I just printed it out), but his first sentence clearly states that he wants to remove the values from the array. Update the code. – riwalk Aug 22 '12 at 13:27
0

Just fill the Dictionary and use Keys as a result array.

Dictionary<int, int> dict = new Dictionary<int, int>();
for(int i = 0; i < array.Length; i++) {
  dict[array[i]] = 0;
}

dict.Keys - RESULT.

PaulSh
  • 24
  • 2
0

This is the solution:

int[] iArray = { 1, 2, 3, 2, 3, 4, 3 };
int[] EachWords = { 1, 2, 3, 2, 3, 4, 3 };

for (int p = 0; p < EachWords.Length; p++)
{
    for (int j = 0; j < EachWords.Length; j++)
    {
        if (EachWords[p] == EachWords[j] && p != j)
        {
            List<int> tmp = new List<int>(EachWords);
            tmp.RemoveAt(j);
            EachWords = tmp.ToArray();
        }
    }
}

for (int j = 0; j < EachWords.Length; j++)
{
    Response.Write(EachWords[j].ToString() + "\n");
}

Now, It will display 1, 2, 3, 4

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
0

if u order items first, and after just compare with next, u'll have nlogn cost.

Algorithm:

  1. order array

  2. foreach elem if(has_next && next is equal) remove element; next

  3. print array

If space cost isnt a problem u can us auxiliar hashtable struct. But i keep thinking my idea is more simple.

Marc
  • 129
  • 1
  • 12
0

You can also use Dictionary which will be faster than the arrayList

    public Dictionary<string,int> removeDupUsingDictionary(int[] n)
    {

        Dictionary<string,int> numbers = new Dictionary<string,int>();

        for( int i = 0 ; i< n.Length; i ++)
        {
            try
            {
                numbers.Add("value" + n[i], n[i]);
            }
            catch (Exception e)
            {
                Console.WriteLine("Already the value" + n[i] + "present in the dictionary");
            }


        }

        return numbers;

    }



    static void Main(string[] args)
    {

        Program num = new Program();
        int[] n = { 6,5,1, 2, 3, 4, 5, 5, 6,6,6,6,6,6 };

        Dictionary<string, int> dictionary = new Dictionary<string, int>();

        int size = n.Length;


        ArrayList actual = num.removeDup(n);

        num.removeDupUsingDictionary(n);



    }
  • Interesting idea, but Exception handling should not be used in situations like this. Instead you should use `.ContainsKey()` or just set the value with the indexer `numbers["value" + n[i]] = n[i]` – psubsee2003 Sep 28 '12 at 09:33
0
static void Main(string[] args)
        {
            int[] array = new int[] { 4, 8, 4, 1, 1, 4, 8 };            
            int numDups = 0, prevIndex = 0;

            for (int i = 0; i < array.Length; i++)
            {
                bool foundDup = false;
                for (int j = 0; j < i; j++)
                {
                    if (array[i] == array[j])
                    {
                        foundDup = true;
                        numDups++; // Increment means Count for Duplicate found in array.
                        break;
                    }                    
                }

                if (foundDup == false)
                {
                    array[prevIndex] = array[i];
                    prevIndex++;
                }
            }

            // Just Duplicate records replce by zero.
            for (int k = 1; k <= numDups; k++)
            {               
                array[array.Length - k] = '\0';             
            }


            Console.WriteLine("Console program for Remove duplicates from array.");
            Console.Read();
        }
Muhammad Mubashir
  • 1,591
  • 1
  • 21
  • 18
0
int[] iArray = { 1, 2, 3, 2, 3, 4, 3 };

        List<int> unique = new List<int>(iArray.Length);                      

        for (int i = 0; i < iArray.Length; i++)
        {
            int count=0;
            for (int j = i + 1; j < iArray.Length; j++)
            {
                if (iArray[i] == iArray[j])
                {
                    count++;
                }
            }
            if (count==0)
            {
                unique.Add(iArray[i]);
            }
        }

        iArray = unique.ToArray();

        for (int i = 0; i < iArray.Length; i++)
        {
            Console.WriteLine(iArray[i]);
        }
Baby Groot
  • 4,637
  • 39
  • 52
  • 71
  • 1
    It would be extraordinarily helpful if you explained the code in your answer; as is, this isn't particularly useful. –  Jul 31 '13 at 06:36
0

You can use .Distinct() Extension Method as follows,


        int[] oldArray = { 1, 2, 3, 3, 4};
    int[] newArray  = oldArray .Distinct().ToArray();

Jatin patil
  • 4,252
  • 1
  • 18
  • 27
0

Your ans is :

    int[] oldArray = {1, 2, 3, 2, 3, 4, 3 };
    int[] newArray = oldArray.Distinct().ToArray();

    String ans = "";
    for (int m = 0; m < newArray.Length; m++)
    {
        ans += newArray[m] +",";
    }
    Console.WriteLine(ans);
Janki
  • 481
  • 2
  • 10
0

This Code is in Python.

array1 = [1,2,2,3,3,3,4,5,6,4,4,5,5,5,5,10,10,8,7,7,9,10]

array1.sort() # sorting is must
print(array1)

current = NONE
count = 0 

# overwriting the numbers at the frontal part of the array
for item in array1:
    if item != current:
        array1[count] = item
        count +=1
        current=item
        
       

print(array1)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10, 10]

print(array1[:count])#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The most Efficient method is :

array1 = [1,2,2,3,3,3,4,5,6,4,4,5,5,5,5,10,10,8,7,7,9,10]

array1.sort()
print(array1)

print([*dict.fromkeys(array1)])#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#OR#
aa = list(dict.fromkeys(array1))
print( aa)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Soudipta Dutta
  • 1,353
  • 1
  • 12
  • 7
-1

This solution is in javascript.

var myval = [1, 2,3, 4, 4, 5, 5, 6, 7];

var tempVal = [];
var l = myval.length;
for(var i=0; i<l; i++){
    if(tempVal.length === 0){
        tempVal.push(myval[i]);
    }
    else{
        var tempL = tempVal.length;
        var foundCount = 0;
        var lookedFor = myval[i];
        for(var t = 0; t<tempL; t++){
            if(tempVal[t] === lookedFor){
                foundCount++;
            }

        }
        if(foundCount === 0){
            tempVal.push(lookedFor);
        }
    }
}       
  • This won't do the original poster much good. Learning the first language is difficult enough, i guess. – scones Feb 10 '13 at 14:39