using System;

public class 이진검색
{
    public static void Main(string[] args)
    {
        //[1] Input
        int[] data = { 1, 3, 5, 7, 9 }; //[!] 오름차순 정렬되었다고 가정하고...
        Console.WriteLine("찾을 데이터 : ");
        int search = Convert.ToInt32(Console.ReadLine());
        bool flag = false; // 찾았으면 true 그렇지 않으면 false
        int index = -1; // 찾은 위치
        int low = 0; int mid = 0; int high = 0; // 이분탐색 관련 변수
        low = 0; high = data.Length - 1;
        //[2] Process
        #region 순차검색
        for (int i = 0; i < data.Length; i++)
        {
            if (data[i] == search)
            {
                flag = true;
                index = i;
            }
        }
        #endregion

        while (low <= high)
        {
            mid = (low + high) / 2; // 중간값(검색할 데이터)
            if (data[mid] == search)
            {
                flag = true; index = mid; break;
            }
            if (data[mid] < search)
            {
                low = mid + 1;
            }
            else
            {
                high = mid - 1;
            }
        }

        //[3] Output
        if (flag)
        {
            Console.WriteLine("{0}를 {1}위치에서 찾았습니다.", search, index);
        }
        else
        {
            Console.WriteLine("찾지 못했습니다.");
        }
    }
}

'.NET프로그래밍 > C# 3.5 SP1' 카테고리의 다른 글

53. 대리자(Delegate)  (0) 2009.08.13
알고리즘 - 11. 병합정렬(Merge)  (0) 2009.08.13
52. 정수형인덱서와 문자열인덱서  (0) 2009.08.13
51. 인덱서(Indexer)  (0) 2009.08.13
50. 속성(Property)  (0) 2009.08.13
Posted by holland14
:

==> 인덱서.cs


using System;

public class 인덱서
{
    public static void Main()
    {
        //[1] 레코드 생성
        Record r = new Record();

        //[2] 데이터 저장
        r.SetNum(1);
        r.SetName("홍길동");

        //[3] 데이터 출력
        Console.WriteLine(r.GetData(1)); // 홍길동
        Console.WriteLine(r[1]); // 홍길동
        Console.WriteLine(r["Name"]); // 홍길동
    }
}



==============================================================================================



==> Record.cs


using System;
using System.Collections;

public class Record
{
    private int num;
    private string name;
    private Hashtable data = new Hashtable();
    public void SetNum(int num)
    {
        this.num = num; // 1이 저장
        data["Num"] = num;
    }

    public void SetName(string name)
    {
        this.name = name; // 홍길동
        data["Name"] = name;
    }

    public string GetData(int index)  // 메서드
    {
        if (index == 0)
        {
            return this.num.ToString();
        }
        else
        {
            return this.name;
        }
    }

    public string this[int index]  // 정수형인덱서
    {
        get { return GetData(index); }
    }

    public string this[string index]  // 문자열인덱서
    {
        get { return Convert.ToString(data[index]); }
    }
}

Posted by holland14
:

==> 인덱서.cs


using System;

public class 인덱서
{
    public static void Main()
    {
        #region Car
  Car hyundai = new Car(3);
        hyundai[0] = "에쿠스";
        hyundai[1] = "소나타";
        hyundai[2] = "산타페";

        for (int i = 0; i < hyundai.Length; i++)
        {
            Console.WriteLine(hyundai[i]);
        }
 #endregion

        Person saram = new Person();
        // 문자열 인덱서
        saram["닉네임"] = "RedPlus";
        saram["주소"] = "Incheon";
        Console.WriteLine(saram["닉네임"]);
        Console.WriteLine(saram["주소"]);
    }
}



==============================================================================================


==> Car.cs


using System;
//[1] Class
public class Car
{
    //[2] Property
    public int Length { get; set; }

    //[3] Constructor
    public Car()
    {
        // Empty
    }

    public Car(int length)
    {
        this.Length = length;
        catalog = new string[length]; // 요소수 생성
    }

    //[4] Field
    private string[] catalog; // 배열 생성
   

    //[5] Indexer
    public string this[int index]
    {
        get { return catalog[index]; }
        set { catalog[index] = value; }
    }

}



==============================================================================================



==> Person.cs


using System;
using System.Collections;

public class Person
{
    //[1] 문자열 인덱서
    public string this[string index]
    {
        get { return (string)names[index]; }
        set { names[index] = value; }
    }

    //[2] Key/Value 저장 필드
    Hashtable names = new Hashtable();
}

Posted by holland14
:

==> 속성.cs


using System;

public class 속성
{
    public static void Main()
    {
        #region Car 클래스
        Car sonata = new Car();

        sonata.Name = "소나타";
        sonata.Color = "Red"; // set

        Console.WriteLine(sonata.Color); // get

        sonata.Run(); // Red/소나타
        #endregion

        Person na = new Person();
        na.Name = "홍길동";
        na.Birth = "1988-02-05";
        Console.WriteLine(na.Age); // 22

    }
}


==============================================================================================


==> Car.cs


using System;

