Programing

C # 배열에서 중복을 어떻게 제거합니까?

lottogame 2020. 5. 8. 08:14
반응형

C # 배열에서 중복을 어떻게 제거합니까?


string[]함수 호출에서 반환되는 C # 배열 로 작업하고 있습니다. Generic컬렉션에 캐스팅 할 수 는 있었지만 temp 배열을 사용하여 더 좋은 방법이 있는지 궁금했습니다.

C # 배열에서 중복을 제거하는 가장 좋은 방법은 무엇입니까?


LINQ 쿼리를 사용하여 다음을 수행 할 수 있습니다.

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

HashSet <string> 접근 방식 은 다음과 같습니다 .

public static string[] RemoveDuplicates(string[] s)
{
    HashSet<string> set = new HashSet<string>(s);
    string[] result = new string[set.Count];
    set.CopyTo(result);
    return result;
}

불행히도이 솔루션에는 해당 버전까지 HashSet이 추가되지 않았으므로 .NET Framework 3.5 이상이 필요합니다. LINQ의 기능인 array.Distinct ()를 사용할 수도 있습니다 .


정렬해야 할 경우 중복을 제거하는 정렬을 구현할 수 있습니다.

그런 다음 하나의 돌로 두 마리의 새를 죽입니다.


다음 테스트 및 작동 코드는 배열에서 중복을 제거합니다. System.Collections 네임 스페이스를 포함해야합니다.

string[] sArray = {"a", "b", "b", "c", "c", "d", "e", "f", "f"};
var sList = new ArrayList();

for (int i = 0; i < sArray.Length; i++) {
    if (sList.Contains(sArray[i]) == false) {
        sList.Add(sArray[i]);
    }
}

var sNew = sList.ToArray();

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

원한다면 이것을 함수로 묶을 수 있습니다.


이것은 솔루션을 얼마나 엔지니어링하고 싶은가에 달려 있습니다. 배열이 그렇게 크지 않고 목록 정렬에 신경 쓰지 않는다면 다음과 비슷한 것을 시도해보십시오.

    public string[] RemoveDuplicates(string[] myList) {
        System.Collections.ArrayList newList = new System.Collections.ArrayList();

        foreach (string str in myList)
            if (!newList.Contains(str))
                newList.Add(str);
        return (string[])newList.ToArray(typeof(string));
    }

- 매번 인터뷰 질문 입니다. 이제 코딩을 완료했습니다.

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();
        }

List<String> myStringList = new List<string>();
foreach (string s in myStringArray)
{
    if (!myStringList.Contains(s))
    {
        myStringList.Add(s);
    }
}

이것은 O (n ^ 2) 이며, 콤보에 채워질 짧은 목록은 중요하지 않지만 큰 컬렉션에서 빠르게 문제가 될 수 있습니다.


protected void Page_Load(object sender, EventArgs e)
{
    string a = "a;b;c;d;e;v";
    string[] b = a.Split(';');
    string[] c = b.Distinct().ToArray();

    if (b.Length != c.Length)
    {
        for (int i = 0; i < b.Length; i++)
        {
            try
            {
                if (b[i].ToString() != c[i].ToString())
                {
                    Response.Write("Found duplicate " + b[i].ToString());
                    return;
                }
            }
            catch (Exception ex)
            {
                Response.Write("Found duplicate " + b[i].ToString());
                return;
            }
        }              
    }
    else
    {
        Response.Write("No duplicate ");
    }
}

다음은 O (1) 공간 을 사용 하는 O (n * n) 방식입니다 .

