Microsoft MVP성태의 닷넷 이야기
.NET Framework: 564. C# - DGML로 바이너리 트리 출력하는 방법 [링크 복사], [링크+제목 복사]
조회: 15403
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C# - DGML로 바이너리 트리 출력하는 방법

지난번 글에서 2진 트리를 화면으로 출력하는 방법에 대해 알아봤는데요.

디버깅 용도로 이진 트리의 내용을 출력하는 방법
; https://www.sysnet.pe.kr/2/0/10922

아쉬운 것이 DGML로 출력했을 때의 그래프가 별로라는 점입니다. 그러니까,,, 대충 다음과 같은 식으로 나오는데요.

dgml_bintree_1.png

다행히 DGML에 Bounds라는 속성을 통해 위치 지정을 할 수 있게 되어 있습니다. 그래서, 소스 코드를 다음과 같이 수정해 주었고,

using System;
using System.IO;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        {
            ContainerOnTree ct = new ContainerOnTree();

            ct.Add(30);
            ct.Add(20);
            ct.Add(40);
            ct.Add(10);
            ct.Add(25);
            ct.Add(23);
            ct.Add(35);
            ct.Add(32);
            ct.Add(37);
            ct.Add(50);
            ct.Add(58);
            ct.Add(5);
            ct.Add(3);
            ct.Add(7);
            ct.Add(15);
            ct.Add(28);
            ct.Add(41);

            File.WriteAllText("test.dgml", ct.ToDGML());
        }
    }
}

public class ContainerOnTree
{
    Node _root = null;
    public Node Root { get { return _root; } }

    public class Node
    {
        public Node Left;
        public Node Right;

        public int Data;
    }

    public void Add(int value)
    {
        Node newItem = new Node();
        newItem.Data = value;

        Node current = _root;
        Node parent = null;

        while (current != null)
        {
            parent = current;

            if (current.Data == value)
            {
                return; // 같은 값이면 처리하지 않음.
            }

            if (current.Data > value)
            {
                current = current.Left;
            }
            else
            {
                current = current.Right;
            }
        }

        if (parent != null)
        {
            if (parent.Data > value)
            {
                parent.Left = newItem;
            }
            else
            {
                parent.Right = newItem;
            }
        }
        else
        {
            _root = newItem;
        }
    }

    int maxHeight(Node p)
    {
        if (p == null) return 0;
        int leftHeight = maxHeight(p.Left);
        int rightHeight = maxHeight(p.Right);
        return (leftHeight > rightHeight) ? leftHeight + 1 : rightHeight + 1;
    }

    public string ToDGML()
    {
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf - 8\"?>");
        sb.AppendLine("<DirectedGraph Layout=\"TopToBottom\" Title=\"Tree\" xmlns=\"http://schemas.microsoft.com/vs/2009/dgml\">");

        int left = (int)Math.Pow(2, maxHeight(_root)) * 30 + 100;
        int top = 100;

        StringBuilder nodes = new StringBuilder();
        StringBuilder links = new StringBuilder();

        DrawNodeDGML(nodes, links, _root, top, left, left / 2);
        sb.AppendLine("<Nodes>" + Environment.NewLine + nodes.ToString() + "</Nodes>");
        sb.AppendLine("<Links>" + Environment.NewLine + links.ToString() + "</Links>");

        sb.AppendLine("<Properties>");

        sb.AppendLine("<Property Id=\"Bounds\" DataType=\"System.Windows.Rect\" />");
        sb.AppendLine("<Property Id=\"Label\" Label=\"Label\" Description=\"Displayable label of an Annotatable object\" DataType=\"System.String\" />");
        sb.AppendLine("<Property Id=\"LabelBounds\" DataType=\"System.Windows.Rect\" />");
        sb.AppendLine("<Property Id=\"Layout\" DataType=\"System.String\" />");
        sb.AppendLine("<Property Id=\"Title\" DataType=\"System.String\" />");
        sb.AppendLine("<Property Id=\"UseManualLocation\" DataType=\"System.Boolean\" />");
        sb.AppendLine("</Properties>");

        sb.AppendLine("</DirectedGraph>");
        return sb.ToString();
    }

    void DrawNodeDGML(StringBuilder nodes, StringBuilder links, Node node, int top, int left, int offset)
    {
        int drawLeft = left + offset;

        nodes.AppendLine(string.Format("<Node UseManualLocation=\"True\" Id=\"{0}\" Bounds=\"{3}, {2}, 50, 26\" Label=\"{1}\" />", node.Data, node.Data,
            top, drawLeft));

        if (node.Left != null)
        {
            links.AppendLine(string.Format("<Link Source=\"{0}\" Label=\"Left\" Target=\"{1}\" />", node.Data, node.Left.Data));
            DrawNodeDGML(nodes, links, node.Left, top + 40, drawLeft, -(Math.Abs(offset) / 2));
        }

        if (node.Right != null)
        {
            links.AppendLine(string.Format("<Link Source=\"{0}\" Label=\"Right\" Target=\"{1}\" />", node.Data, node.Right.Data));
            DrawNodeDGML(nodes, links, node.Right, top + 40, drawLeft, +(Math.Abs(offset) / 2));
        }
    }
}

실행해 보면, 제법 그럴 듯하게 나옵니다. ^^

dgml_bintree_2.png

(첨부한 파일은 이 글의 테스트 코드를 포함합니다.)




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







[최초 등록일: ]
[최종 수정일: 6/27/2021]

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

비밀번호

댓글 작성자
 



2016-10-06 01시10분
Microsoft/automatic-graph-layout
; https://github.com/Microsoft/automatic-graph-layout
정성태

... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12324정성태9/11/202010356개발 환경 구성: 514. smigdeploy.exe를 이용한 Windows Server 2016에서 2019로 마이그레이션 방법
12323정성태9/11/20209275오류 유형: 649. Copy Database Wizard - The job failed. Check the event log on the destination server for details.
12322정성태9/11/202010216개발 환경 구성: 513. Azure VM의 RDP 접속 위치 제한 [1]
12321정성태9/11/20208616오류 유형: 648. netsh http add urlacl - Error: 183 Cannot create a file when that file already exists.
12320정성태9/11/20209774개발 환경 구성: 512. RDP(원격 데스크톱) 접속 시 비밀 번호를 한 번 더 입력해야 하는 경우
12319정성태9/10/20209534오류 유형: 647. smigdeploy.exe를 Windows Server 2016에서 실행할 때 .NET Framework 미설치 오류 발생
12318정성태9/9/20209057오류 유형: 646. OpenVPN - "TAP-Windows Adapter V9" 어댑터의 "Network cable unplugged" 현상
12317정성태9/9/202011342개발 환경 구성: 511. Beats용 Kibana 기본 대시 보드 구성 방법
12316정성태9/8/20209795디버깅 기술: 170. WinDbg Preview 버전부터 닷넷 코어 3.0 이후의 메모리 덤프에 대해 sos.dll 자동 로드
12315정성태9/7/202012082개발 환경 구성: 510. Logstash - FileBeat을 이용한 IIS 로그 처리 [2]
12314정성태9/7/202010452오류 유형: 645. IIS HTTPERR - Timer_MinBytesPerSecond, Timer_ConnectionIdle 로그
12313정성태9/6/202011754개발 환경 구성: 509. Logstash - 사용자 정의 grok 패턴 추가를 이용한 IIS 로그 처리
12312정성태9/5/202015715개발 환경 구성: 508. Logstash 기본 사용법 [2]
12311정성태9/4/202010890.NET Framework: 937. C# - 간단하게 만들어 보는 리눅스의 nc(netcat), json_pp 프로그램 [1]
12310정성태9/3/202010115오류 유형: 644. Windows could not start the Elasticsearch 7.9.0 (elasticsearch-service-x64) service on Local Computer.
12309정성태9/3/20209858개발 환경 구성: 507. Elasticsearch 6.6부터 기본 추가된 한글 형태소 분석기 노리(nori) 사용법
12308정성태9/2/202011141개발 환경 구성: 506. Windows - 단일 머신에서 단일 바이너리로 여러 개의 ElasticSearch 노드를 실행하는 방법
12307정성태9/2/202011901오류 유형: 643. curl - json_parse_exception / Invalid UTF-8 start byte
12306정성태9/1/202010049오류 유형: 642. SQL Server 시작 오류 - error code 10013
12305정성태9/1/202010973Windows: 172. "Administered port exclusions"이 아닌 포트 범위 항목을 삭제하는 방법
12304정성태8/31/20209918개발 환경 구성: 505. 윈도우 - (네트워크 어댑터의 우선순위로 인한) 열거되는 IP 주소 순서를 조정하는 방법
12303정성태8/30/202010089개발 환경 구성: 504. ETW - 닷넷 프레임워크 기반의 응용 프로그램을 위한 명령행 도구 etrace 소개
12302정성태8/30/202010047.NET Framework: 936. C# - ETW 관련 Win32 API 사용 예제 코드 (5) - Private Logger파일 다운로드1
12301정성태8/30/202010305오류 유형: 641. error MSB4044: The "Fody.WeavingTask" task was not given a value for the required parameter "IntermediateDir".
12300정성태8/29/20209755.NET Framework: 935. C# - ETW 관련 Win32 API 사용 예제 코드 (4) CLR ETW Consumer파일 다운로드1
12299정성태8/27/202010674.NET Framework: 934. C# - ETW 관련 Win32 API 사용 예제 코드 (3) ETW Consumer 구현파일 다운로드1
... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...