Microsoft MVP성태의 닷넷 이야기
.NET Framework: 581. C# - 순열(Permutation) 예제 코드 [링크 복사], [링크+제목 복사]
조회: 20436
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - 순열(Permutation) 예제 코드

조합이 나오면,

C# - 조합(Combination) 예제 코드
; https://www.sysnet.pe.kr/2/0/10954

빠지지 않는 것이 바로 순열입니다. 위의 조합 코드를 만든 James McCaffrey가 순열도 만들어 놓았기 때문에 그대로 사용해도 좋습니다. ^^

Using Permutations in .NET for Improved Systems Security
; http://delphi.ktop.com.tw/download/upload/41338_Using%20Permutations%20in%20.NET%20for%20Improved%20Systems%20Security.doc

namespace ConsoleApplication1
{
    class Permutation
    {
        private int[] data = null;
        private int order = 0;

        public Permutation(int n)
        {
            this.data = new int[n];
            for (int i = 0; i < n; ++i)
            {
                this.data[i] = i;
            }

            this.order = n;
        }

        public Permutation Successor()
        {
            if (this.order <= 1)
            {
                return null;
            }

            Permutation result = new Permutation(this.order);

            int left, right;
            for (int k = 0; k < result.order; ++k)  // Step #0 - copy current data into result
            {
                result.data[k] = this.data[k];
            }

            left = result.order - 2;  // Step #1 - Find left value 
            while ((result.data[left] > result.data[left + 1]) && (left >= 1))
            {
                --left;
            }

            if ((left == 0) && (this.data[left] > this.data[left + 1]))
            {
                return null;
            }

            right = result.order - 1;  // Step #2 - find right; first value > left
            while (result.data[left] > result.data[right])
            {
                --right;
            }

            int temp = result.data[left];  // Step #3 - swap [left] and [right]
            result.data[left] = result.data[right];
            result.data[right] = temp;


            int i = left + 1;              // Step #4 - order the tail
            int j = result.order - 1;

            while (i < j)
            {
                temp = result.data[i];
                result.data[i++] = result.data[j];
                result.data[j--] = temp;
            }

            return result;
        }

        internal static long Choose(int length)
        {
            long answer = 1;

            for (int i = 1; i <= length; i ++)
            {
                checked { answer = answer * i; }
            }

            return answer;
        }

        public string[] ApplyTo(string[] arr)
        {
            if (arr.Length != this.order)
            {
                return null;
            }

            string[] result = new string[arr.Length];
            for (int i = 0; i < result.Length; ++i)
            {
                result[i] = arr[this.data[i]];
            }

            return result;
        }

        public override string ToString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("( ");
            for (int i = 0; i < this.order; ++i)
            {
                sb.Append(this.data[i].ToString() + " ");
            }
            sb.Append(")");

            return sb.ToString();
        }

    }
}

같은 사람이 만들었기 때문에 사용법도 순열과 매우 흡사하게 구성됩니다.

string[] items = new string[] { "apple", "banana", "cherry" };

Permutation c = new Permutation(items.Length);

string[] snapshot = null;

while (c != null)
{
    snapshot = c.ApplyTo(items);
    DisplayItems(snapshot);

    c = c.Successor();
}

/*
출력 결과:

{ apple, banana, cherry }
{ apple, cherry, banana }
{ banana, apple, cherry }
{ banana, cherry, apple }
{ cherry, apple, banana }
{ cherry, banana, apple }
*/

또한, 제네릭과 IEnumerable 메서드를 추가 적용해 보면,

public class Permutation<TData> : IEnumerable<TData[]>
{
    private int[] data = null;
    private int order = 0;
    private TData[] elems;

    public Permutation(TData[] items)
    {
        this.order = items.Length;
        this.data = new int[this.order];
        this.elems = items;
        for (int i = 0; i < this.order; ++i)
        {
            this.data[i] = i;
        }
    }

    public Permutation<TData> Successor()
    {
        if (this.order <= 1)
        {
            return null;
        }

        Permutation<TData> result = new Permutation<TData>(this.elems);

        int left, right;
        for (int k = 0; k < result.order; ++k)  // Step #0 - copy current data into result
        {
            result.data[k] = this.data[k];
        }

        left = result.order - 2;  // Step #1 - Find left value 
        while ((result.data[left] > result.data[left + 1]) && (left >= 1))
        {
            --left;
        }

        if ((left == 0) && (this.data[left] > this.data[left + 1]))
        {
            return null;
        }

        right = result.order - 1;  // Step #2 - find right; first value > left
        while (result.data[left] > result.data[right])
        {
            --right;
        }

        int temp = result.data[left];  // Step #3 - swap [left] and [right]
        result.data[left] = result.data[right];
        result.data[right] = temp;

        int i = left + 1;              // Step #4 - order the tail
        int j = result.order - 1;

        while (i < j)
        {
            temp = result.data[i];
            result.data[i++] = result.data[j];
            result.data[j--] = temp;
        }

        return result;
    }

    internal static long Choose(int length)
    {
        long answer = 1;

        for (int i = 1; i <= length; i++)
        {
            checked { answer = answer * i; }
        }

        return answer;
    }

    public TData[] ApplyTo(TData[] arr)
    {
        if (arr.Length != this.order)
        {
            return null;
        }

        TData[] result = new TData[arr.Length];
        for (int i = 0; i < result.Length; ++i)
        {
            result[i] = arr[this.data[i]];
        }

        return result;
    }

    public override string ToString()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.Append("( ");
        for (int i = 0; i < this.order; ++i)
        {
            sb.Append(this.data[i].ToString() + " ");
        }
        sb.Append(")");