void removeDuplicates(char* strIn)
{
    int numDups = 0, prevIndex = 0;
    if(NULL != strIn && *strIn != '\0')
    {
        int len = strlen(strIn);
        for(int i = 0; i < len; i++)
        {
            bool foundDup = false;
            for(int j = 0; j < i; j++)
            {
                if(strIn[j] == strIn[i])
                {
                    foundDup = true;
                    numDups++;
                    break;
                }
            }

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

        strIn[len-numDups] = '\0';
    }
}

위의 해시 / 링크 접근 방식은 일반적으로 실제 생활에서 사용하는 방법입니다. 그러나 인터뷰에서 그들은 일반적으로 해시를 배제하는 일정한 공간 또는 LINQ 를 사용하여 배제하는 내부 API가 없는 일정한 공간을두기를 원합니다 .


모든 문자열을 사전에 추가하고 나중에 Keys 속성을 가져옵니다. 이렇게하면 각각의 고유 한 문자열이 생성되지만 원래 입력과 동일한 순서는 아닙니다.

최종 결과가 원래 입력과 동일한 순서를 갖도록 요구하는 경우 각 문자열의 첫 번째 발생을 고려할 때 다음 알고리즘을 대신 사용하십시오.

  1. 목록 (최종 출력)과 사전 (중복 확인)을 갖습니다.
  2. 입력의 각 문자열에 대해 사전에 이미 존재하는지 확인하십시오.
  3. 그렇지 않은 경우 사전과 목록 모두에 추가하십시오.

마지막에는 목록에 각 고유 문자열의 첫 항목이 포함됩니다.

사전을 구성 할 때 문화와 같은 것을 고려하여 악센트 문자가있는 복제본을 올바르게 처리하십시오.


다음 코드는 이것이 최적의 솔루션이 아니지만 ArrayList에서 중복을 제거하려고 시도합니다. 인터뷰 중에 재귀를 통해 중복 항목을 제거하고 두 번째 / 임시 배열 목록을 사용하지 않고이 질문을 받았습니다.

private void RemoveDuplicate() 
{

ArrayList dataArray = new ArrayList(5);

            dataArray.Add("1");
            dataArray.Add("1");
            dataArray.Add("6");
            dataArray.Add("6");
            dataArray.Add("6");
            dataArray.Add("3");
            dataArray.Add("6");
            dataArray.Add("4");
            dataArray.Add("5");
            dataArray.Add("4");
            dataArray.Add("1");

            dataArray.Sort();

            GetDistinctArrayList(dataArray, 0);
}

private void GetDistinctArrayList(ArrayList arr, int idx)

{

            int count = 0;

            if (idx >= arr.Count) return;

            string val = arr[idx].ToString();
            foreach (String s in arr)
            {
                if (s.Equals(arr[idx]))
                {
                    count++;
                }
            }

            if (count > 1)
            {
                arr.Remove(val);
                GetDistinctArrayList(arr, idx);
            }
            else
            {
                idx += 1;
                GetDistinctArrayList(arr, idx);
            }
        }

간단한 해결책 :

using System.Linq;
...

public static int[] Distinct(int[] handles)
{
    return handles.ToList().Distinct().ToArray();
}

중복 요소를 저장하지 않고 중복 추가 요청을 자동으로 무시하는 해시 세트 일 수 있습니다.

static void Main()
{
    string textWithDuplicates = "aaabbcccggg";     

    Console.WriteLine(textWithDuplicates.Count());  
    var letters = new HashSet<char>(textWithDuplicates);
    Console.WriteLine(letters.Count());

    foreach (char c in letters) Console.Write(c);
    Console.WriteLine("");

    int[] array = new int[] { 12, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 };

    Console.WriteLine(array.Count());
    var distinctArray = new HashSet<int>(array);
    Console.WriteLine(distinctArray.Count());

    foreach (int i in distinctArray) Console.Write(i + ",");
}

참고 : 테스트되지 않았습니다!

string[] test(string[] myStringArray)
{
    List<String> myStringList = new List<string>();
    foreach (string s in myStringArray)
    {
        if (!myStringList.Contains(s))
        {
            myStringList.Add(s);
        }
    }
    return myStringList.ToString();
}

필요한 것을 할 수 있습니다 ...

편집 아아! 1 분도 안되는 시간에 강탈당했습니다!


아래를 테스트하고 작동합니다. 멋진 점은 문화에 민감한 검색도한다는 것입니다.

class RemoveDuplicatesInString
{
    public static String RemoveDups(String origString)
    {
        String outString = null;
        int readIndex = 0;
        CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;


        if(String.IsNullOrEmpty(origString))
        {
            return outString;
        }

        foreach (var ch in origString)
        {
            if (readIndex == 0)
            {
                outString = String.Concat(ch);
                readIndex++;
                continue;
            }

            if (ci.IndexOf(origString, ch.ToString().ToLower(), 0, readIndex) == -1)
            {
                //Unique char as this char wasn't found earlier.
                outString = String.Concat(outString, ch);                   
            }

            readIndex++;

        }


        return outString;
    }


    static void Main(string[] args)
    {
        String inputString = "aAbcefc";
        String outputString;

        outputString = RemoveDups(inputString);

        Console.WriteLine(outputString);
    }

}

--AptSenSDET


이 코드는 배열에서 중복 값을 100 % 제거합니다. [[[]]]를 사용했습니다. ..... 어떤 OO 언어로든 변환 할 수 있습니다.

for(int i=0;i<size;i++)
{
    for(int j=i+1;j<size;j++)
    {
        if(a[i] == a[j])
        {
            for(int k=j;k<size;k++)
            {
                 a[k]=a[k+1];
            }
            j--;
            size--;
        }
    }

}

일반 확장 방법 :

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    HashSet<TSource> set = new HashSet<TSource>(comparer);
    foreach (TSource item in source)
    {
        if (set.Add(item))
        {
            yield return item;
        }
    }
}