public class Car
{
    private string _Name; // 필드
    public string Name // 속성
    {
        get { return _Name; }
        set { _Name = value; }
    }

    private string _Color;// 필드
    public string Color // 속성
    {
        get { return _Color; }
        set { _Color = value; }
    }

    public void Run()
    {
        Console.WriteLine("{0},{1}", _Name, Color);
    }

}


==============================================================================================


==> Person.cs


using System;

public class Person
{  
    // 2.0까지
    private string _Name;
    public string Name
    {  
        get { return _Name; }
        set { _Name = value; }
    }

   
    // 쓰기 전용 생성 : 추가 로직
    private string _Birth;
    public string Birth
    {
        set
        {
            _Birth = value; // 넘겨온 값을 필드에 셋팅
            Age = DateTime.Now.Year - Convert.ToDateTime(value).Year + 1;
        }
    }

    // 3.5부터 : prop
    public int Age { get; set; }
   
}

 

/*
 - private한 필드를 public속성으로 외부에 공개
 - value는 넘겨온 값을 의미한다.
*/

Posted by holland14
:

using System;

// Overload : 다중정의(여러번 정의) <-> Override : 재 정의(다시 정의)
public class 메서드오버로드
{
    public static void Main()
    {
        Sum(100); // 1~100까지 합
        Sum(10, 20); // 10~20까지 합
        Sum(1, 100, 2); // 1~100까지 2의 배수(짝수)의 합
    }

    private static void Sum(int p, int p_2, int p_3)
    {
        int sum = 0;
        for (int i = p; i <= p_2; i++)
        {
            if (i % p_3 == 0)
            {
                sum += i;
            }
        }
        Console.WriteLine(sum);
    }

    private static void Sum(int p, int p_2)
    {
        int sum = 0;
        for (int i = p; i <= p_2; i++)
        {
            sum += i;
        }
        Console.WriteLine(sum);
    }

    private static void Sum(int p)
    {
        int sum = 0;
        for (int i = 1; i <= p; i++)
        {
            sum += i;
        }
        Console.WriteLine(sum);
    }
   
}

'.NET프로그래밍 > C# 3.5 SP1' 카테고리의 다른 글

51. 인덱서(Indexer)  (0) 2009.08.13
50. 속성(Property)  (0) 2009.08.13
47. 메서드(Method)  (0) 2009.08.12
46. 소멸자(Destructor)  (0) 2009.08.11
45. 생성자(Constructor)  (0) 2009.08.11
Posted by holland14
:

using System;

public class 메서드
{
    public static void Main()
    {
        int a = 10;
        int b = 20;
        int c; // 초기화하지 않음 => 어차피 Test에 의해서 초기화 된다면 그 시간도 아끼겠다...

        Test(a, ref b, out c);
        Console.WriteLine("메인 : a : {0}, b : {1}, c : {2}", a, b, c); // 10, 200, 300

        // 매개변수로 단일데이터 넘겼을때
        TestParams(10); // 값 설정
        int[] data = { 10, 20 }; TestParams(data); // 배열 설정
        TestParams(new int[] { 10, 20, 30 }); // 참조 설정

        // 매개변수로 가변데이터 넘겼을때
        TestParams(10, 20); TestParams(10, 20, 30); TestParams(10, 20, 30, 40);
       

    }

    public static void TestParams(params int[] arr)
    {
        foreach (int item in arr)
        {
            Console.WriteLine("{0}", item);   
        }
    }

    public static void Test(int a, ref int b, out int c)
    {
        a = 100; b = 200;
        c = a + b; // c를 할당
        Console.WriteLine("테스트 : a : {0}, b : {1}, c : {2}" , a, b, c); // 100, 200, 300
    }
}

Posted by holland14
:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function ChangeStyle() {
            var div1 = document.getElementById("myLayer");
            div1.style.backgroundColor = "Yellow";
            div1.style.border = "1px solid red";
            div1.style.fontSize = "30pt";
        }
       
        function GoGo(flag) {
            var div1 = document.getElementById("myLayer");
            if (flag == -1) {
                div1.style.left = (parseInt(div1.style.left) - 10) + "px";
            }
            else {
                div1.style.left = (parseInt(div1.style.left.replace("px","")) + 10) + "px";
            }
        }
        // 함수를 만드는 또 다른 모양?
        var $ = document.getElementById; // 축약표시, AJAX, jQuery, prototype에서  많이 쓴다.
        ShowLayer = function() {
            var objLayer = document.getElementById("myLayer");
            // 보이면 숨기고, 안 보이면 보여라... toggle
            if (document.getElementById("myLayer").style.visibility == "visible") {
                $("myLayer").style.visibility = "hidden";
                objLayer.style.display = "none" // 영역자체를 없앰
            }
            else {
                $("myLayer").style.visibility = "visible";
                objLayer.style.display = "block"; // 영역보이기
            }
        };
   
    </script>