        return sb.ToString();
    }

    public IEnumerator<TData[]> GetEnumerator()
    {
        Permutation<TData> p = new Permutation<TData>(this.elems);
        TData[] snapshot = null;

        while (p != null)
        {
            snapshot = p.ApplyTo(this.elems);
            yield return snapshot;

            p = p.Successor();
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        Permutation<TData> p = new Permutation<TData>(this.elems);
        TData[] snapshot = null;

        while (p != null)
        {
            snapshot = p.ApplyTo(this.elems);
            yield return snapshot;

            p = p.Successor();
        }
    }
}

배열의 요소 타입에 상관없이 사용할 수 있습니다.

{
    string[] items = new string[] { "apple", "banana", "cherry" };
    Permutation<string> p = new Permutation<string>(items);

    foreach (var result in p)
    {
        PrintElems(result);
    }
}

{
    int[] items = new int[] { 1, 2, 3 };
    Permutation<int> p = new Permutation<int>(items);

    foreach (var result in p)
    {
        PrintElems(result);
    }
}

private static void PrintElems(T[] elems)
{
    Console.Write("{ ");

    foreach (var elem in elems)
    {
        Console.Write(elem + ", ");
    }

    Console.WriteLine("}");
}

/* 출력 결과
{ apple, banana, cherry, }
{ apple, cherry, banana, }
{ banana, apple, cherry, }
{ banana, cherry, apple, }
{ cherry, apple, banana, }
{ cherry, banana, apple, }
{ 1, 2, 3, }
{ 1, 3, 2, }
{ 2, 1, 3, }
{ 2, 3, 1, }
{ 3, 1, 2, }
{ 3, 2, 1, }
*/

첨부한 파일은, "Using Permutations in .NET for Improved Systems Security" 워드 파일과 이 글의 예제 코드입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 11/12/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12327정성태9/12/202010101.NET Framework: 938. C# - ICS(Internet Connection Sharing) 제어파일 다운로드1
12326정성태9/12/20209613개발 환경 구성: 516. Azure VM의 Network Adapter를 실수로 비활성화한 경우
12325정성태9/12/20209168개발 환경 구성: 515. OpenVPN - 재부팅 후 ICS(Internet Connection Sharing) 기능이 동작 안하는 문제
12324정성태9/11/202010419개발 환경 구성: 514. smigdeploy.exe를 이용한 Windows Server 2016에서 2019로 마이그레이션 방법
12323정성태9/11/20209336오류 유형: 649. Copy Database Wizard - The job failed. Check the event log on the destination server for details.
12322정성태9/11/202010277개발 환경 구성: 513. Azure VM의 RDP 접속 위치 제한 [1]
12321정성태9/11/20208662오류 유형: 648. netsh http add urlacl - Error: 183 Cannot create a file when that file already exists.
12320정성태9/11/20209853개발 환경 구성: 512. RDP(원격 데스크톱) 접속 시 비밀 번호를 한 번 더 입력해야 하는 경우
12319정성태9/10/20209613오류 유형: 647. smigdeploy.exe를 Windows Server 2016에서 실행할 때 .NET Framework 미설치 오류 발생
12318정성태9/9/20209111오류 유형: 646. OpenVPN - "TAP-Windows Adapter V9" 어댑터의 "Network cable unplugged" 현상
12317정성태9/9/202011395개발 환경 구성: 511. Beats용 Kibana 기본 대시 보드 구성 방법
12316정성태9/8/20209832디버깅 기술: 170. WinDbg Preview 버전부터 닷넷 코어 3.0 이후의 메모리 덤프에 대해 sos.dll 자동 로드
12315정성태9/7/202012127개발 환경 구성: 510. Logstash - FileBeat을 이용한 IIS 로그 처리 [2]
12314정성태9/7/202010524오류 유형: 645. IIS HTTPERR - Timer_MinBytesPerSecond, Timer_ConnectionIdle 로그
12313정성태9/6/202011827개발 환경 구성: 509. Logstash - 사용자 정의 grok 패턴 추가를 이용한 IIS 로그 처리
12312정성태9/5/202015785개발 환경 구성: 508. Logstash 기본 사용법 [2]
12311정성태9/4/202010970.NET Framework: 937. C# - 간단하게 만들어 보는 리눅스의 nc(netcat), json_pp 프로그램 [1]
12310정성태9/3/202010217오류 유형: 644. Windows could not start the Elasticsearch 7.9.0 (elasticsearch-service-x64) service on Local Computer.
12309정성태9/3/20209951개발 환경 구성: 507. Elasticsearch 6.6부터 기본 추가된 한글 형태소 분석기 노리(nori) 사용법
12308정성태9/2/202011214개발 환경 구성: 506. Windows - 단일 머신에서 단일 바이너리로 여러 개의 ElasticSearch 노드를 실행하는 방법
12307정성태9/2/202011987오류 유형: 643. curl - json_parse_exception / Invalid UTF-8 start byte
12306정성태9/1/202010137오류 유형: 642. SQL Server 시작 오류 - error code 10013
12305정성태9/1/202011053Windows: 172. "Administered port exclusions"이 아닌 포트 범위 항목을 삭제하는 방법
12304정성태8/31/202010016개발 환경 구성: 505. 윈도우 - (네트워크 어댑터의 우선순위로 인한) 열거되는 IP 주소 순서를 조정하는 방법
12303정성태8/30/202010159개발 환경 구성: 504. ETW - 닷넷 프레임워크 기반의 응용 프로그램을 위한 명령행 도구 etrace 소개
12302정성태8/30/202010097.NET Framework: 936. C# - ETW 관련 Win32 API 사용 예제 코드 (5) - Private Logger파일 다운로드1
... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...