ArrayList로 작업 할 때이 코드를 사용할 수 있습니다

ArrayList arrayList;
//Add some Members :)
arrayList.Add("ali");
arrayList.Add("hadi");
arrayList.Add("ali");

//Remove duplicates from array
  for (int i = 0; i < arrayList.Count; i++)
    {
       for (int j = i + 1; j < arrayList.Count ; j++)
           if (arrayList[i].ToString() == arrayList[j].ToString())
                 arrayList.Remove(arrayList[j]);

public static int RemoveDuplicates(ref int[] array)
{
    int size = array.Length;

    // if 0 or 1, return 0 or 1:
    if (size  < 2) {
        return size;
    }

    int current = 0;
    for (int candidate = 1; candidate < size; ++candidate) {
        if (array[current] != array[candidate]) {
            array[++current] = array[candidate];
        }
    }

    // index to count conversion:
    return ++current;
}

아래는 자바의 간단한 논리이며 배열의 요소를 두 번 순회하고 동일한 요소가 0을 할당하면 비교하는 요소의 색인을 건드리지 않습니다.

import java.util.*;
class removeDuplicate{
int [] y ;

public removeDuplicate(int[] array){
    y=array;

    for(int b=0;b<y.length;b++){
        int temp = y[b];
        for(int v=0;v<y.length;v++){
            if( b!=v && temp==y[v]){
                y[v]=0;
            }
        }
    }
}

  private static string[] distinct(string[] inputArray)
        {
            bool alreadyExists;
            string[] outputArray = new string[] {};

            for (int i = 0; i < inputArray.Length; i++)
            {
                alreadyExists = false;
                for (int j = 0; j < outputArray.Length; j++)
                {
                    if (inputArray[i] == outputArray[j])
                        alreadyExists = true;
                }
                        if (alreadyExists==false)
                        {
                            Array.Resize<string>(ref outputArray, outputArray.Length + 1);
                            outputArray[outputArray.Length-1] = inputArray[i];
                        }
            }
            return outputArray;
        }

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


namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
             List<int> listofint1 = new List<int> { 4, 8, 4, 1, 1, 4, 8 };
           List<int> updatedlist= removeduplicate(listofint1);
            foreach(int num in updatedlist)
               Console.WriteLine(num);
        }


        public static List<int> removeduplicate(List<int> listofint)
         {
             List<int> listofintwithoutduplicate= new List<int>();


              foreach(var num in listofint)
                 {
                  if(!listofintwithoutduplicate.Any(p=>p==num))
                        {
                          listofintwithoutduplicate.Add(num);
                        }
                  }
             return listofintwithoutduplicate;
         }
    }



}

strINvalues = "1,1,2,2,3,3,4,4";
strINvalues = string.Join(",", strINvalues .Split(',').Distinct().ToArray());
Debug.Writeline(strINvalues);

Kkk 이것이 마법인지 아니면 아름다운 코드인지 확실하지 않습니다.

참고 URL : https://stackoverflow.com/questions/9673/how-do-i-remove-duplicates-from-ac-sharp-array

반응형