</head>
<body>

    <div id="myLayer" style="position:absolute;top:100px;border:1px solid black;left:100px;width:200px;height:50px;visibility:visible;">
    안녕하세요.
    </div>
    <input type="button" value="레이어 스타일 변경" onclick="ChangeStyle();" />
    <input type="button" value="왼쪽으로" onclick="GoGo(-1);" />
    <input type="button" value="오른쪽으로" onclick="GoGo(1);" />
    <a href="#" onclick="ShowLayer();">보이기/숨기기(토글)</a>
   
    <hr />
    <script>
        function ChangeSize(num) {
            var content = document.getElementById("txtContent");
            content.style.height =
            (parseInt(content.style.height.replace("px", "")) + num) + "px";
        }
    </script>
    <a href="#" onclick="ChangeSize(10);">[+ 증가]</a>
    <a href="#" onclick="ChangeSize(-10);">[- 감소]</a><br />
    <textarea id="txtContent" cols="40" rows="4" style="height:100px;"></textarea>

</body>
</html>

Posted by holland14
:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function CheckSelect() {
            if (document.getElementById("lstFavorite").selectedIndex == 0) {
                alert("관심사항을 선택하시오.");
                document.getElementById("lstFavorite").focus();
            }
            else {
                window.alert("당신의 관심사항 : " + document.getElementById("lstFavorite").value);
            }
        }   
    </script>
</head>
<body>
    관심사항<br />
    <select id="lstFavorite">
        <option value="">- 선택 -</option>
        <option value="C#">C#</option>
        <option value="ASP.NET">ASP.NET</option>
        <option value="Sliverlight">Silverlight</option>
    </select>

    <input type="button" value="확인" onclick="CheckSelect();" />
</body>
</html>

Posted by holland14
:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function CheckAgree() {
            // 체크박스가 체크되었는지 확인
            if (document.getElementById("chkAgree").checked) {
                return true; // Summit 진행
            }
            else {
                alert("동의하셔야합니다.");
                document.getElementById("chkAgree").focus(); //
                return false; // onsubmit 이벤트 중지
            }

        }

        function SetDis() {
            document.getElementById("btnSubmit").disabled =
                    !document.getElementById("chkAgree").checked;
        }
    </script>
</head>
<body>
    <form id="Frm" name="frm" action="LoginProcess.aspx" method="post" onsubmit="return CheckAgree();">
        약관에 동의하시겠습니까?
        <input type="checkbox" id="chkAgree" onclick="SetDis();" /> 동의함
        <input type="submit" id="btnSubmit" value="회원가입페이지로 이동" />
    </form>
   
    <script>
        // 기본값으로 버튼 비활성화
        document.getElementById("btnSubmit").disabled = true; // 비활성화
    </script>

</body>
</html>



==============================================================================================


==> LoginProcess.aspx


<%@ Page Language="C#" %>

<%
    Response.Write(String.Format("아이디 : {0}<br />암호 : {1}<br />"
        , Request["txtUID"], Request["txtPwd"]));
 %>
 <input type="button" value="뒤로" onclick="history.go(-1);" />

Posted by holland14
:

==> 폼.htm


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>입력 값에 대한 유효성 검사</title>
    <script type="text/javascript">
        function CheckForm() {
            // 아이디 텍스트박스 객체 가져오기
            var txtUID = window.document.LoginForm.txtUID; // 고전방식
            // 체크
            if (txtUID.value == "") {
                window.alert("아이디를 입력하세요.");
                txtUID.focus(); // 해당 컨트롤에 포커스
                return false; // 현재 함수 멈춤
            }

            // 암호 텍스트박스 체크 : 길이
            var txtPwd = document.getElementById("txtPwd"); // 추천방식
            if (txtPwd.value.length < 3 || txtPwd.value.length > 12) {
                alert("암호를 3자 이상 12자 이하로 입력하시오.");
                txtPwd.focus();
                txtPwd.select(); // 선택:블록씌우기
                return false;
            }
            window.document.LoginForm.action = "LoginProcess.aspx"; // 동적변경
            window.document.LoginForm.submit(); // 폼 내용 전송
        }
    </script>
</head>
<body>
    <form id="LoginForm" name="LoginForm" action="LoginProcess.aspx" method="post">
        <table border="1" width="400">
            <tr>
                <td>아이디 : </td>
                <td><input type="text" id="txtUID" name="txtUID" /></td>
            </tr>
            <tr>
                <td>암호 : </td>
                <td><input type="text" id="txtPwd" name="txtPwd" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="button" value="로그인" onclick="CheckForm();" /></td>
            </tr>

        </table>
    </form>

</body>
</html>


==============================================================================================


==> LoginProcess.aspx


<%@ Page Language="C#" %>

<%
    Response.Write(String.Format("아이디 : {0}<br /> 암호 : {1}<br />"
        , Request["txtUID"], Request["txtPwd"]));
 %>
 <input type="button" value="뒤로" onclick="history.go(-1);" />

'.NET프로그래밍 > JavaScript 1.2' 카테고리의 다른 글

29. 드롭다운리스트체크(selectedIndex 사용)  (0) 2009.08.11
28. 폼(form)객체 - 2  (0) 2009.08.11
26. 히스토리(history) 객체  (0) 2009.08.11
25. 로케이션객체  (0) 2009.08.10
24. 도큐먼트객체  (0) 2009.08.10
Posted by holland14
: