초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 C# 소스이다.

/*
 * Filename: MakeMultTableApp.cs
 *
 *     Print a multiplication table.
 *
 *     Compile: csc MakeMultTableApp.cs
 *     Execute: MakeMultTableApp 230 5100
 *
 * Date: 2009/03/07
 * Author: pkim (AT) scripts.pe.kr
 */

using System;

namespace MyTestApplication1 { 

    public class MakeMultTableApp {

        public static void PrintUsing() {
            Console.WriteLine("Using: MakeMultTableApp [number1] [number2]");
            Console.WriteLine("Print a multiplication table for the given two integers.");
        }

        public static void PrintMultTable(long x, long y) {
            long nx = (x >= 0) ? x : - x;
            long ny = (y >= 0) ? y : - y;
            int ntail1 = 0;
            int ntail2 = 0;
            while (nx % 10 == 0) {
                nx = nx / 10;
                ntail1++;
            }
            while (ny % 10 == 0) {
                ny = ny / 10;
                ntail2++;
            }
            long z = nx * ny;
            String strZ = "" + z;
            String strX = "" + nx;
            String strY = "" + ny;
            int n = strY.Length;
            String zeros  = "0000000000000000000000000000000000000000";
            String whites = "                                        ";
            String bars   = "----------------------------------------";
            String line1, line2, line3, line4;
            String loffset = "       ";
            line4 = loffset + strZ;
            line1 = loffset + whites.Substring(0, strZ.Length - strX.Length) + strX;
            line2 = "   x ) " +  whites.Substring(0, strZ.Length- strY.Length) + strY;
            line3 = "     --" +  bars.Substring(0, strZ.Length);
            Console.WriteLine(line1 + zeros.Substring(0, ntail1));
            Console.WriteLine(line2 + zeros.Substring(0, ntail2));
            Console.WriteLine(line3);
            if (strY.Length > 1) {
                int y1;
                String strT;
                for (int i = 0; i < strY.Length; i++) {
                    y1 = Convert.ToInt32(strY.Substring(strY.Length - i - 1, 1));
                    if (y1 != 0) {
                        strT = "" + (nx * y1);
                        Console.WriteLine(loffset + whites.Substring(0, strZ.Length - strT.Length - i) + strT);
                    }
                }
                Console.WriteLine(line3);
            }
            Console.WriteLine(line4 + zeros.Substring(0, ntail1) + zeros.Substring(0, ntail2));
        }

        public static void Main(String[] args) {
            long x, y;
            if (args.Length >= 2) {
                x = Convert.ToInt64(args[0]);
                y = Convert.ToInt64(args[1]);
                Console.WriteLine("");
                PrintMultTable(x, y);
            }
            else {
                PrintUsing();
            }
        }
    }
}



 

컴파일> csc MakeMultTableApp.cs
실행> MakeMultTableApp 230 5100
결과>

          230
   x )   5100
     ------
         23
       115
     ------
       1173000

 

Posted by Scripter
,


 

/*
 *  Filename: testStringReverse.cs
 *
 *  Compile: csc testStringReverse.cs
 *  Execute: testStringReverse
 */

using System;

public class StringReverseApp {
    public static void Main(string[] args) {
        string a, b;
        a = "Hello, world!";
        b = "안녕하세요?";
        char[] arr = a.ToCharArray();
        Array.Reverse(arr);
        Console.WriteLine(new String(arr));
        arr = b.ToCharArray();
        Array.Reverse(arr);
        Console.WriteLine(new String(arr));
    }
}
/*
Expected result:
!dlrow ,olleH
?요세하녕안
*/



 

Posted by Scripter
,

다음은 초등학교에서 배우는 나눗셈 계산표를 만들어주는 C# 소스 코드이다.
나눗셈 계산표를 완성하고 나서 약수, 배수 관계를 알려준다.


  1.  /*
  2.  *  Filename: MakeDivisionTableApp.cs
  3.  *
  4.  *  Purpose:  Make a division table in a handy written form.
  5.  *
  6.  *  Compile: csc MakeDivisionTableApp.cs BigInteger.cs
  7.  *
  8.  *  Execute: MakeDivisionTableApp 12345 32
  9.  *           MakeDivisionTableApp 500210 61
  10.  *
  11.  *     Date:  2009/01/24
  12.  *   Author:  PH Kim   [ pkim ((AT)) scripts.pe.kr ]
  13.  */
  14. using System;
  15. // using System.Numeric;     // only for C# 3.0 above
  16. using ScottGarland;          // for C# 2.0   Get at http://www.codeplex.com/biginteger/Release/ProjectReleases.aspx?ReleaseId=16762
  17. namespace MyTestApplication1 {
  18.     public class MakeDivisionTableApp {
  19.         public static BigInteger ZERO = new BigInteger("0");
  20.         public static void printUsage() {
  21.              // Console.WriteLine("Using: MakeDivisionTableApp [numerator] [denominator]");
  22.              // Console.WriteLine("Make a division table in a handy written form.");
  23.              Console.WriteLine("사용법: MakeDivisionTableApp [피제수] [제수]");
  24.              Console.WriteLine("손으로 작성한 형태의 나눗셈 표를 만들어준다.");
  25.         }
  26.         public static String simplify(double v) {
  27.             String t = "" + v;
  28.             if (t.EndsWith(".0"))
  29.                 t = t.Substring(0, t.Length - 2);
  30.             return t;
  31.         }
  32.         public static String simplify(BigInteger v, int width) {
  33.             String t = "" + v;
  34.             if (t.EndsWith(".0"))
  35.                 t = t.Substring(0, t.Length - 2);
  36.             int len = t.Length;
  37.             if (len < width)
  38.                 t = "                                                                                             ".Substring(0, width - len) + t;
  39.             return t;
  40.         }
  41.         public String getSuffix(BigInteger v) {
  42.             BigInteger t = BigInteger.Modulus(v, new BigInteger("10"));
  43.             String suffix = "은";
  44.             if ("2459".IndexOf("" + t) >= 0) {
  45.                 suffix = "는";
  46.             }
  47.             return suffix;
  48.         }
  49.         public BigInteger makeTable(BigInteger numer, BigInteger denom, BigInteger quotient) {
  50.             String strNumer = "" + numer;
  51.             String strDenom = "" + denom;
  52.             String strQuotient = "" + quotient;
  53.             int lenN = strNumer.Length;
  54.             int lenD = strDenom.Length;
  55.             int lenQ = strQuotient.Length;
  56.             int offsetLeft = 3 + lenD + 3;
  57.             String spaces = "                                                                                 ";
  58.             String uline  = "_________________________________________________________________________________".Substring(0, lenN + 2);
  59.             String sline  = "---------------------------------------------------------------------------------".Substring(0, lenN);
  60.             int bias = lenN - lenQ;
  61.             Console.WriteLine(spaces.Substring(0, offsetLeft) + spaces.Substring(0, bias) + quotient);
  62.             Console.WriteLine(spaces.Substring(0, offsetLeft - 2) + uline);
  63.             Console.Write("   " + strDenom + " ) " + strNumer);
  64.             String strTmpR = strNumer.Substring(0, bias + 1);
  65.             BigInteger tmpR = new BigInteger(strTmpR);
  66.             BigInteger tmpSub = ZERO;
  67.             String oneDigit = null;
  68.             for (int i = 0; i < lenQ; i++) {
  69.                 if (strQuotient.Substring(i, 1).Equals("0")) {
  70.                     if (i + 1 < lenQ) {
  71.                         oneDigit = strNumer.Substring(bias + i + 1, 1);
  72.                         Console.Write(oneDigit);
  73.                         strTmpR += oneDigit;
  74.                         tmpR = new BigInteger(strTmpR);
  75.                     }
  76.                 }
  77.                 else {
  78.                     Console.WriteLine();
  79.                     tmpSub = BigInteger.Multiply(new BigInteger(strQuotient.Substring(i, 1)), denom);
  80.                     Console.WriteLine(spaces.Substring(0, offsetLeft) + simplify(tmpSub, bias + i + 1));
  81.                     Console.WriteLine(spaces.Substring(0, offsetLeft) + sline);
  82.                     tmpR = BigInteger.Subtract(tmpR, tmpSub);
  83.                     if (tmpR.Equals(ZERO) && i + 1 < lenQ) {
  84.                         Console.Write(spaces.Substring(0, offsetLeft) + spaces.Substring(0, bias + i + 1));
  85.                     }
  86.                     else {
  87.                         Console.Write(spaces.Substring(0, offsetLeft) + simplify(tmpR, bias + i + 1));
  88.                     }
  89.                     strTmpR = "" + tmpR;
  90.                     if (i + 1 < lenQ) {
  91.                         oneDigit = strNumer.Substring(bias + i + 1, 1);
  92.                         Console.Write(oneDigit);
  93.                         strTmpR += oneDigit;
  94.                         tmpR = new BigInteger(strTmpR);
  95.                     }
  96.                 }
  97.             }
  98.             Console.WriteLine();
  99.             return tmpR;
  100.         }
  101.         public static void Main(String[] args) {
  102.             if (args.Length < 2) {
  103.                 printUsage();
  104.                 Environment.Exit(1);
  105.             }
  106.             BigInteger a = null;
  107.             BigInteger b = null;
  108.             try {
  109.                 a = new BigInteger(args[0]);
  110.                 b = new BigInteger(args[1]);
  111.             }
  112.             catch (ArgumentOutOfRangeException ex) {
  113.                 Console.WriteLine(ex);
  114.                 Console.WriteLine("피제수: " + args[0] + ", 제수: " + args[1]);
  115.                 Console.WriteLine("숫자 입력에 오류가 있습니다.");
  116.                 Environment.Exit(1);
  117.             }
  118.             catch (ArgumentNullException ex) {
  119.                 Console.WriteLine(ex);
  120.             }
  121.             catch (FormatException ex) {
  122.                 Console.WriteLine(ex);
  123.                 Console.WriteLine("피제수: " + args[0] + ", 제수: " + args[1]);
  124.                 Console.WriteLine("숫자 입력에 오류가 있습니다.");
  125.                 Environment.Exit(1);
  126.             }
  127.             if (BigInteger.Compare(a, ZERO) <= 0) {
  128.                 Console.WriteLine("피제수: " + a);
  129.                 Console.WriteLine("피제수는 양의 정수라야 합니다.");
  130.                 Environment.Exit(1);
  131.             }
  132.             else if (BigInteger.Compare(b, ZERO) <= 0) {
  133.                 Console.WriteLine("제수: " + b);
  134.                 Console.WriteLine("제수는 양의 정수라야 합니다.");
  135.                 Environment.Exit(1);
  136.             }
  137.             MakeDivisionTableApp app = new MakeDivisionTableApp();
  138.             BigInteger q = BigInteger.Divide(a, b);
  139.             BigInteger r = BigInteger.Modulus(a, b);
  140.             Console.Write("나눗셈 " + a + " ÷ " + b + " 의 결과: ");
  141.             Console.Write("몫: " + q + ", ");
  142.             Console.WriteLine("나머지: " + r);
  143.             Console.WriteLine();
  144.             BigInteger k = app.makeTable(a, b, q);
  145.             Console.WriteLine();
  146.             if (k.Equals(r)) {
  147.                 Console.WriteLine("나머지: " + k);
  148.             }
  149.             if (k.Equals(ZERO)) {
  150.                 Console.WriteLine(a + " = " + b + " x " + q);
  151.                 Console.WriteLine(a + app.getSuffix(a) + " " + b + "의 배수(mupltiple)이다.");
  152.                 Console.WriteLine(b + app.getSuffix(b) + " " + a + "의 약수(divisor)이다.");
  153.             }
  154.             else {
  155.                 Console.WriteLine(a + " = " + b + " x " + q + " + " + r);
  156.                 Console.WriteLine(a + app.getSuffix(a) + " " + b + "의 배수(mupltiple)가 아니다.");
  157.             }
  158.         }
  159.     }
  160. }





실행> MakeDivisionTableApp 500210 61

나눗셈 500210 ÷ 61 의 결과: 몫: 8200, 나머지: 10

          8200
      ________
   61 ) 500210
        488
        ------
         122
         122
        ------
            10

나머지: 10
500210 = 61 x 8200 + 10
500210은 61의 배수(mupltiple)가 아니다.




Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은 세 개의 public 클래스로 구성되어 있다. 각 클래스는 별도의 파일로 저장되어야 한다.
(Java와는 달리) 하나의 C# 소스파일에 public 클래스가 여러개 존재해도 된다. 소스 파일명도 public 클래스명과 달라도 된다. C# 언어는 소스 코드에서 C, C++, Java  언어 처럼 대소문자 구별을 엄격히 한다.

Parent는 부모 클래스이고 Child는 Parent에서 상속 받은 자식 클래스이다.


컴파일하는 명령은 

     csc TestSubclassing.cs Parent.cs Child.cs

이다.

// Filename: Parent.cs

using System;

namespace MyTestApplication1 {

public class Parent {

    private String name;

        public Parent() {
        }

        public Parent(String name) {
            this.name =  name;
        }

        public virtual void sayName() {
            System.Console.WriteLine("I am Parent, " + name);
        }
    }
}




 

// Filename: Child.cs

using System;

namespace MyTestApplication1 {

    public class Child : Parent {
        private String name;

        public Child(String name) {
            // super(name);               // 클래스 상속시 부모 클래스 생성자 호출
            this.name =  name;
        }

        public override void sayName() {
            Console.WriteLine("I am a child, named as " + name);
        }
    }
}




 

// Filename: TestSubclassing.cs

using System;

namespace MyTestApplication1 {

    public class TestSubclassing {
        public static void Main(String[] args) {
            Child obj = new Child("Dooly");
            obj.sayName();
        }
    }
}



실행> TestSubclassing
I am a child, named as Dooly




Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

콘솔에 삼각형

         *
       * *
      *   *
     *     *
    *       *
   *         *
  *           *
 *             *
*****************


을 출력하는 C# 애플리케이션을 만들어 보자. 이런 소스 코드의 작성은 학원이나 학교에서 프로그래밍 입문자에게 과제로 많이 주어지는 것 중의 하나이다. 코끼리를 보거나 만진 사람들이 저마다 그 생김새를 말할 때 제각기 다르게 표현할 수 있듯이 이런 소스 코드의 작성도 알고 보면 얼마든지 많은 방법이 있을 것이다. 여기서는 쉬운 코드 부터 작성해 보고 차츰차츰 소스를 바꾸어 가면서 C# 프로그래밍의 기초부분을 터득해 보기로 한다.


우선 첫번 째로 다음 예제는 컨솔 출력 메소드 System.Console.WriteLine()의 사용법만 알면 누구나 코딩할 수 있는 매우 단순한 소스 코드이다.


삼각형 출력 예제 1
/*
 *  Filename: PrintTriangleApp1.cs
 *            Print a triangle on console.
 *
 *  Compile: csc PrintTriangleApp1.cs
 *  Execute: PrintTriangleApp1
 *
 *      Date:  2009/01/24
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;

namespace MyTestApplication1 {

    public class PrintTriangleApp1 {
        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            Console.WriteLine("        *        ");
            Console.WriteLine("       * *       ");
            Console.WriteLine("      *   *      ");
            Console.WriteLine("     *     *     ");
            Console.WriteLine("    *       *    ");
            Console.WriteLine("   *         *   ");
            Console.WriteLine("  *           *  ");
            Console.WriteLine(" *             * ");
            Console.WriteLine("*****************");
        }
    }
}


위의 소스 코드는 아무 알고리즘도 없는 너무 단순한 코드이다. 이런 코드를 작성했다간 출력 모양이나 크기를 변경해야 하는 상황을 맞이하면 워드프로세서로 문서 만드는 것 이상으로 많은 수작업을 하거나 아니면 포기하는 지경에 이를 수도 있다. 그래서 다음처럼 좀 더 나은 소스 코드를 작성하였다.



삼각형 출력 예제 2
/*
 *  Filename: PrintTriangleApp2.cs
 *            Print a triangle on console.
 *
 *  Compile: csc PrintTriangleApp2.cs
 *  Execute: PrintTriangleApp2
 *
 *      Date:  2009/01/24
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;

namespace MyTestApplication1 {

    public class PrintTriangleApp2 {
        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            for (int i = 0; i < 8; i++) {
                for (int k = 0;  k < 8 - i; k++) {
                    Console.Write(" ");
                }
                for (int k = 0;  k < 2*i + 1; k++) {
                    if (k == 0 || k == 2*i)
                        Console.Write("*");
                    else
                        Console.Write(" ");
                }
                for (int k = 0;  k < 8 - i; k++) {
                    Console.Write(" ");
                }
                Console.WriteLine();
            }

            for (int i = 0; i < 17; i++) {
                Console.Write("*");
            }
            Console.WriteLine();
        }
    }
}


위의 소스 코드는 출력 메소드 Console.WriteLine()과 Console.Write() 그리고 for 구문을 적절히 사용하여 구현되었다. 숫자 몇 곳만 수정하면 출력되는 삼각형의 크기를 바꿀 수 있다. 한 줄에 출력될 문자를 구성하는 알고리즘은 위의 예제와 근본적으로 같지만 Console.Write()를 사용하지 않고, 그대신 System.Text.StringBuilder 클래스를 적절히 사용하여 한 즐씩 출력하는 소스 코드를 다음 예제와 같이 작성해 보았다. 아래의 소스 코드에서 사용된 문자치환 메소드 StringBuilder.Replace()의 사용법은 다음과 같다.

using System.Text;
public StringBuilder StringBuilder.Replace(string oldValue, string newValue, int startIndex, int count);



삼각형 출력 예제 3
/*
 *  Filename: PrintTriangleApp3.cs
 *            Print a triangle on console.
 *
 *  Compile: csc PrintTriangleApp3.cs
 *  Execute: PrintTriangleApp3
 *
 *      Date:  2009/01/24
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;
using System.Text;

namespace MyTestApplication1 {

    public class PrintTriangleApp3 {
        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            string line = "                 ";
            StringBuilder line2 = new StringBuilder("");
            for (int i = 0; i < 8; i++) {
                line2 = new StringBuilder(line);
                line2.Replace(" ", "*", 8-i, 1);
                line2.Replace(" ", "*", 8+i, 1);
                Console.WriteLine(line2);
            }

            line2 = new StringBuilder(line);
            for (int i = 0; i < 17; i++) {
                line2.Replace(" ", "*", i, 1);
            }
            Console.WriteLine(line2);
        }
    }
}



별(*) 문자를 이용하여 삼각형을 출력하는 일은 빈칸  문자와 별 문자를 적당한 좌표(위치)에 촐력하는 일이다. StringBuilder를 사용하더라도 한 줄의 출력을 빈칸 만으로로 구성된 string(소스 코드에서 변수 whites가 참조하는 string 값)을 기본으로 하고, 이 string에 한 두 개의 빈칸을 바꾸어 출력하는 기법으로 작성한 것이 다음 소스 코드이다. 단, 마지막 줄에 츨력될 string은 stars라는 별도의 변수로 처리하였다.



삼각형 출력 예제 4
/*
 *  Filename: PrintTriangleApp4.cs
 *            Print a triangle on console.
 *
 *  Compile: csc PrintTriangleApp4.cs
 *  Execute: PrintTriangleApp4
 *
 *      Date:  2009/01/24
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;
using System.Text;

namespace MyTestApplication1 {

    public class PrintTriangleApp4 {
        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            String whites = "                 ";
            String stars  = "*****************";
            StringBuilder line2 = new StringBuilder(whites);
            line2.Replace(" ", "*", 8, 1);
            Console.WriteLine(line2);

            for (int i = 1; i < 8; i++) {
                line2 = new StringBuilder(whites);
                line2.Replace(whites.Substring(8-i, 1), stars.Substring(8-i, 1), 8-i, 1);
                line2.Replace(whites.Substring(8+i, 1), stars.Substring(8+i, 1), 8+i, 1);
                Console.WriteLine(line2);
            }

            Console.WriteLine(stars);
        }
    }
}



빈칸 문자를 별(*) 문자로 바꾸기 위해, 위의 소스 코드에서는 StringBuilder.Replace() 메소드를 이용하였지만, 다음 소스 코드에서는 StringBuilder[index] = char 메소드를 이용하였다.



삼각형 출력 예제 5
/*
 *  Filename: PrintTriangleApp5.cs
 *            Print a triangle on console.
 *
 *  Compile: csc PrintTriangleApp5.cs
 *  Execute: PrintTriangleApp5
 *
 *      Date:  2009/01/24
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;
using System.Text;

namespace MyTestApplication1 {

    public class PrintTriangleApp5 {
        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            String whites = "                 ";
            String stars  = "*****************";
            StringBuilder line = new StringBuilder(whites);
            int start = 8;
            line[start] =  stars[8];
            Console.WriteLine(line);

            for (int i = 1; i < 8; i++) {
                line = new StringBuilder(whites);
                line[start - i] = stars[start - i];
                line[start + i] =  stars[start + i];
                Console.WriteLine(line);
            }

            Console.WriteLine(stars);
        }
    }
}




출력되는 삼각형이 좌우 대칭이라는 사실에 착안하여, 다음 소스 코드에서는  각 줄을 처음 8자, 중앙 한 문자, 끝 8자(처음 8자의 역순)로 string을 만들어 출력하였다.

Java 언아에는 StringBuffer.reverse()라는 메소드가 있어서 유익하였지만,
C# 언어에는  StringBuilderRreverse()라는 메소드가 없기에
Java 소스 코드

                line.reverse();
                System.out.println(line);

가 C# 소스 코드

                arrRev = line.ToString().ToCharArray();
                Array.Reverse(arrRev);
                Console.WriteLine( new String(arrRev) );

처럼 여러 단계를 거쳐 역순 문자열이 출력되었다.



삼각형 출력 예제 6
/*
 *  Filename: PrintTriangleApp6.cs
 *            Print a triangle on console.
 *
 *  Compile: csc PrintTriangleApp6.cs
 *  Execute: PrintTriangleApp6
 *
 *      Date:  2009/01/24
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;
using System.Text;

namespace MyTestApplication1 {

    public class PrintTriangleApp6 {
        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            char[] arrRev;
            String whites = "        ";
            String stars  = "********";
            int start = 8;
            StringBuilder line = new StringBuilder(whites);
            line.Append('*');
            line.Append(whites);
            Console.WriteLine(line);

            for (int i = 1; i < 8; i++) {
                line = new StringBuilder(whites);
                line[start - i] = stars[start - i];
                Console.Write(line);
                Console.Write(" ");
                arrRev = line.ToString().ToCharArray();
                Array.Reverse(arrRev);
                Console.WriteLine( new String(arrRev) );
             }

            line = new StringBuilder(stars);
            Console.Write(line);
            line.Append("*");
            Console.WriteLine(line);
        }
    }
}




다음 소스 코드는 한 줄에 출력될 문자열의 데이터를 17비트 이진법 수로 구성하고, 이 이진법수의 비트가 0인 곳에는 빈칸을, 1인 곳에는 별(*)을 출력하는 기법으로 작성되었다.

int 타입을 2진법 표현 문자열로 표현하는 C# 소스 코드는 어떻게 될까?
Java 소스 코드는

                String strValue = Integer.parseInt(intValue, 2);

이다. 이를 C# 소스 코드로 재작성하면

                String strValue = System.Convert.ToString(intValue, 2);

이 된다.



삼각형 출력 예제 7
/*
 *  Filename: PrintTriangleApp7.cs
 *            Print a triangle on console.
 *
 *  Compile: csc PrintTriangleApp7.cs
 *  Execute: PrintTriangleApp7
 *
 *      Date:  2009/01/24
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;
using System.Text;

namespace MyTestApplication1 {

    public class PrintTriangleApp7 {
        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            int start = 0x100;
            int total = 0;
            int val = start;
            String data;
            for (int k = 0; k < 8; k++) {
                val = (start << k) | (start >> k);
                data = Convert.ToString(val, 2);
                for (int i = 0; i < 17 - data.Length; i++) {
                    Console.Write(' ');
                }
                for (int i = 0; i < data.Length; i++) {
                    if (data[i] == '0')
                        Console.Write(' ');
                    else
                        Console.Write('*');
                }
                Console.WriteLine();
                total += val;
            }

            val = (start << 8) | (start >> 8);
            total += val;
            data = Convert.ToString(total, 2);
            for (int i = 0; i < 17 - data.Length; i++) {
                Console.Write(' ');
            }
            for (int i = 0; i < data.Length; i++) {
                if (data[i] == '0')
                    Console.Write(' ');
                else
                    Console.Write('*');
            }
            Console.WriteLine();
        }
    }
}




기본적인 원리는 위의 소스 코드와 같지만 이진법수의 한 비트 마다 한 문자씩 츨력하는 대신에 출력된 한 줄의 string을 완성하여 이를 Sytem.out.println()으로 출력하는 기법으로 재작성한 것이 다음의 소스 코드이다. String.replaceAll() 메소드를 이용하여, 모든 0을 빈칸으로, 모든 1을 별(*) 문자로 바꾸었으며, 별(*) 문자만으로 이루어진 마지막 줄 출력을 위해 변수 total을 준비하였다. for 반복 구문의 블럭 내에서 구문

            total |= val;

이 하는 일이 무엇인지 이해할 수 있으면 좋겠다.




삼각형 출력 예제 8
/*
 *  Filename: PrintTriangleApp8.cs
 *            Print a triangle on console.
 *
 *  Compile: csc PrintTriangleApp8.cs
 *  Execute: PrintTriangleApp8
 *
 *      Date:  2009/01/24
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;
using System.Text;

namespace MyTestApplication1 {

    public class PrintTriangleApp8 {
        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            String zeros  = "00000000";
            int start = 0x100;
            int total = 0;
            int val = start;
            String line = "";
            String data;
            for (int k = 0; k < 8; k++) {
                val = (start << k) | (start >> k);
                data = Convert.ToString(val, 2);
                line = zeros.Substring(0, 17 - data.Length) + data;
                line = line.Replace("0", " ");
                line = line.Replace("1", "*");
                Console.WriteLine(line);
                total |= val;
            }

            val = (start << 8) | (start >> 8);
            total |= val;
            line = Convert.ToString(total, 2);
            line = line.Replace("0", " ");
            line = line.Replace("1", "*");
            Console.WriteLine(line);
        }
    }
}




소스 코드가 처음 것 보다 매우 복잡해졌지만 저너릭(generics)을 지원하는 리스트(System.Collections.Genericl.List)를 이용해서도 할 수 있다는 것을 보여주기 위해서 일부러 작성해보았다. C# 2.0 부터 등장한 저너릭를 이용한 소스 코드이므로 C# 2.0 이상에서 컴파일되어야 한다. 별(*) 문자만으로 이루어진 마지막 줄 출력을 위해 변수 last를 준비하였다.



삼각형 출력 예제 9
/*
 *  Filename: PrintTriangleApp9.cs
 *            Print a triangle on console.
 *
 *  Compile: csc PrintTriangleApp9.cs
 *  Execute: PrintTriangleApp9
 *
 *      Date:  2009/01/24
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace MyTestApplication1 {

    public class PrintTriangleApp9 {
        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            int start = 8;
            List<String> data = new List<String>();
            List<String> last = new List<String>();
            for (int k = 0; k < 17; k++) {
                data.Add(" ");
                last.Add(" ");
            }
            data[start] = "*";
            last[start] = "*";
            for (int i = 0; i < data.Count; i++) {
                Console.Write(data[i]);
            }
            Console.WriteLine();
            data[start] = " ";

            for (int k = 1; k < 8; k++) {
                data[start - k] = "*";
                last[start - k] = "*";
                data[start + k] = "*";
                last[start + k] = "*";

                for (int i = 0; i < data.Count; i++) {
                    Console.Write(data[i]);
                }
                Console.WriteLine();

                data[start - k] = " ";
                data[start + k] = " ";
            }

            last[start - 8] = "*";
            last[start + 8] = "*";
            for (int i = 0; i < last.Count; i++) {
                Console.Write(last[i]);
            }
            Console.WriteLine();
        }
    }
}




다음 예제는 수학에서 xy-좌표평면에 점을 찍듯이 논리 구문

             (x + y - 8 == 0) || (y - x + 8 == 0) || (y - 8 == 0)

가 참이 되는 위치에 별(*) 문자를 표시하는 기법으로 작성된 소스 코드이다.




삼각형 출력 예제 10
/*
 *  Filename: PrintTriangleApp10.cs
 *            Print a triangle on console.
 *
 *  Compile: csc PrintTriangleApp10.cs
 *  Execute: PrintTriangleApp10
 *
 *      Date:  2009/01/24
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace MyTestApplication1 {

    public class PrintTriangleApp10 {
        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            char a;
            for (int y = 0; y <= 8; y++) {
                for (int x = 0; x <= 16; x++) {
                    if ((x + y - 8 == 0) || (y - x + 8 == 0) || (y - 8 == 0))
                        a = '*';
                    else
                        a = ' ';
                    Console.Write(a);
                }
                Console.WriteLine();
            }
        }
    }
}


Posted by Scripter
,

ASCII(애스키)란 American Standard Code for Information Interchange의 줄임글로서, 영문자에 기초한 문자 인코딩이다.  이 문자 인코딩에는 C0 제어문자(C0 control character)도 포함되어 있다.  ( 참고:  ASCII - Wikipedia, the free encyclopedia )

다음은  7bit ASCII 코드표를 만들어 보여주는 C# 소스 코드이다. 소스 코드 중에 진법변환에 필요한 메소드

        convertAtoI(string, radix)
        convertItoA(long, radix)

의 구현도 포함되어 있다.

/*
 *  Filename: MakeAsciiTableApp.cs
 *            Make a table of ascii codes.
 *
 *  Compile: csc MakeAsciiTableApp.cs
 *  Execute: MakeAsciiTableApp
 *
 *      Date:  2009/01/19
 *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
 */

