= 개요 = * 일시 : 2013년 4월 19일 00시 10분 * 동기 *지피실에서 시험공부하다가 지겨워져서 지피실에 계신 선배분들에게 간단한 코드 연습거리를 달라고 말씀드렸더니 크기 10의 파스칼 삼각형을 출력하라고 하셨다. 그래서 바로 착수. * 개발 시간 : 60분 * 크기 10짜리 파스칼 삼각형을 만드는 데에는 30분 걸림. 그런데 개인적으로 뭘 만들고 더 개조하는 것을 좋아해서 삼각형의 크기를 입력받아서 출력하도록 바꿨는데 아주 사소한 문제가 등장. 정말 간단한 문제였는데 왜 그거가지고 20분을 고민했는지 아직도 이해가 안 된다. * 개발 언어 : 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; // 프로그램 종료 Printer printer = new Printer(lines); PTriangle pTriangle = new PTriangle(lines); 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); } 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칸이 한 단위) public Printer(int lines) { this.lines = lines; } public void print(int[] nums) { count = lines - nums.Length; if (count % 2 == 1) { // 빈 공간의 수가 홀수일 경우 그 반을 출력 Console.Write(" "); count--; } for (int i = 0; i < count / 2; i++ ) { // 좌측의 빈 공간 출력 Console.Write(" "); } for (int i = 0; i < nums.Length; i++) { // 숫자 출력 Console.Write("{0, 4}", nums[i]); } Console.Write("\n"); } } } }}} == 결과 == {{{ 삼각형의 크기를 입력하세요 (1~13, 0 = exit) 5 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 삼각형의 크기를 입력하세요 (1~13, 0 = exit) 0 }}}