U E D R , A S I H C RSS

파스칼삼각형/조영준 (rev. 1.2)

파스칼삼각형/조영준

개요

  • 일시 : 2013년 4월 19일 00시 10분
  • 동기
    • 지피실에서 시험공부하다가 지겨워져서 지피실에 계신 선배분들에게 간단한 코드 연습거리를 달라고 말씀드렸더니 크기 10의 파스칼 삼각형을 출력하라고 하셨다. 그래서 바로 착수.
  • 개발 시간 : 90분
    • 크기 10짜리 파스칼 삼각형을 만드는 데에는 30분 걸림. 그런데 개인적으로 뭘 만들고 더 개조하는 것을 좋아해서 삼각형의 크기를 입력받아서 출력하도록 바꿨는데 아주 사소한 문제가 등장. 정말 간단한 문제였는데 왜 그거가지고 20분을 고민했는지 아직도 이해가 안 된다. 그리고 10분을 투자해서 원하는 크기의 삼각형을 출력하도록 바꾸었고, 30분을 더 투자해서 파스칼 삼각형의 최대값에 따라 출력 크기 설정하도록 변경.
  • 개발 언어 : C#
  • 아쉬운 점
    • 원래 더 큰 숫자의 삼각형 크기를 가질 수 있도록 하려고 했지만 콘솔창의 가로 폭이 좁아서 불가능. 내가 왜 이렇게 짰는데 엉엉.
    • 파스칼 삼각형의 최대값을 그냥 공식으로 바로 구하려고 했는데 조합이나 팩토리얼 매소드를 못 찾고 짜기도 귀찮아서 그냥 직접 구하는 방식으로 변경.

소스

Program.cs

// 파스칼 삼각형 출력
using System;
namespace PascalTriangle
{
    class Program
    {
        static void Main(string[] args)
        {
            string s;
            int lines;
            while (true)
            {
                Console.WriteLine("삼각형의 크기를 입력하세요 (1~13, 0 = exit)");
                s = Console.ReadLine(); //삼각형 크기를 입력받음
                try
                {
                    lines = Convert.ToInt32(s);
                    if (lines < 0 || lines > 13)
                    {
                        // 14 이상에는 삼각형이 정상 출력되나 보기 좋지 않음
                        Exception e = new Exception("유효하지 않은 범위입니다");
                        throw e;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                if (lines == 0) return; // 프로그램 종료
                PTriangle pTriangle = new PTriangle(lines);
                Printer printer = new Printer(lines, pTriangle.getMax().ToString().Length+1);

                for (int i = 0; i < lines; i++)
                {
                    printer.print(pTriangle.Next());
                }
            }
        }
    }
}

PTriangle.cs

using System;
namespace PascalTriangle
{
    class PTriangle
    {
        private int lines; //삼각형의 총 줄
        private int count; //현재 반환중인 줄
        private int[] prv; // 이전 줄
        private int[] current; // 현재 줄
        
        public PTriangle(int lines)
        {
            this.lines = lines;
            count = 1;
        }
        public int[] Next()
        {
            if (count == 1)
            {
                //삼각형의 머리일 경우
                count++;
                return savePrv(new int[] { 1 });
            }
            current = new int[count];
            current[0] = 1; //줄의 맨 처음
            current[count-1] = 1; //줄의 맨 마지막
            for (int i = 0; i < current.Length - 2; i++)
            {
                current[i + 1] = prv[i] + prv[i + 1]; //파스칼 삼각형 규칙
            }
            count++;
            return savePrv(current);
        }
        public int getMax()
        {
            //파스칼 삼각형의 최대값 반환
            for(int i = 0 ; i < lines ; i++)
            {
                Next();
            }
            count = 1; //초기화
            return current[lines/2];
        }
        private int[] savePrv(int[] i)
        {
            //리턴과 동시에 int[] prv에 저장
            prv = i;
            return i;
        }
    }
}

Printer.cs

using System;
namespace PascalTriangle
{
    class Printer
    {
        private int lines; //총 출력할 줄
        private int count; //좌우로 출력해야할 빈 공간의 수 (4칸이 한 단위)
        private int scale; //한 칸당 너비 짝수야 한다
        public Printer(int lines, int scale)
        {
            this.lines = lines;
            this.scale = scale;
            if (scale % 2 == 1) this.scale++; //너비가 홀수이면 짝수로 변경 
        }
        public void print(int[] nums)
        {
            count = lines - nums.Length;
            if (count % 2 == 1)
            {
                // 빈 공간의 수가 홀수일 경우 그 반을 출력
                printEmpty(scale / 2);
                count--;
            }
            for (int i = 0; i < count / 2; i++ )
            {
                // 좌측의 빈 공간 출력
                printEmpty(scale);
            }
            for (int i = 0; i < nums.Length; i++)
            {
                // 빈 공각 출력
                printEmpty(scale - nums[i].ToString().Length);
                // 숫자 출력
                Console.Write(nums[i]);
            }
            Console.Write("\n");
        }
        private void printEmpty(int size)
        {
            //입력받은 수 만큼 빈 칸 출력
            for (int i = 0; i < size; i++)
            {
                Console.Write(" ");
            }
        }
    }
}

결과

삼각형의 크기를 입력하세요 (1~13, 0 = exit)
5
     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1
삼각형의 크기를 입력하세요 (1~13, 0 = exit)
6
             1
           1   1
         1   2   1
       1   3   3   1
     1   4   6   4   1
   1   5  10  10   5   1
삼각형의 크기를 입력하세요 (1~13, 0 = exit)
0
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:31:23
Processing time 0.0158 sec