using System;

namespace MyTestApplication1 {

    public class MakeAsciiTableApp {
        static void println(String s) {
            Console.WriteLine(s);
        }

        static void print(String s) {
            Console.Write(s);
        }

        static void PrintUsage() {
            println("Usage: MakeAsciiTableApp");
            println("Make a table of ascii codes.");
        }

        static string BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        public static string ConvertItoA(long num, int radix) {
            string tmp;
            string ret;
            string arr;
            long q, r;
            bool isNegative = false;
            if (num < 0L) {
                isNegative = true;
                num = -num;
            }
            arr = "";
            q = num;
            r = 0L;

            while (q >= (long) radix) {
                r = q % (long) radix;
                q = q / (long) radix;
                tmp = BASE36.Substring((int)r, 1);
                arr += tmp;
            }
            tmp = BASE36.Substring((int)q, 1);
            arr += tmp;
            if (isNegative) {
                arr += "-";
             }

             ret = "";
             for (int j = 0; j < arr.Length; j++) {
               ret += arr.Substring(arr.Length - j - 1, 1);
             }
             return ret;
        }

        public static long ConvertAtoI(string s, int radix) {
            long ret = 0L;
            bool isNegative = false;
            int len =s.Length;
            char c;
            int i;
            long val = 0L;

            c = s[0];
            if (c == '-') {
                isNegative = true;
            }
            else if (c >= '0' && c <= '9') {
                ret = (long) (c - '0');
            }
            else if (c >= 'A' && c <= 'Z') {
                ret = (long) (c - 'A') + 10L;
            }
            else if (c >= 'a' && c <= 'z') {
                ret = (long) (c - 'a') + 10L;
            }
            if (ret >= (long) radix) {
                Console.WriteLine("        Invalid character!");
                return ret;
            }

            for (i = 1; i < len; i++) {
                c = s[i];
                ret *= radix;
                if (c >= '0' && c <= '9') {
                    val = (long) (c - '0');
                }
                else if (c >= 'A' && c <= 'Z') {
                    val = (long) (c - 'A') + 10L;
                }
                else if (c >= 'a' && c <= 'z') {
                    val = (long) (c - 'a') + 10L;
                }
                if (val >= (long) radix) {
                    Console.WriteLine("        Invalid character!");
                    return ret;
                }
                ret += val;
            }

            if (isNegative)
             ret = -ret;
            return ret;
        }

       static string[] asc  = new string[] {
            "NUL", "SOH", "STX", "ETX", "EOT",
            "ENQ", "ACK", "BEL", "BS", "HT",
            "LF", "VT", "FF", "CR", "SO",
            "SI", "DLE", "DC1", "DC2", "DC3",
            "DC4", "NAK", "SYN", "ETB", "CAN",
            "EM", "SUB", "ESC", "FS", "GS",
            "RS", "US", "Spc"
        };

        static string[] control  = new string[] {
            "NUL (null)",
            "SOH (start of heading)",
            "STX (start of text)",
            "ETX (end of text)",
            "EOT (end of transmission)",
            "ENQ (enquiry)",
            "ACK (acknowledge)",
            "BEL (bell)",
            "BS  (backspace)",
            "TAB (horizontal tab)",
            "LF  (line feed, NL new line)",
            "VT  (vertical tab)",
            "FF  (form feed, NP new page)",
            "CR  (carriage return)",
            "SO  (shift out)",
            "SI  (shift in)",
            "DLE (data link escape)",
            "DC1 (device control 1)",
            "DC2 (device control 2)",
            "DC3 (device control 3)",
            "DC4 (device control 4)",
            "NAK (negative acknowledge)",
            "SYN (synchronous idle)",
            "ETB (end of trans. block)",
            "CAN (cancel)",
            "EM  (end of medium)",
            "SUB (substitute, EOF end of file)",
            "ESC (escape)",
            "FS  (file separator)",
            "GS  (group separator)",
            "RS  (record separator)",
            "US  (unit separator)",
        };

        public static void MakeTable() {
            string sbuf = "";
            string abuf = "";
            string tbuf = "";
            int i, j;
            char c;

            print("    ");
            for (i = 0; i < 8; i++) {
                print("+----");
            }
            print("+");
            println("");

            print("    ");
            print("| 0- ");
            print("| 1- ");
            print("| 2- ");
            print("| 3- ");
            print("| 4- ");
            print("| 5- ");
            print("| 6- ");
            print("| 7- ");
            print("|");
            println("");

            print("+---");
            for (i = 0; i < 8; i++) {
                print("+----");
            }
            print("+");
            println("");

            for (i = 0; i < 16; i++) {
                tbuf = "";
                sbuf = ConvertItoA((long) i, 16);
                tbuf += "| " + sbuf + " ";
                for (j = 0; j < 8; j++) {
                    if (j*16 + i <= 32) {
                       abuf = String.Format("| {0, -3}", asc[j*16 + i]);
                    }
                    else if (j*16 + i == 127) {
                        abuf = String.Format("| {0, -3}", "DEL");
                    }
                    else {
                        c = (char) (j*16 + i);
                        abuf = String.Format("| {0, 2} ", c);
                    }
                    tbuf += abuf;
                }
                tbuf += "|";
                println(tbuf);
            }

            print("+---");
            for (i = 0; i < 8; i++) {
                print("+----");
            }
            print("+");
            println("");
            println("");

            for (i = 0; i < 16; i++) {
                sbuf = String.Format("{0, -30}",  control[i]);
                tbuf = String.Format("  {0, -34}",  control[i+16]);
                print(sbuf);
                println(tbuf);
            }
        }

        // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
        public static void Main(string[] args) {
            if (args.Length > 0 && "-h".Equals(args[0])) {
                PrintUsage();
                Environment.Exit(1);
            }
            MakeTable();
        }
    }
}






컴파일> csc MakAsciiTableApp.cs

실행> MakeAsciiTableApp

    +----+----+----+----+----+----+----+----+
    | 0- | 1- | 2- | 3- | 4- | 5- | 6- | 7- |
+---+----+----+----+----+----+----+----+----+
| 0 | NUL| DLE| Spc|  0 |  @ |  P |  ` |  p |
| 1 | SOH| DC1|  ! |  1 |  A |  Q |  a |  q |
| 2 | STX| DC2|  " |  2 |  B |  R |  b |  r |
| 3 | ETX| DC3|  # |  3 |  C |  S |  c |  s |
| 4 | EOT| DC4|  $ |  4 |  D |  T |  d |  t |
| 5 | ENQ| NAK|  % |  5 |  E |  U |  e |  u |
| 6 | ACK| SYN|  & |  6 |  F |  V |  f |  v |
| 7 | BEL| ETB|  ' |  7 |  G |  W |  g |  w |
| 8 | BS | CAN|  ( |  8 |  H |  X |  h |  x |
| 9 | HT | EM |  ) |  9 |  I |  Y |  i |  y |
| A | LF | SUB|  * |  : |  J |  Z |  j |  z |
| B | VT | ESC|  + |  ; |  K |  [ |  k |  { |
| C | FF | FS |  , |  < |  L |  \ |  l |  | |
| D | CR | GS |  - |  = |  M |  ] |  m |  } |
| E | SO | RS |  . |  > |  N |  ^ |  n |  ~ |
| F | SI | US |  / |  ? |  O |  _ |  o | DEL|
+---+----+----+----+----+----+----+----+----+

NUL (null)                      DLE (data link escape)
SOH (start of heading)          DC1 (device control 1)
STX (start of text)             DC2 (device control 2)
ETX (end of text)               DC3 (device control 3)
EOT (end of transmission)       DC4 (device control 4)
ENQ (enquiry)                   NAK (negative acknowledge)
ACK (acknowledge)               SYN (synchronous idle)
BEL (bell)                      ETB (end of trans. block)
BS  (backspace)                 CAN (cancel)
TAB (horizontal tab)            EM  (end of medium)
LF  (line feed, NL new line)    SUB (substitute, EOF end of file)
VT  (vertical tab)              ESC (escape)
FF  (form feed, NP new page)    FS  (file separator)
CR  (carriage return)           GS  (group separator)
SO  (shift out)                 RS  (record separator)
SI  (shift in)                  US  (unit separator)



Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,

컴퓨터 프로그래밍에서 꼭 알아두어야 할 주요 진법은 당연히 10진법, 2진법, 8진법, 16진법이다.
다음은  0부터 15까지의 정수를 10진법, 2진법, 8진법, 16진법의 표로 만들어 보여주는 C# 소스 코드이다. 진법 변환에 필요한 C# 메소드로

         Convert.Int64(string str,  int radix);

가 이미 있지만, 여기에서는 아예 변환 메소드

        convertAtoI(string, radix)
        convertItoA(long, radix)

를 자체 구현하여 사용하였다.



  1. /*
  2.  *  Filename: MakeRadixTableApp.cs
  3.  *            Show the radix table with 10-, 2-, 8-, 16-radices.
  4.  *
  5.  *  Compile: csc MakeRadixTableApp.cs
  6.  *  Execute: MakeRadixTableApp
  7.  *
  8.  *      Date:  2009/01/19
  9.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  10.  */
  11. using System;
  12. namespace MyTestApplication1 {
  13.     public class MakeRadixTableApp {
  14.         static void println(String s) {
  15.             Console.WriteLine(s);
  16.         }
  17.         static void print(String s) {
  18.             Console.Write(s);
  19.         }
  20.         static void PrintUsage() {
  21.             println("Usage: MakeRadixTableApp");
  22.             println("Show the radix table with 10-, 2-, 8-, 16-radices.");
  23.         }
  24.         static string BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  25.         public static string ConvertItoA(long num, int radix) {
  26.             string tmp;
  27.             string ret;
  28.             string arr;
  29.             long q, r;
  30.             bool isNegative = false;
  31.             if (num < 0L) {
  32.                 isNegative = true;
  33.                 num = -num;
  34.             }
  35.             arr = "";
  36.             q = num;
  37.             r = 0L;
  38.             while (q >= (long) radix) {
  39.                 r = q % (long) radix;
  40.                 q = q / (long) radix;
  41.                 tmp = BASE36.Substring((int)r, 1);
  42.                 arr += tmp;
  43.             }
  44.             tmp = BASE36.Substring((int)q, 1);
  45.             arr += tmp;
  46.             if (isNegative) {
  47.                 arr += "-";
  48.              }
  49.              ret = "";
  50.              for (int j = 0; j < arr.Length; j++) {
  51.                ret += arr.Substring(arr.Length - j - 1, 1);
  52.              }
  53.              return ret;
  54.         }
  55.         public static long ConvertAtoI(string s, int radix) {
  56.             long ret = 0L;
  57.             bool isNegative = false;
  58.             int len =s.Length;
  59.             char c;
  60.             int i;
  61.             long val = 0L;
  62.             c = s[0];
  63.             if (c == '-') {
  64.                 isNegative = true;
  65.             }
  66.             else if (c >= '0' && c <= '9') {
  67.                 ret = (long) (c - '0');
  68.             }
  69.             else if (c >= 'A' && c <= 'Z') {
  70.                 ret = (long) (c - 'A') + 10L;
  71.             }
  72.             else if (c >= 'a' && c <= 'z') {
  73.                 ret = (long) (c - 'a') + 10L;
  74.             }
  75.             if (ret >= (long) radix) {
  76.                 Console.WriteLine("        Invalid character!");
  77.                 return ret;
  78.             }
  79.             for (i = 1; i < len; i++) {
  80.                 c = s[i];
  81.                 ret *= radix;
  82.                 if (c >= '0' && c <= '9') {
  83.                     val = (long) (c - '0');
  84.                 }
  85.                 else if (c >= 'A' && c <= 'Z') {
  86.                     val = (long) (c - 'A') + 10L;
  87.                 }
  88.                 else if (c >= 'a' && c <= 'z') {
  89.                     val = (long) (c - 'a') + 10L;
  90.                 }
  91.                 if (val >= (long) radix) {
  92.                     Console.WriteLine("        Invalid character!");
  93.                     return ret;
  94.                 }
  95.                 ret += val;
  96.             }
  97.             if (isNegative)
  98.                 ret = -ret;
  99.             return ret;
  100.         }
  101.         public static void MakeTable() {
  102.             string sbuf = "";
  103.             string abuf = "";
  104.             string tbuf = "";
  105.             int i;
  106.             for (i = 0; i < 4; i++) {
  107.                 print("+-------");
  108.             }
  109.             print("+");
  110.             println("");
  111.             print("|  Dec");
  112.             print("\t|   Bin");
  113.             print("\t|  Oct");
  114.             print("\t|  Hex  |");
  115.             println("");
  116.             for (i = 0; i < 4; i++) {
  117.                 print("+-------");
  118.             }
  119.             print("+");
  120.             println("");
  121.             for (i = 0; i < 16; i++) {
  122.                 sbuf = String.Format("|   {0, 2}", i);
  123.                 abuf = ConvertItoA((long) i, 2);
  124.                 tbuf = String.Format("\t|  {0, 4}", abuf);
  125.                 sbuf += tbuf;
  126.                 abuf = ConvertItoA((long) i, 8);
  127.                 tbuf = String.Format("\t|   {0, 2}", abuf);
  128.                 sbuf += tbuf;
  129.                 abuf = ConvertItoA((long) i, 16);
  130.                 tbuf = String.Format("\t|    {0, -2} |", abuf);
  131.                 sbuf += tbuf;
  132.                 println(sbuf);
  133.             }
  134.             for (i = 0; i < 4; i++) {
  135.                 print("+-------");
  136.             }
  137.             print("+");
  138.             println("");
  139.         }
  140.         // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
  141.         public static void Main(string[] args) {
  142.             if (args.Length > 0 && "-h".Equals(args[0])) {
  143.                 PrintUsage();
  144.                 Environment.Exit(1);
  145.             }
  146.             MakeTable();
  147.         }
  148.     }
  149. }



컴파일> csc MakeRadixTableApp.cs

실행> MakeRadixTableApp

+-------+-------+-------+-------+
|  Dec  |   Bin |  Oct  |  Hex  |
+-------+-------+-------+-------+
|    0  |     0 |    0  |    0  |
|    1  |     1 |    1  |    1  |
|    2  |    10 |    2  |    2  |
|    3  |    11 |    3  |    3  |
|    4  |   100 |    4  |    4  |
|    5  |   101 |    5  |    5  |
|    6  |   110 |    6  |    6  |
|    7  |   111 |    7  |    7  |
|    8  |  1000 |   10  |    8  |
|    9  |  1001 |   11  |    9  |
|   10  |  1010 |   12  |    A  |
|   11  |  1011 |   13  |    B  |
|   12  |  1100 |   14  |    C  |
|   13  |  1101 |   15  |    D  |
|   14  |  1110 |   16  |    E  |
|   15  |  1111 |   17  |    F  |
+-------+-------+-------+-------+




Creative Commons License

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,

다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 C# 소스 코드이다.

메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환의 핵심은

         public static long ConvertAtoI(string s, int radix)
         public static string ConvertItoA(long num, int radix)

의 구현과 이용이다. 지원되는 진법은 2진법부터 36진법까지이다.
C#에는 Java의 StringTokener가 구현되어 있지 않다.
그래서 Java의 StringTokener와 비슷한 C#용 StringTokener.Token이라는
클래스를 구현해 보았다.


  1. /*
  2.  *  Filename: ConvertRadixApp.cs
  3.  *            Convert radix in a interactive mode.
  4.  *
  5.  *  Compile: csc ConvertRadixApp.cs
  6.  *  Execute: ConvertRadixApp
  7.  *
  8.  *      Date:  2009/01/19
  9.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  10.  */
  11. using System;
  12. namespace StringTokenizer {
  13.     class Token {
  14.         private string data,delimeter;
  15.         private string[] tokens;
  16.         private int index;
  17.         public Token(string strdata) {
  18.             Init(strdata, " ");
  19.         }
  20.         public Token(string strdata, string delim) {
  21.             Init(strdata, delim);
  22.         }
  23.         private void Init(string strdata, string delim) {
  24.             data = strdata;
  25.             delimeter = delim;
  26.             string data2 = "";
  27.             bool isDelim = false;
  28.             String c;
  29.             for (int i = 0; i < data.Length; i++) {
  30.                 c = data.Substring(i, 1);
  31.                 if (delim.Contains(c)) {
  32.                     if (!isDelim) {
  33.                         isDelim = true;
  34.                         data2 += c;
  35.                     }
  36.                     continue;
  37.                 }
  38.                 data2 += c;
  39.             }
  40.             tokens = data2.Split(delimeter.ToCharArray());
  41.             index = 0;
  42.         }
  43.         public int Count() {
  44.             return tokens.Length;
  45.         }
  46.         public bool HasMoreTokens() {
  47.             return (index < (tokens.Length));
  48.         }
  49.         public string NextToken() {
  50.             if (index < tokens.Length) {
  51.                 return tokens[index++];
  52.             }
  53.             else {
  54.                 return "";
  55.             }
  56.         }
  57.     }
  58. }
  59. namespace MyTestApplication1 {
  60.     public class ConvertRadixApp2 {
  61.         public static void PrintUsage() {
  62.             Console.WriteLine("Usage: java ConvertRadixApp");
  63.             Console.WriteLine("Convert radix in a interactive mode, where the maximum radix is 36.");
  64.         }
  65.         public void PrintAbout() {
  66.             Console.WriteLine("    About: Convert radix in a interactive mode.");
  67.         }
  68.         public void PrintMainMenu() {
  69.             Console.WriteLine("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it");
  70.         }
  71.         public void PrintMainPrompt() {
  72.             Console.Write("  Prompt> ");
  73.         }
  74.         public void PrintSubMenu(int srcRadix, int destRadix) {
  75.             Console.WriteLine("    Convert Radix_" + srcRadix + " to Radix_" + destRadix);
  76.             Console.WriteLine("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit");
  77.         }
  78.         public void PrintSubPrompt() {
  79.             Console.Write("    Input Value>> ");
  80.         }
  81.         static string BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  82.         public static string ConvertItoA(long num, int radix) {
  83.             string tmp;
  84.             string ret;
  85.             string arr;
  86.             long q, r;
  87.             bool isNegative = false;
  88.             if (num < 0L) {
  89.                 isNegative = true;
  90.                 num = -num;
  91.             }
  92.             arr = "";
  93.             q = num;
  94.             r = 0L;
  95.             while (q >= (long) radix) {
  96.                 r = q % (long) radix;
  97.                 q = q / (long) radix;
  98.                 tmp = BASE36.Substring((int)r, 1);
  99.                 arr += tmp;
  100.             }
  101.             tmp = BASE36.Substring((int)q, 1);
  102.             arr += tmp;
  103.             if (isNegative) {
  104.                 arr += "-";
  105.              }
  106.              ret = "";
  107.              for (int j = 0; j < arr.Length; j++) {
  108.                ret += arr.Substring(arr.Length - j - 1, 1);
  109.              }
  110.              return ret;
  111.         }
  112.         public static long ConvertAtoI(string s, int radix) {
  113.             long ret = 0L;
  114.             bool isNegative = false;
  115.             int len =s.Length;
  116.             char c;
  117.             int i;
  118.             long val = 0L;
  119.             c = s[0];
  120.             if (c == '-') {
  121.                 isNegative = true;
  122.             }
  123.             else if (c >= '0' && c <= '9') {
  124.                 ret = (long) (c - '0');
  125.             }
  126.             else if (c >= 'A' && c <= 'Z') {
  127.                 ret = (long) (c - 'A') + 10L;
  128.             }
  129.             else if (c >= 'a' && c <= 'z') {
  130.                 ret = (long) (c - 'a') + 10L;
  131.             }
  132.             if (ret >= (long) radix) {
  133.                 Console.WriteLine("        Invalid character!");
  134.                 return ret;
  135.             }
  136.             for (i = 1; i < len; i++) {
  137.                 c = s[i];
  138.                 ret *= radix;
  139.                 if (c >= '0' && c <= '9') {
  140.                     val = (long) (c - '0');
  141.                 }
  142.                 else if (c >= 'A' && c <= 'Z') {
  143.                     val = (long) (c - 'A') + 10L;
  144.                 }
  145.                 else if (c >= 'a' && c <= 'z') {
  146.                     val = (long) (c - 'a') + 10L;
  147.                 }
  148.                 if (val >= (long) radix) {
  149.                     Console.WriteLine("        Invalid character!");
  150.                     return ret;
  151.                 }
  152.                 ret += val;
  153.             }
  154.             if (isNegative)
  155.                 ret = -ret;
  156.             return ret;
  157.         }
  158.         public string ConvertRadix(String s, int srcRdx, int destRdx) {
  159.             long val;
  160.             string ret = "";
  161.             try {
  162.                 val = ConvertAtoI(s, srcRdx);
  163.                 ret = ConvertItoA(val, destRdx);
  164.                 return ret.ToUpper();
  165.             }
  166.             catch (Exception nfx) { ]
  167.                 Console.WriteLine("    Error: " + nfx + " cantains some invalid character.");
  168.                 ret = "????";
  169.                 return ret.ToUpper();
  170.             }
  171.         }
  172.         public void DoConvert(int srcRadix, int destRadix) {
  173.             string cmd;
  174.             string srcStr = "", destStr = "";
  175.             Console.WriteLine();
  176.             PrintSubMenu(srcRadix, destRadix);
  177.             try {
  178.                 do {
  179.                     PrintSubPrompt();
  180.                     while ((cmd = Console.ReadLine()) == null) {
  181.                     }
  182.                     if ("main()".Equals(cmd)) {
  183.                         return;
  184.                     }
  185.                     else if ("exit()".Equals(cmd) || "quit()".Equals(cmd)) {
  186.                         Environment.Exit(0);
  187.                     }
  188.                     try {
  189.                         Convert.ToInt32(cmd, srcRadix);
  190.                         srcStr = cmd;
  191.                         destStr = ConvertRadix(srcStr, srcRadix, destRadix);
  192.                         Console.WriteLine("        ( " + srcStr + " )_" + srcRadix +  "   --->   ( " + destStr + " )_" + destRadix);
  193.                         Console.WriteLine();
  194.                     }
  195.                     catch (FormatException ex) {
  196.                          Console.WriteLine(cmd + ": " + ex);
  197.                     }
  198.                 } while (true);
  199.             }
  200.             catch (Exception ex) {
  201.                 Console.WriteLine("" + ex);
  202.             }
  203.         }
  204.         public void DoStart() {
  205.          char[] seps = { ' ', ',', '\t' };
  206.             string line;
  207.             string cmd;
  208.             int srcRadix = 10, destRadix = 10;
  209.             bool onlyOnce = true;
  210.             try {
  211.                 do {
  212.                     Console.WriteLine();
  213.                     if (onlyOnce) {
  214.                         Console.WriteLine("  The supported maximum radix is 36.");
  215.                         onlyOnce = false;
  216.                     }
  217.                     PrintMainMenu();
  218.                     PrintMainPrompt();
  219.                     while ((cmd = Console.ReadLine()) == null) {
  220.                     }
  221.                     if ("qQxX".Contains(cmd) && cmd.Length == 1) {
  222.                         Environment.Exit(0);
  223.                     }
  224.                     else if ("aA".Contains(cmd) && cmd.Length == 1) {
  225.                         PrintAbout();
  226.                     }
  227.                     else if ("sS".Contains(cmd) && cmd.Length == 1) {
  228.                         Console.Write("  Input the source and target radices (say, 16 2): ");
  229.                         line = Console.ReadLine();
  230.                         StringTokenizer.Token tok = new StringTokenizer.Token(line, " , \t");
  231.                         while (tok.Count() != 2) {
  232.                             Console.Write("  Input the source and target radices (say, 16 2): ");
  233.                             line = Console.ReadLine();
  234.                             tok = new StringTokenizer.Token(line, " , \t");
  235.                         }
  236.                         try {
  237.                             srcRadix = Convert.ToInt32(tok.NextToken());
  238.                             destRadix = Convert.ToInt32(tok.NextToken());
  239.                             DoConvert(srcRadix, destRadix);
  240.                         }
  241.                         catch (FormatException ex) {
  242.                             Console.WriteLine("" + ex);
  243.                         }
  244.                     }
  245.                 } while (true);
  246.             }
  247.             catch (Exception ex) {
  248.                 Console.WriteLine("" + ex);
  249.             }
  250.         }
  251.         // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
  252.         public static void Main(string[] args) {
  253.             if (args.Length > 0 && "-h".Equals(args[0])) {
  254.                 PrintUsage();
  255.                 Environment.Exit(1);
  256.             }
  257.             ConvertRadixApp2 app = new ConvertRadixApp2();
  258.             app.DoStart();
  259.         }
  260.     }
  261. }



컴파일> csc ConvertRadixApp.cs

실행> ConvertRadixApp

  The supported maximum radix is 36.
  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 10 16

    Convert Radix_10 to Radix_16
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 256
        ( 256 )_10   --->   ( 100 )_16

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 16 10

    Convert Radix_16 to Radix_10
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> FFFF
        ( FFFF )_16   --->   ( 65535 )_10

    Input Value>> exit()



 

Posted by Scripter
,

다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 C# 컨솔 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  Golden ratio - Sajun.org

  1. /*
  2.  *  Filename: TestGoldenRatioApp.cs
  3.  *    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  4.  *
  5.  *   Compile: csc TestGoldenRatioApp.
  6.  *
  7.  *   Execute: TestGoldenRatioApp
  8.  *
  9.  *      Date:  2009/01/16
  10.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  11.  */
  12. using System;
  13. using System.Collections.Generic;
  14. namespace MyTestApplication1 {
  15.     public class TestGoldenRatioApp {
  16.         public static void PrintUsing() {
  17.             Console.WriteLine("Using: TestGoldenRatioApp [-h|-help]");
  18.             Console.WriteLine("This calculates the value of the golden ratio.");
  19.         }
  20.         // 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  21.         public List<double> FindQuadraticRoot(double a, double b, double c) {
  22.             double x1, x2;
  23.             if (a == 0.0) {
  24.                 throw new Exception("Since the highest coefficient is zero, the given equation is not a quadratic equation.");
  25.             }
  26.             else if (b*b - 4*a*c < 0.0) {
  27.                 throw new Exception("Since the discriminant " + (b*b - 4*a*c) + " is negative, the given equation has no real root.");
  28.             }
  29.             x1 = (-b + Math.Sqrt(b*b - 4*a*c)) / (2.0 * a);
  30.             x2 = (-b - Math.Sqrt(b*b - 4*a*c)) / (2.0 * a);
  31.             List<Double> array = new List<double>();
  32.             array.Add(x1);
  33.             array.Add(x2);
  34.             return array;
  35.         }
  36.         // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
  37.         public static void Main(string[] args) {
  38.             TestGoldenRatioApp app = new TestGoldenRatioApp();
  39.             if (args.Length > 0 && (args[0].Equals("-h") || args[0].Equals("-help"))) {
  40.                 PrintUsing();
  41.                 Environment.Exit(1);
  42.             }
  43.             try {
  44.                 List<double> values = app.FindQuadraticRoot(1.0, -1.0, -1.0);
  45.                 double x1, x2;
  46.                 x1 = values[0];
  47.                 x2 = values[1];
  48.                 if (x1 >= x2) {
  49.                     Console.WriteLine("The bigger root is " + x1 + ", ");
  50.                     Console.WriteLine("and the less root is " + x2 + ".");
  51.                 }
  52.                 else {
  53.                     Console.WriteLine("The bigger root is " + x2 + ", ");
  54.                     Console.WriteLine("and the less root is " + x1 + ".");
  55.                 }
  56.             }
  57.             catch (Exception caught) {
  58.                 Console.WriteLine("" + caught);
  59.             }
  60.         }
  61.     }
  62. }



컴파일> csc TestGoldenRatioApp.cs

실행> TestGoldenRatioApp
The bigger root is 1.618033988749895,
and the less root is -0.6180339887498949.




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

Posted by Scripter
,
현재 시각을 컨솔에 보여주는 간단한 애플리케이션의 C# 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)


  1. /*
  2.  *  Filename: TestCTimeApp.cs
  3.  *
  4.  *  Compile: csc TestCTimeApp.cs
  5.  *
  6.  *  Execute: TestCTimeApp
  7.  */
  8. using System;
  9. namespace MyTestApplication1 {
  10.     public class TestCTimeApp {
  11.         static string[] weekNames = {
  12.                       "일", "월", "화", "수", "목", "금", "토"
  13.                   };
  14.         // Java 언어의 main 메소드에 해당하는 C# 언어의 Main 메소드
  15.         public static void Main(string[] args) {
  16.             DateTime now = DateTime.Now;
  17.             DateTime StartOfEpoch = new DateTime(1970, 1, 1);
  18.             // 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  19.             Console.WriteLine("UTC: " + (long) ((DateTime.UtcNow - StartOfEpoch).TotalMilliseconds / 1000L));
  20.             // 현재 시각 표시: 20xx년 xx월 xx일 (x요일) xx시 xx분 xx초
  21.             Console.Write(now.Year + "년 ");
  22.             Console.Write(now.Month + "월 ");   // Not 1 + now.Month !!
  23.             Console.Write(now.Day + "일 ");
  24.             Console.Write("(" + weekNames[(int) now.DayOfWeek] + "요일) ");
  25.             Console.Write(now.Hour + "시 ");
  26.             Console.Write(now.Minute + "분 ");
  27.             Console.WriteLine(now.Second + "초");
  28.             // 1월 1일은 1, 1월 2일은 2
  29.             Console.Write("올해 몇 번째 날: " + now.DayOfYear + ", ");
  30.             // True 이면 서머타임 있음
  31.             Console.WriteLine("서머타임 적용 여부: " + (! now.IsDaylightSavingTime() ? "안함" : "함"));
  32.         }
  33.     }
  34. }



컴파일> csc TestCTimeApp.cs

실행> TestCTimeApp
UTC: 1206323913초
2008년 3월 24일 (화요일) 10시 58분 33초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함




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

Posted by Scripter
,