블로그 이미지
Leeway is... the freedom that someone has to take the action they want to or to change their plans.
maetel

Notice

Recent Post

Recent Comment

Recent Trackback

Archive

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
  • total
  • today
  • yesterday

Category

2008. 3. 27. 17:25 @GSMC/정문열: Generative Art
2008-03-27 나무 @504

(1) Tree of Exp
(2) Randomization ( tree의 leaf들을 random하게 selection한다.)
(3) Mutation & Cross-over


randomization

uniform distribution 균등 분포
: 각각이 선택될 확률이 동일
http://en.wikipedia.org/wiki/Uniform_distribution_%28discrete%29

ref. http://en.wikipedia.org/wiki/Probability_distribution


standard normal distribution
http://en.wikipedia.org/wiki/Standard_distribution
(그림)
각각의 op가 선택될 확률은 다르나, 모두 합치면 1이 된다.

(각 op가 뽑힐 확률은 지정해 둔다.)
selection을 (충분히 많이) 무한 번 반복하면 각 op가 가지는 확률을 알 수 있다.

tree 1과 tree 2를 교배시켜 새로운 tree 3을 생성할 때,
각 tree 1과 tree 2의 요소(node)가 변이(mutation)을 일으킬 수 있다.



mutation

tree의 각 node에서 mutation이 일어날 확률을(여부를) 계산(선택)한다.
즉, 각 node마다 mutation probability를 가진다.
(그림)



cross-over

(그림)

(1/2)*(1/2) = 1/4
그러나 (유전자 쌍의 동일한 위치에서 일어나는) cross-over 때문에 매번 다른 유전자를 지닌 자식이 나온다. => "phenotype"
대응되는 node끼리 교배 -> 우열 등의 규칙은 임의로 결정

(그림)


tree 하나를 염색체 하나로 보고 유전 법칙을 적용하자.
염색체가 (이중나선 DNA)쌍으로 존재하듯, 염색체 한 쌍을 보유하는 개체 하나 당 tree 2개로 구성되어 있다고 본다.
교배는 이 개체와 다른 개체, 즉 총 4개의 tree가 mutation, cross-over 수반한 교배를 한다.
이렇게 생성된 evolved 이미지에 criteria를 적용하여 적자생존의 법칙처럼 적당한 이미지가 걸러지도록 한다.



"random 함수는 동일한 확률 분효를 가진다."

(그림)



'@GSMC > 정문열: Generative Art' 카테고리의 다른 글

Class와 Object  (0) 2008.04.14
[이선애] study 1  (0) 2008.03.28
tree (data structure)  (0) 2008.03.24
class 3/20  (0) 2008.03.20
references for basic programming  (0) 2008.03.17
posted by maetel


strcmp
Compare two strings
Returns an integral value indicating the relationship between the strings:
A zero value indicates that both strings are equal.
A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.


printf format tags
%[flags][width][.precision][length]specifier



atoi
Convert string to integer
On success, the function returns the converted integral number as an int value.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX or INT_MIN is returned.



StudentRecord record[NStudent];

StudentRecord *record;
StudentRecord *record_c;

record = new StudentRecord[NStudent];

// C++ version of allocating a memory block

record_c = (StudentRecord *) malloc (sizeof(StudentRecord)*NStudent);
// C version of allocating a memory block
// void * malloc ( size_t size );



malloc
Allocate memory block

ref.   Dynamic Memory Allocation: new and delete (C++)



"NUL indicates end-of-string." (교재 65쪽)


memcpy
서 교수님:
두 개의 struct type 데이터에 대해서, A = B;라고 하여 B를 A에 assign 하는 경우 대부분은 성립합니다. 그러나, struct 내부에서 배열을 가지고 있는 경우에는 그렇지 않습니다. 그래서 memcpy() 라는 함수를 사용하여 메모리를 블럭 단위로 카피하는 방법이 있습니다. 이는 음악 CD나 DVD 의 바이너리 카피를 만드는 것과 같은 이치입니다.




posted by maetel
Steve Oualline
Practical C Prgoramming
6. Decision and Control Statements


calculations, expressions, decision and control statements

control flow
linear programs
branching statements (cause one section of code to be executed or not executed, depending on a conditional clause)
looping statements (are used to repeat a section of code a number of times or until some condition occurs)


if Statement


if (condition)
    statement;

relational operator

"According to the C syntax rules, the else goes with the nearest if."


KISS principle (Keep It Simple, Stupid)
: We shoud write code as cleary and simply as possible.

"By adding an extra set of braces, we improve readability, understanding, and clarity."



strcmp
Compare two strings
: The function compare two strings, and then returns zero if they are equal or nonzero if they are different.
: This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminanting null-character is reached.
: Returns an integral value indicating the relationship between the strings: A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.


Looping statements
while statement

while (condition)
    statement;

The program will repeatedly execute the statement inside the while until the condition becomes false (0).

the Fibonacci numbers    (피보나치 수, 한글 위키백과)


break statement
Loops can be exited at any point through the use of a break statement.


continue statement

"Programs should be clear and simple and should not hide anything."




'@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

[Steve Oualline] 7. Programming Process  (0) 2008.04.05
week 4 review  (0) 2008.03.27
week 3 review  (0) 2008.03.22
[Steve Oualline] 5. Arrays, Qualifiers, and Reading Numbers  (0) 2008.03.16
hw2  (0) 2008.03.15
posted by maetel
2008. 3. 24. 15:09 @GSMC/정문열: Generative Art

data structure

ref.
http://www.webopedia.com/TERM/d/data_structure.html

In programming, the term data structure refers to a scheme for organizing related pieces of information. The basic types of data structures include:
  • files
    • lists
  • arrays
  • trees
  • Each of these basic structures has many variations and allows different operations to be performed on the data.


    ref.
    http://en.wikipedia.org/wiki/Data_structure

    ref.
    http://cplusplus.com/doc/tutorial/structures.html




    tree structure


    사용자 삽입 이미지

    ref.
    http://www.webopedia.com/TERM/T/tree_structure.html

    ref.
    Steve Oualline, Practical C Programmin, 292-293p

    root
    node
    leaves

    "Recursion is extremely useful with trees. Our rules for recursion are:
    1. The function must make things simpler. This rule is satisfied by trees, because as you descend the hierarchy there is less to search.
    2. There must be some endpoint. A tree offers two endpoints, either you find a match, or you reach a null node.




    ref.
    http://en.wikipedia.org/wiki/Tree_%28data_structure%29


    binary search tree
    http://en.wikipedia.org/wiki/Binary_search_tree



    Eric F Charlton : Tree Data Structures


    '@GSMC > 정문열: Generative Art' 카테고리의 다른 글

    [이선애] study 1  (0) 2008.03.28
    class 3/27  (0) 2008.03.27
    class 3/20  (0) 2008.03.20
    references for basic programming  (0) 2008.03.17
    Inversion Method  (0) 2008.03.08
    posted by maetel


    Read a file and see the ascii code.
    ref. http://www.asciitable.com/

    cstdio (stdio.h)
    C library to perform Input/Output operations

    FILE
    Object containing information to control a stream

    fgetc

    Get character from stream

    feof
    Check End-of-File indicator


    (char)

    fopen

    fclose

    EOF (End-Of-File)
    the value returned by several <cstdio> functions to indicate failure, either because the End-of-File has been reached in a reading operation or because an error happened.



    Usage of memcpy function in <string.h>
    void * memcpy (void * destination, const void * source, size_t num);
    struct
        ref. Cprogramming.com Tutorial: Structures


    size_t
    Unsigned integral type
    : the integral data type returned by the language operator sizeof and is defined in the <cstddef> header file (among others) as an unsigned integral type
    : It expresses a size or count in bytes.

    strcpy


    memcpy
    Copy block of memory


    sizeof



    Xcode 실행 결과:
    Student: Hong Gil-Dong A: 38 W: 72.0
    Student: Hong Gil-Dong A: 38 W: 72.0
    \277\377\3660\217\341SH\277\377\366\200\277\377\367�ď\344<\\277\377\366\240���P�����\377\377\217\345&(��������\277\377\366\300�����0\360\220\325ܿ\377\367�\277\377\367�\214\217\341SH\277\377\366\360����\217\341Vp\217\345\305h�\340���P���\217\340V \277\377\366\360\277\377\367�\217\340Vt\217\345�\277\377\367���q
    \331��q
    \331H���\247!\340�����������\217\345\305h\217\345\305h�\340���P���\217\340\271\364\277\377\367P���P\217ຼ\217\340\250\360\277\377\367PD��"�\340��q
    \331H�����\340\227!\340\227!\340���\247!\340���\277\377\370����\217\345\305h�\340��q
    \331]\277\377\370�\217\340\333\277\377\370�$��"\217\340\334ܧ\230\200�����0��\217\345\305h��B��"\217\342Nd\217\3406\200����\247\230�\200�\204�\204rs/l��q
    \331��q
    \331\372-2/build/Deb��������������������\227!\340\227!\340\277\377\370\260\240�\234\247!\340�������\277\377\370�\217\345?����/����\277\377\370\270��\306T��\277\377\370\200�\240\217\345\305h\217\341\374\277\377\370\200"�(\217\341Ts3-2.ob�\247\230�\340\217\340\217<\277\377\370\220D��"�\340\220︿\377\370\240���P\220�L\217\345\305h\277\377\370\260\277\377\371��\303\357����������\260h\217\345\305h��\260h\277\377\370\320��\306T��\364\217\341\374\277\377\370\360\240�\324܏\341
    \214\220\324\314������\2520\277\377\372\344\277\377\371X\277\377\372\350\217\3451��\340\217\3401�\277\377\371 �6\350\217\345/\220���\217\345/\220����\340\217\340/\220\277\377\3710�\340\217\34004\217\345V\220����\240���\217\340V\220\277\377\371P����\217\340WH������������\277\377\372\344\277\377\372\360\277\377\372\350����\277\377\372\344\277\377\372\360\277\377\371\200\240�\333H�6\350\220\333H\277\377\371\200����\220�L\277\377\372\360\277\377\372\350���\277\377\372\360��.\344\277\377\371\340����\217\341V\330�6\350�������\277\377\372\344\277\377\372\360\277\377\372\350�\214�6\350\220\333H\277\377\371\340\220\351\220ۤ��\2520�7\330����6\320�������\220�\360��������������������������������\277\377\372\344\277\377\372\360\277\377\372\350���\277\377\372\360��.\344\277\377\372@\277\377\372\350��/��\251\376\376\376\377\200\200\200\200�����������q\376\376\377���\217\340r\244��������\217\340s��������StudentRecord=136
    double=8, float=4, int=4, char=1

    shell 실행 결과:
    Student: Hong Gil-Dong A: 38 W: 72.0
    Student: Hong Gil-Dong A: 38 W: 72.0
    #[p#####C<##SH###H##~0##~0##############^$###0#######0##^$#####^###H##C<##SH###H###\##~0#L##########################^$####0p##^L##V#######WH#########h###T##########################0p######h0####0(####0##V####@####d###h##~0##~0##~0##~0###0$"#########p###0#####0p###h0####0(#####0
                                           x(܏########"######h##
    T#####SH##########SH#######X)@##<\#########h####0 ###P)##SH####M#0####@0p###h########(##T###r###/###/#############0##04000pM#l#######0p##
    ###V###########h##r##h#######x#L##:p#####V#0p##V####0###r##h###P##,h#ď##h###`##########`######h###pп######h##V##!D#######h###p#########h### D#######h##r#-X#######q#####r###sStudentRecord=136
    double=8, float=4, int=4, char=1



    An example of how to use struct in C++ programming
    algorithm


    struct

    FileIn.is_open

    FileIn.getline
    http://cplusplus.com/reference/iostream/fstream/

    FileIn.close

    strcpy

    sscanf


    console:
    ------------------------------------------------------
     1  Name:   Peter Pan           Age:  7 W: 23.8
     2  Name: Nine-tails Fox        Age: 999        W: 50.0
     3  Name:  Genius Babo  Age: 31 W: 80.8
     4  Name: Sleepless Turandot            Age: 21 W: 48.0
     5  Name: Choon-Hyang Sung      Age: 16 W: 42.0



    '@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

    week 4 review  (0) 2008.03.27
    [Steve Ouallline] 6. Decision and Control Statements  (0) 2008.03.25
    [Steve Oualline] 5. Arrays, Qualifiers, and Reading Numbers  (0) 2008.03.16
    hw2  (0) 2008.03.15
    week 2 review  (0) 2008.03.15
    posted by maetel
    2008. 3. 20. 17:17 @GSMC/정문열: Generative Art
    2008-03-20 나무 @504


    random

    uniform distribution
    http://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29

    standard normal distribution 정규 분포
    http://en.wikipedia.org/wiki/Standard_distribution

    cf. http://en.wikipedia.org/wiki/Uniform_distribution_%28ecology%29



    VarX: [-1, 1] * [-1, 1] -> [-1, 1]
    VarY

    VarX (x,y) = ( R(x,y), G(x,y), B(x,y) )  <- 이미지


    normalization

    -1 <= {R, G, B} <= 1

    cf. (-1,1)로 하면 (0,1)일 때보다 조작의 가능성이 높아진다

    R, G, B: 8bits => (0,0,0) ~ (255,255,255)




    '@GSMC > 정문열: Generative Art' 카테고리의 다른 글

    class 3/27  (0) 2008.03.27
    tree (data structure)  (0) 2008.03.24
    references for basic programming  (0) 2008.03.17
    Inversion Method  (0) 2008.03.08
    Monte Carlo method + random sampling  (0) 2008.03.08
    posted by maetel
    2008. 3. 17. 22:20 @GSMC/정문열: Generative Art

    '@GSMC > 정문열: Generative Art' 카테고리의 다른 글

    tree (data structure)  (0) 2008.03.24
    class 3/20  (0) 2008.03.20
    Inversion Method  (0) 2008.03.08
    Monte Carlo method + random sampling  (0) 2008.03.08
    week 1 review  (0) 2008.03.08
    posted by maetel
    Steve Oualline
    Practical C Programming

    5. Arrays, Qualifiers, and Reading Numbers


    An array is a set of consecutive memory locations used to store data. Each item in the array is called an element. The number of elements in an array is called the dimension of the array.
    To reference an element of an array, you use a number called the index -- the number inside the square brackets.



    Strings are sequences of characters. Strings are just character arrays with a few restrictions.

    \0


    strcpy(string1, string2)
    Copy string

    variable-length strings


    strcat(string1, string2)
    Concatenate strings
    : to add a space


    strlen(string)
    Get string length


    strcmp(string1, string2)
    Compare two strings


    fgets
    Get string from stream
    fgets (name, sizeof (name), stdin);
    cf. Chapter 14. File Input/Output


    sizeof (name)

    stdin
    standard input stream


    '\n'
    newline

    '\0'
    end-of-line



    Multidimensional Arrays

    type variable[size1][size2];


    printf

    scanf
    Read formatted data from stdin

    fgets

    sscanf
    Read formatted data from string
    : string scanf


    C lets you give detailed information about how the hardware is to be used.    - 75p

    Types of Integers
    %hd
    signed short int

    %d
    signed int

    %ld
    signed long int

    %hu
    unsigned short int

    %u
    unsigned int

    %lu
    unsigned long int


    Types of Floats
    %f
    float (printf only)

    %lf
    double (scanf only)

    %Lf
    long doubel (not available on all compilers)



    Side Effects
    A side effect is an operation that is performed in addition to the main operation executed by the statement.




    '@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

    [Steve Ouallline] 6. Decision and Control Statements  (0) 2008.03.25
    week 3 review  (0) 2008.03.22
    hw2  (0) 2008.03.15
    week 2 review  (0) 2008.03.15
    [Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
    posted by maetel

    hw2

    1. 주어진 데이터를 내림차순으로 정렬하는 프로그램을 작성하시오.
    2. 주어진 데이터를 오름차순으로 정렬하는 프로그램을 작성하시오.

    붉은 줄을 빼 먹는 바람에... ㅡㅜ 일일이 써 봄.
    /*    
       int n;
       int s;
       int k;
       for (n=0; n<20; n++){
           s = number[n];
           for(i=n; i<20; i++){
               if(s>number[i]){
                   k = s;
                   s = number[i];
                   number[i] = k;
               }
            number[n] = s;
           cout << number[n] << " : ";
           }        
       }
       for (i=0; i<20; i++)
       cout << number[i] << "<";
    */



     less = number[0];
        for (i=0; i<20; i++)
            if(less>number[i]){
                k = less;
                less = number[i];    
                number[i] = k;
            }
        cout << "less: " << less << endl;

        number[0] = less;
        cout << "number[0]= " << number[0] << endl;    

        less = number[1];
        for (i=1; i<20; i++)
            if(less>number[i]){
                k = less;
                less = number[i];
                number[i] = k;
            }
    //    k = number[1];
        number[1] = less;
    //    less = k;
        cout << "number[1]= " << number[1] << endl;
        
        
        less = number[2];
        for (i=2; i<20; i++)
            if(less>number[i]){
                k = less;
                less = number[i];
                number[i] = k;
            }
        number[2] = less;
        cout << "number[2]= " << number[2] << endl;
     
        
        less = number[3];
        for (i=3; i<20; i++)
            if(less>number[i]){
                k = less;
                less = number[i];
                number[i] = k;
            }
        number[3] = less;
        cout << "number[3]= " << number[3] << endl;

    그렇다. 난 이 코드가 대단히 비효율적이라는 것 때문에 괴로웠다. 비효율적이라기보다는 하지 않아도 되는 일을 쓸데없이 시키고 있지 않은가. 처음 숙제를 시작할 때부터 알고 있었던 사실이었다. 분명 방법이 있다는 것을 느끼면서도, 무슨 수를 써도 어쩔 수 없어 결국 for 구문 아래에서 swapping을 해야 했던 이유는, index를 기준으로 접근했을 때에는 index를 swapping해야 한다고만 생각하고, element를 기준으로 접근했을 때에는 element의 value를 swapping해야 한다고만 생각했기 때문이었다. 하지만 index를 swapping하자니 for 구문 아래에서 에러가 나고, value를 찾은 다음에는 해당 index를 for 구문 밖으로 빼낼 방법이 없고. 아예 전체 index에 대한 ghost index(?) 같은 걸 만들어야 하나 해서 심지어 실행해 옮기기까지 했던 왕삽질을 거듭했다.

    사고에도 시각의 맹점 같은 게 있는 것 같다. 뭔가 있다는 것을 알면서도 죽어도 그게 보이지 않는, 죽어도 그게 생각나지 않는. 결과만 나오면 뭐 하나? 내게 코딩은 수단이지 결코 목적이 아닌 것을. 학교에 온 이유는 여기까지 왔을 때, 사고의 맹점에 다달았을 때, 더 이상 혼자 힘으로는 갈 수가 없다는 것을 수없이 느꼈기 때문이었다. 이런 건 책이나 인터넷 포럼 같은 곳에 나와 있는 것도 아니다. (이 문제는 초보 예제니까 나와 있을지도 모르겠지만. 이 문제가 문제가 아니라 사고력이 문제인 것이다.) 컴퓨터 공학을 전공한 사람이나 직업 프로그래머라고 해서 실마리를 주는 것도 아니었다. 내가 뭐 그렇게 어려운 알고리듬을 원하는 것도 아니건만. (조금은 원하나? 당장이 아니라서 그렇지.) 내가 코딩해서 원하는 결과가 나왔던 40여 개의 코드 중에 정말로 기능적으로 최적이며 응용이 쉽게 만들었다고 느낀 코드는 딱 하나이다. 게다가 그 또한 내 무지에서 비롯된 착각인지도 모른다.
     
    교수님 코드:
    int i;
    int temp;
    int min_index;

    for (i=0; i<Length; i++)
    {
        for(j=min_index+1; j<Length; j++)
        {
            if(number[min_index] > number[j])
                min_index = j;
        }
       
        temp = number[min_index];
        number[min_index] = number[i];
        number[i] = temp;
    }

    진짜 이거 이렇게 풀어 줄 존재가 절실했다. 실제로 어떤 일들이 벌어지고 있는지 알고 있는 사람이 절실했다. 정확하고 세세하게 알고 있어야 진정 컨트롤할 수 있기 때문이다. 나는 조절력을 가지고 싶다. 많이도 아니다. 내 작업할 수 있는 정도로만. 내가 뭐 지형이나 지질을 파악한댔나, 단지 내가 지도에서 어느 위치에 있는지만 알 수 있으면 만족이다. 초보만 떼면 되는데.

       

    '@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

    week 3 review  (0) 2008.03.22
    [Steve Oualline] 5. Arrays, Qualifiers, and Reading Numbers  (0) 2008.03.16
    week 2 review  (0) 2008.03.15
    [Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
    hw1  (0) 2008.03.10
    posted by maetel
    1. swapping
    지난 (주어진 데이터 - 수열 - 에서 최대값과 최소값을 구하는) 숙제로 assignment에 대해 완전히 이해했다고 생각했었는데 아니었다. ( ..)^
    Swapping two data elements
    int a, b, c;
    a=10; b=20;
    How can you exchange the values of the two variables?
    이 문제 정말 헤맸음. int c가 선언되어 있어서 힌트가 되었다.


    2. address
    중간에 방을 세 개나 비워 둔다... 왜 그럴까...? >> ㅎㅎ 비워 두는 거 아니다.
    number[]와 number는 다른 거 아니었어??? > 아니다. 같은 거다.
    max와 min을 먼저 만드는 것을 보면 memory는 OS가 main() 함수를 호출하기 이전에 (즉, 프로그램이 실행되기 이전에) 마련되는 것인가? > 아니구나. main() 함수에서 선언된 순서대로인 것이 맞다.

    (관련 있는지 모르겠지만,)http://cplusplus.com/doc/tutorial/pointers.html
    > 관련 없다.

    number+i를 number로 바꾸면,
    3221223080 0xbffff6a8 10
    3221223080 0xbffff6a8 5
    3221223080 0xbffff6a8 30
    3221223080 0xbffff6a8 93
    3221223080 0xbffff6a8 0
    3221223080 0xbffff6a8 84
    3221223080 0xbffff6a8 65
    3221223080 0xbffff6a8 3
    3221223080 0xbffff6a8 78
    3221223080 0xbffff6a8 67
    3221223080 0xbffff6a8 45
    3221223080 0xbffff6a8 12
    3221223080 0xbffff6a8 28
    3221223080 0xbffff6a8 75
    3221223080 0xbffff6a8 111
    3221223080 0xbffff6a8 3
    3221223080 0xbffff6a8 845
    3221223080 0xbffff6a8 41
    3221223080 0xbffff6a8 343
    3221223080 0xbffff6a8 43
    address=3221223080 (bffff6a8) = 10
    address=3221223080 (bffff6a8) = 5
    address=3221223080 (bffff6a8) = 30
    address=3221223080 (bffff6a8) = 93
    address=3221223080 (bffff6a8) = 0
    address=3221223080 (bffff6a8) = 84
    address=3221223080 (bffff6a8) = 65
    address=3221223080 (bffff6a8) = 3
    address=3221223080 (bffff6a8) = 78
    address=3221223080 (bffff6a8) = 67
    address=3221223080 (bffff6a8) = 45
    address=3221223080 (bffff6a8) = 12
    address=3221223080 (bffff6a8) = 28
    address=3221223080 (bffff6a8) = 75
    address=3221223080 (bffff6a8) = 111
    address=3221223080 (bffff6a8) = 3
    address=3221223080 (bffff6a8) = 845
    address=3221223080 (bffff6a8) = 41
    address=3221223080 (bffff6a8) = 343
    address=3221223080 (bffff6a8) = 43
    Their sum is 1981
    Their max is 845
    Their min is 0
    Address of the variable max is 0xbffff6a0
    Address of the variable min is 0xbffff6a4

    sum의 address를 첨가하면,
    Address of the variable sum is 0xbffff69c
    그렇다면, int sum이 가장 먼저 생성된다.

    쉘에서 다시 실행시키면,
    3221223816 0xbffff988 10
    3221223816 0xbffff988 5
    3221223816 0xbffff988 30
    3221223816 0xbffff988 93
    3221223816 0xbffff988 0
    3221223816 0xbffff988 84
    3221223816 0xbffff988 65
    3221223816 0xbffff988 3
    3221223816 0xbffff988 78
    3221223816 0xbffff988 67
    3221223816 0xbffff988 45
    3221223816 0xbffff988 12
    3221223816 0xbffff988 28
    3221223816 0xbffff988 75
    3221223816 0xbffff988 111
    3221223816 0xbffff988 3
    3221223816 0xbffff988 845
    3221223816 0xbffff988 41
    3221223816 0xbffff988 343
    3221223816 0xbffff988 43
    address=3221223816 (bffff988) = 10
    address=3221223816 (bffff988) = 5
    address=3221223816 (bffff988) = 30
    address=3221223816 (bffff988) = 93
    address=3221223816 (bffff988) = 0
    address=3221223816 (bffff988) = 84
    address=3221223816 (bffff988) = 65
    address=3221223816 (bffff988) = 3
    address=3221223816 (bffff988) = 78
    address=3221223816 (bffff988) = 67
    address=3221223816 (bffff988) = 45
    address=3221223816 (bffff988) = 12
    address=3221223816 (bffff988) = 28
    address=3221223816 (bffff988) = 75
    address=3221223816 (bffff988) = 111
    address=3221223816 (bffff988) = 3
    address=3221223816 (bffff988) = 845
    address=3221223816 (bffff988) = 41
    address=3221223816 (bffff988) = 343
    address=3221223816 (bffff988) = 43
    Their sum is 1981
    Their max is 845
    Their min is 0
    Address of the variable max is 0xbffff980
    Address of the variable min is 0xbffff984
    Address of the variable sum is 0xbffff97c

    아항~ memory의 주소는 compile할 때 할당되고, update를 하더라도 기존 주소를 그대로 찾아간다. 맞나??? > 틀리다. 그냥 그렇게 보였을 뿐. (메모리를 달리 사용하고 있지 않았기 때문이었다.)
    여하간, 도대체 왜! sum, max, min이 먼저 만들어지고 나서 number[]가 만들어지는 것이야??? > 변수들의 형태에 따라서 분류하여 그 순서대로 만들기 때문이란다.

    뜬금없이 제일 마지막에 int why 변수를 하나 첨가해 보았더니, (Xcode 실행창)
    3221223084 0xbffff6ac 10
    3221223084 0xbffff6ac 5
    3221223084 0xbffff6ac 30
    3221223084 0xbffff6ac 93
    3221223084 0xbffff6ac 0
    3221223084 0xbffff6ac 84
    3221223084 0xbffff6ac 65
    3221223084 0xbffff6ac 3
    3221223084 0xbffff6ac 78
    3221223084 0xbffff6ac 67
    3221223084 0xbffff6ac 45
    3221223084 0xbffff6ac 12
    3221223084 0xbffff6ac 28
    3221223084 0xbffff6ac 75
    3221223084 0xbffff6ac 111
    3221223084 0xbffff6ac 3
    3221223084 0xbffff6ac 845
    3221223084 0xbffff6ac 41
    3221223084 0xbffff6ac 343
    3221223084 0xbffff6ac 43
    address=3221223084 (bffff6ac) = 10
    address=3221223084 (bffff6ac) = 5
    address=3221223084 (bffff6ac) = 30
    address=3221223084 (bffff6ac) = 93
    address=3221223084 (bffff6ac) = 0
    address=3221223084 (bffff6ac) = 84
    address=3221223084 (bffff6ac) = 65
    address=3221223084 (bffff6ac) = 3
    address=3221223084 (bffff6ac) = 78
    address=3221223084 (bffff6ac) = 67
    address=3221223084 (bffff6ac) = 45
    address=3221223084 (bffff6ac) = 12
    address=3221223084 (bffff6ac) = 28
    address=3221223084 (bffff6ac) = 75
    address=3221223084 (bffff6ac) = 111
    address=3221223084 (bffff6ac) = 3
    address=3221223084 (bffff6ac) = 845
    address=3221223084 (bffff6ac) = 41
    address=3221223084 (bffff6ac) = 343
    address=3221223084 (bffff6ac) = 43
    Their sum is 1981
    Their max is 845
    Their min is 0
    Address of the variable max is 0xbffff6a0
    Address of the variable min is 0xbffff6a4
    Address of the variable sum is 0xbffff69c
    Address of the variable why is 0xbffff6a8

    헉!!! 주소 바꾼다... 도대체 뭣이야... 점점 더 이해 안 가. ㅜㅜ
    어쨌든, update 시 변경 사항이 있으면 compile 후 주소를 바꿔치기도 하는 등 각 변수에게 고정된 주소를 주는 것이 아니구나.


    서 교수님:
    컴파일러가 C 소스코드를 분석해서 기계어로 바꾸는데, 소스코드 전체를 들여다 보면 변수들이 여럿 나오겠지요. 단일 변수들은 단일 변수들로 배치할 것이고 어레이로 선언된 것들은 따로 배치해서 메모리를 할당하게 되어 있을 겁니다. 물론 어떤 컴파일러는 그렇지 않고 다른 방법을 사용할 수도 있습니다. 그래서,  number의 어드레스가 다른 변수들과 달리 나중의 주소를 가지게 되는 것으로 판단됩니다.

    number[10] 이라고 배열 선언을 하면 컴파일러는 10개의 연속된 데이터를 위한 공간을 확보하고 그 첫번째 공간의 주소를 number 에 넣습니다. 그래서 number 는 number[0] 의 주소를 가지는 것입니다.

    number[1] 은 배열에서  number[0] 다음의 값을 가지는데 그 공간의 주소값을 알고 싶으면 &number[1] 이라고 하든지 number+1  이라고 하면 됩니다.

    꺼꾸로, number 에서 시작하여 두 번째 즉 number[1] 의 값을 주소로부터 얻고 싶으면 number[1] 이라고  하든지 *(number+1) 로 하여 얻을 수 있습니다.

    서 교수님:
    각 변수들의 실제 메모리 주소 (physical address) 는 프로그램이 실행되는 시점에서 결정됩니다. 적당한 메모리 위치에 OS 가 실행프로그램을 통째로 카피하고, CPU가 main() 의 첫 부분부터 실행하도록 합니다.  다른 프로그램들이 자주 실행되고 끝나는 상황이라면 변수들의 주소가 거의 매번 다르게 보일 것입니다. 그래서, 실제 주소를 지정하는 방법은 거의 없습니다.

    서 교수님:
    변수들이 몇 개가 있는지 어떤 형태인지를 컴파일러가 모두 조사한 후에 각 변수들에 필요한 메모리를 미리 할당해 둡니다.  이때는 상대적인 메모리 주소를 사용하죠. 소스코드에서는 변수들의 선언 순서가 중요합니다. 그러나, 실제로 실행되는 상황에서는 이미 필요한 모든 변수들이 메모리를 차지하고 있는 상황이 됩니다.

    서 교수님:
    C/C++ 프로그래밍은 컴퓨터 구조에 대해서 약간 알고 있으면 훨씬 더 쉽게 접근할 수 있습니다.



    3.
    교수님 강조:
    문제의 풀이를 순차적인 언어로 표현할 수 있으면, 그것을 프로그래밍 언어로 바꿀 수 있다.



    4.
    warning: control reaches end of non-void function

    무슨 뜻인가 했더니 >
    It means that you have to return a value using the return statement before the end of your function. This does not apply to void functions because a void function does not return a value.
    -> omission으로 함수의 return 값을 지정해 주지 않았을 때 생기는 경고였다.



    5.
    int *address;

    int printf ( const char * format, ... );
    %[flags][width][.precision][length]specifier

    *
    The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
    > 난 이거 아직 이해 못 했다.



    6.
    address = &max;

    &
    2) A symbol used to precede a variable name (as in &x). Means the address of the named variable (address of x). Used to assign a value to a pointer variable.


     


    posted by maetel
    Practical C Programming
    http://www.oreilly.com/catalog/pcp3/

    Chapter 4. Basic Declarations and Expressions


    Basic Program Structure


    The basic elements of a program are the data declarations, functions, and comments.

    main() 함수는 첫번째로 호출되는 함수이며, 이 main 함수가 다른 함수들을 직접 또는 간접으로 호출한다.

    return(0);는 프로그램이 정상적으로 (Status=0) 존재했었음을 OS에게 보고하기 위해 쓰인다. : return value가 클수록 error가 심각하다는 뜻이다.



    Variables
    Each variable has a variable type.
    A variable must be defined in a declaration statement just before the main() line at the top of a program.

    http://en.wikipedia.org/wiki/Computer_numbering_formats

    http://en.wikipedia.org/wiki/Signed_number_representations



    Assignment statements
    The general form of the assignment statement is:
    variable = expression;
    The = is used for assignment.



    printf Function

    printf

    : a standard function to output our message
    Print formatted data to stdout
    Writes to the standard output (stdout) a sequence of data formatted as the format argument specifies. After the format parameter, the function expects at least as many additional arguments as specified in format.
    The format tags follow this prototype:
    %[flags][width][.precision][length]specifier

    : 표준 입출력 함수- 표준 입출력 장치를 통해 데이터를 입력하거나 출력하는 기능을 갖고 있는 함수
    - 표준 입출력 함수를 사용하려면 #include <stdio.h>를 기술해 줘야 한다.
    [형식] printf(" 출력양식 ", 인수1,인수2...);
    - 서식문자열에는 모든 문자를 사용할 수 있으며 변환문자와 제어문자를 제외하고는 화면에 그대로 출력
    - 인수와 변환문자는 일대일 대응해야 하며 반드시 인수의 자료형과 문자의 자료형은 일치해야 한다.
    ex) printf("%d + %d= %d\n",10,20,30);
    출력결과 10+20=30


    stdout
    Standard output stream
    : the default destination of regular output for applications. It is usually directed to the output device of the standard console (generally, the screen).

    cf. library fuctions


    %d
    : integer conversion specification

    parameter list

    The general form of the printf statement is:
    printf(format, expression-1, expression-2, ...);
    where format is the string describing what to point.



    Characters

    escape character


    '@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

    hw2  (0) 2008.03.15
    week 2 review  (0) 2008.03.15
    hw1  (0) 2008.03.10
    Key concepts in programming: statement & expression  (1) 2008.03.09
    week 1 review - keywords & file I/O  (0) 2008.03.07
    posted by maetel

    hw1

    1. input.txt 파일에 20개의 정수를 임의로 입력하여 작성하시오.
    2. 프로그램을 수정하여 입력 데이터 파일의 합을 구하는 프로그램을 작성하시오.
    3. 최대값과 최소값을 구하는 루틴을 첨가하시오.


    Xcode에서 프로젝트를 만들어 코딩할 경우, 파일명이나 폴더명을 함부로 바꾸면 (아마도 소유권 문제로) 실행이 되지 않을 수 있다. 이 경우 "no launchable executable present at path"라는 메시지가 뜬다.
    쉘에서 "chmod +x 파일이름"을 친 이후 다시 컴파일하면 가능하다. 그러나 여전히 XCode 내부에서 실행시킬 수는 없었다.
    얼마나 당황스러웠는지 새로 프로젝트를 만들 생각을 아예 못 한... 나는 초짜라 그런지 코딩은 재밌는 것 같은데 XCode 등이 토대로 하는 세계관(?? ㅡㅡ; )이나 컴퓨터 자체가 무섭다.


    FileIn.open로 읽어 들일 파일은
    XCode에서는 debug 폴더 안에, shell에서 실행시킬 때에는 .cpp 실행파일이 있는 폴더 안에 넣어 줘야 한다.

    이번 숙제 엄청 간단한 거였는데 굉장히 오랜 시간이 걸렸다. 그 중 90%는 코딩이 아니라 인터페이스에 익숙치 않아 생긴 초삽질성 장애들. ㅡㅡ; 물론 처음에는 for 구문 안에 for 구문을 돌리는 등 헤매였지만... 아래 그 적나라한 흔적. (마음이 급하면 우선 손익은 Python에 기대게 된다.)
    어쨌든 assignment라는 게 얼마나 고마운 건지 처음으로 알았다. 마구마구 업뎃이 되는구나. 그전에는 왕 무시했었는데.

    list = [5,2,1,6,10,3,80]

    max = list[0]

    for i in range(6):
       

    #for i in range(6):
    ###    print list[i]
    ##      for j in range(4):
    ##          if list[i] > list[j]:
               
    #    if list[i+1] > list[i]:
    #        mx0 = list[i+1]
    ##        print "mx0=", mx0
           
    #        for j in range(i+1,6):
    #            if mx0 < list[j+1]:
    #                mx1 = list[j+1]
    #                print "mx1=", mx1
                       
            
    #            for k in range(j+1,6):
    #                if mx1 < list[k+1]:
    #                    mx2 = list[k+1]
    #                    print "mx2=", mx2


    #print "***"



    '@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

    week 2 review  (0) 2008.03.15
    [Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
    Key concepts in programming: statement & expression  (1) 2008.03.09
    week 1 review - keywords & file I/O  (0) 2008.03.07
    vi  (0) 2008.03.07
    posted by maetel

    statement (문장)
    - A statement will have internal components (eg, expressions).
    - Many languages (e.g. C) make a distinction between statements and definitions, with a statement only containing executable code and a definition declaring an identifier.
    : An instruction written in a high-level language.
    - Programs consist of statements and expressions. An expression is a group of symbols that represent a value.
    - Statements do not return results and are executed solely for their side effects, while expressions always return a result and often do not have side effects at all.

    Simple statements

        * assignment: A := A + 1
        * call: CLEARSCREEN()
        * return: return 5;
        * goto: goto 1
        * assertion: assert(ptr != NULL);

    Compound statements

        * statement block: begin WRITE('Number? '); READLN(NUMBER); end
        * if-statement: if A > 3 then WRITELN(A) else WRITELN("NOT YET") end
        * switch-statement: switch (c) { case 'a': alert(); break; case 'q': quit(); break; }
        * while-loop: while NOT EOF DO begin READLN end
        * do-loop: do { computation(&i); } while (i < 10);
        * for-loop: for A:=1 to 10 do WRITELN(A) end



    expression (式)
    : a combination of values, variables, operators, and functions
    : any legal combination of symbols that represents a value
    : 프로그래밍 작성 언어에서 어떤 값을 계산하는 숫자, 변수, 함수 호출 결과 및 이들이 연산자에 의해 조합된 것. 예를 들어 100, x, x+y, sin(y*2), y>100 등은 모두 식이다. 그 결과값의 형에 따라 산술식, 논리식, 문자열식 등이 있다.
    - Each programming language and application has its own rules for what is legal and illegal.
    - Every expression consists of at least one operand and can have one or more operators. Operands are values, whereas operators are symbols that represent particular actions.
    - The expression is (or can be said to have) its evaluated value; the expression is a representation of that value.
    -  Expressions are often classified by the type of value that they represent. For example:

    # Boolean expressions : Evaluate to either TRUE or FALSE
    # integer expressions: Evaluate to whole numbers, like 3 or 100
    # Floating-point expressions: Evaluate to real numbers, like 3.141 or -0.005
    # String expressions: Evaluate to character strings



    side effect
    - a function or expression is said to produce a side effect if it modifies some state in addition to returning a value.



    declaration
    (宣言)
    - a declaration specifies a variable's dimensions, identifier, type, and other aspects. It is used to announce the existence of a variable or function.
    - For variables, definitions assign bits to an area of memory that was reserved during the declaration phase. For functions, definitions supply the function body. It is thus clear that while a variable or function may be declared many times, it must only be defined once.
    (1) 어떤 언어의 원시 프로그램에서 그 프로그램의 인터프리터에 필요한 정보, 특히 프로그램에서 실행 시 사용될 자료의 특성을 전달하기 위한 표현 방법.
    (2) 프로그램에서 변수, 프로시저, 함수 등의 이름과 그 자료 유형, 함수의 반환값, 함수나 프로시저의 인자와 그 몸체를 정의하는 것. 특히 프로그램에서 쓰이는 변수의 형을 정의하는 것을 말한다.



    ref. philphys informed:
    http://en.wikibooks.org/wiki/Computer_programming#Common_concepts

    http://en.wikibooks.org/wiki/Python_Programming


    '@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

    week 2 review  (0) 2008.03.15
    [Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
    hw1  (0) 2008.03.10
    week 1 review - keywords & file I/O  (0) 2008.03.07
    vi  (0) 2008.03.07
    posted by maetel
    Non-Uniform Random Variate Generation
    (originally published with Springer-Verlag, New York, 1986)
    Luc Devroye
    School of Computer Science
    McGill University


    III. DISCRETE RANDOM VARIATES 83
    1. Introduction. 83
    2. The inversion method. 85
       2.1. Introduction. 85
       2.2. Inversion by truncation of a continuous random variate. 87


    http://en.wikipedia.org/wiki/Variate

    http://en.wikipedia.org/wiki/Exponential_decay

    http://en.wikipedia.org/wiki/Poisson_distribution


    '@GSMC > 정문열: Generative Art' 카테고리의 다른 글

    class 3/20  (0) 2008.03.20
    references for basic programming  (0) 2008.03.17
    Monte Carlo method + random sampling  (0) 2008.03.08
    week 1 review  (0) 2008.03.08
    Random Walk and Fractal Growth  (0) 2008.03.07
    posted by maetel
    A Monte Carlo method is a computational algorithm that relies on repeated random sampling to compute its results.

    an animated presentation of the monte carlo integration - an example from philphys
    랜덤 넘버 제너레이터가 유니폼 하면서 완전히 랜덤하게, 즉 아무런 패턴이 없는 수를 뿌려 낸다는 확신이 있어야 MC에 쓸 수 있다.
    패턴이 있긴 해도 그 패턴의 길이가, 즉 주기가 내가 샘플링 하려고 하는 수의 수보다도 길다면, 그럼 그건 사실상 랜덤하다고 받아들일 수 있다.
    MC는 필요한 계산양이 거의 선형적으로 늘어나니까 고차원 계산을 할 때 훨씬 적은 양의 계산으로도 꽤 믿을 만한 값을 구할 수 있다. 원하는 오차한계에 맞춰서 샘플링 수를 제한할 수도 있고.


    Battleship (game)



    (from ref. offered by professor Jung)
    http://random.mat.sbg.ac.at/links/monte.html






    Pseudorandomness
    http://en.wikipedia.org/wiki/Pseudorandomness

    Statistical randomness
    http://en.wikipedia.org/wiki/Statistical_randomness


    random seed
    http://en.wikipedia.org/wiki/Random_seed

    random in Python -- Generate pseudo-random numbers
    http://docs.python.org/lib/module-random.html

    random number generator
    http://en.wikipedia.org/wiki/Random_number_generator

    Poisson distribution
    http://en.wikipedia.org/wiki/Poisson_distribution


    '@GSMC > 정문열: Generative Art' 카테고리의 다른 글

    references for basic programming  (0) 2008.03.17
    Inversion Method  (0) 2008.03.08
    week 1 review  (0) 2008.03.08
    Random Walk and Fractal Growth  (0) 2008.03.07
    Steven Rooke  (0) 2008.03.04
    posted by maetel
    ref. (extended by the references recommended by professor Jung)

    M A P S • v o l u m e X - n u m b e r 3 • c r e a t i v i t y 2 0 0 0
        by Multidisciplinary Association for Psychedelic Studies (그 희한한 사람들이 갑자기 사라진 게 아니라 이런 데 있었구만.)
        * entheogen -> wikipedia:

    Communications of the ACM — Association for Computing Machinery


    random coil



    '@GSMC > 정문열: Generative Art' 카테고리의 다른 글

    Inversion Method  (0) 2008.03.08
    Monte Carlo method + random sampling  (0) 2008.03.08
    Random Walk and Fractal Growth  (0) 2008.03.07
    Steven Rooke  (0) 2008.03.04
    Computational Beauty of Nature (by Gary William Flake) - Introduction  (0) 2008.02.29
    posted by maetel
    Random Walk and Fractal Growth I
    전산물리 입문 2000/2 김승환
    POSTECH NCSL (포항공대 비선형 및 컴플렉스시스템 연구실 )

    invalid-file

    Random Walk and Fractal Growth I 전산물리 입문 2000/2 김승환 POSTECH NCSL (포항공대 비선형 및 컴플렉스시스템 연구실 )

    아이고 이런 감사할 데가... html로 보기

    keywords:
    random, Brownian motion, Tydall effect, random walk, mean square distance,  Monte Carlo (여기에도 나오네... 적분 방법 아니었어?), pseudo-random number generators (그래 이게 목적이겠지만.), Molecular Dynamics (MD) 방법 (방법??), self-avoiding random walk (SAW), Flory 이론, Nienhuis (??), persistent random walk, limited random walk, fractal growth, DLA (Diffusion Limited Aggregates), Chaos Game, Iterated Function System, Theory of Affine Map (->Image Processing), Benoit Mandelbrot, Fractal Geometry, Hausdorff Dimension, Koch 곡선, Box counting algorithm (Capacity dimension), 'Mountains Never Existed',



    MC(Monte Carlo) code:
          if randN(m) < 0.5,

               Point(m) = Point(m)+1;

          else

               Point(m) = Point(m)-1;

          end;
    randN = rand(N)
    : Generate  N random number between 0 and 1

    뭐니? orz... point()가 뭔데? 이렇게 짧으면 더 쓸쓸해. ㅡㅜ
    그냥 좀 더 흘트린다는 건가? 뭐를? m을? 전산물리... 안 듣긴 했지만...
    근데 이거 통계물리나 열물리 같은 거 아니야?

    Monte Carlo N-Particle Transport Code 이거랑 관계가 있는가?
    헉... 적분이랑 관계 없는 건가...
    Monte Carlo method -> 여기에 정리하는 중


    MC 방법의 응용
        * random walks, fractal growth,
        * Equilibrium/non-equilibrium statistical phenomena, phase transition
        * neural networks
        * particle scattering with the help of computers
        * optimization
        나는 particle scattering 때문에 자주 본 거였구만.


    RAND(N)
    (0.0,1.0)사이의 균일한 분포를 가진 마구잡이 수로 이루어진 NxN 행렬
    그럼 프로세싱에서의 random()인 건가...? 분포가 다른 건가?


    S = RAND('state')
    현재상태를 포함한 35-element 벡터.
    RAND('state',S) resets the state to S.
    RAND('state',0) resets the generator to its initial state.
    RAND('state',J), for integer J, resets the generator to its J-th state.
    RAND('state',sum(100*clock)) resets it to a different state each time.
    포기.

    ref.
    K. Kremer and T. W. Lyklema, Phys. Rev. Lett. 55, 9091 (1985)
    T. M. Bishtein, S. V. Buldyrev, and A. M. Elyashivitch, Polymer 26, 1814 (1985)


     Fractal Growth
    - 평형으로부터 멀리 떨어진 현상 (far from equilibrium)
    - 시공간적으로 매우 다양한 형태
    - 해석적 연구가 매우 어려움

    프랙탈 성장의 예
    - 금속이온의 전기화학적 흡착에 의한 뭉침
    - 고분자, 세라믹, 유리, 얇은막의 성장
    - Viscous fingering
    - Dielectric breakdown
    - 박테리아의 성장
    - 신경세포의 성장


    DLA 모형

        * Diffusion Limited Aggregates
              o 프랙탈 구조를 만들 수 있음이 증명된 첫 성장 모형
              o T.A. Witten and L.M. Sander , 1981.

        * 마구걷기 모형화
              o 매우 간단함
              o 브라운운동에 기초
              o 마구걷기에 의한 확산 모형

        * 성장규칙
              o 평면상의 움직이지 않는 씨앗으로부터 시작.
              o 멀리 떨어진 곳으로부터 시작하여 마구 걷기를 수행.
              o 마구 걷기가 씨앗을 만나면 붙음.
              o 다시 마구걷기를 반복함._M#]





    '@GSMC > 정문열: Generative Art' 카테고리의 다른 글

    Monte Carlo method + random sampling  (0) 2008.03.08
    week 1 review  (0) 2008.03.08
    Steven Rooke  (0) 2008.03.04
    Computational Beauty of Nature (by Gary William Flake) - Introduction  (0) 2008.02.29
    L-System  (0) 2008.02.27
    posted by maetel

    syntax
    auto

    break
    Break is used within loops and switch statements to jump to the end of the code block. It causes the "//code..." above to be skipped and terminates the loop. In switch case statements, break causes the remaining cases to be skipped--it prevents "falling through" to other cases.
    호~ 나도 이거 필요한 적 많았는데...

    continue

    to jump to the top of the loop block
    그럼 왜 continue라고 불러??

    for


    goto
    You cannot, for instance, jump into the middle of a function from a different function by using goto.

    if



    switch
    The prevent falling through, include break;at the end of any code block.
    신기하다!





    #include
    Generally, it is necessary to tell the preprocessor where to look for header files if they are not placed in the current directory or a standard system directory.

    include file (짜넣기 파일)
    : 복수의 프로그램이 공통으로 사용하는 정수나 영역 등에 대해서 그 속성을 뜻매김한 정보를 저장하고 있는 파일.


    cout
    standard output stream

    standard output
    The place where output goes unless you specify a different output device. The standard output device is usually the display screen.

    stream
    a succession of data elements made available over time

    standard stream
    The three I/O connections are called standard input, standard output and standard error.

    사용자 삽입 이미지


    console
    : where text messages are shown.
    : The combination of display monitor and keyboard (or other device that allows input). -> link


    사용자 삽입 이미지



    ifstream
    Input file stream class
    The file to be associated with the stream can be specified either as a parameter in the constructor or by calling member open.



    File I/O

    file I/O in C++
    C++ has two basic classes to handle files, ifstream and ofstream. To use them, include the header file fstream. Ifstream handles file input (reading from files), and ofstream handles file output (writing to files).

    file I/O in C
    For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file).




    질문>> main() 함수에 대하여

    main() 함수란?
    서 교수님:
    main() 함수는 시스템 (오퍼레이팅 시스템: OS) 이 호출하는 함수이기 때문에 미리 리턴 타입을 정해 둔 것입니다. 또 이 함수의 첫번째 문장부터 수행되도록 미리 정해져 있습니다. 그래서, main() 이 없는 C 프로그램은 컴파일 에러가 나고 main() 여러 개가 있어도 에러가 나옵니다.
    그리고, 좀 더 복잡한 프로그램에서는 외부 실행 파일을 직접 호출하여 사용하기도 합니다. 그런한 경우 main() 의 리턴값에 따라 수행결과를 판단할 수 있어요.

    최근의 컴파일러 출력을 보면 C/C++ 의 main() 함수는 int 를 리턴하는 것으로 규정되어 있습니다. 그래서
        int main ()
    이라고 선언을 하죠. 그래서, 이 함수가 끝날 때에는 항상 return return_val; 가 들어가야 합니다.  return_val은 에러가 없을 경우 통상적으로 0 을 주면 됩니다.

    main() 함수 안에서 exit(0); 과 return 0; 는 같은 역할을 합니다.

    컴파일할 때 아래와 같이 하면 int main() 으로 해야 된다고 경고가 나올 것입니다.
    g++ V2008122-01.cpp -o V2008122-01 -Wall


    main() 함수를 선언할 때 리턴 타입을 정해 주지 않으면 다음과 같은 오류 메시지가 뜬다.
    /Users/lym/cintro/week1/V2008122-01.cpp:16: warning: ISO C++ forbids declaration of 'main' with no type



    질문>> "int argc, char *argv[]"에 대하여

    int main(int argc, char *argv[])
    에서 main 다음 괄호 안의 것들은 command line argument라고 부른다.

    cf. 교재 201쪽
    The parameter argc is the number of arguments on the command line including the program name. The array argv contains the actual arguments.

    argument
    : a value that is passed to a routine
    - In programming, a value that you pass to a routine. For example, if SQRT is a routine that returns the square root of a value, then SQRT(25) would return the value 5. The value 25 is the argument.
    Argument
    is often used synonymously with parameter, although parameter can also mean any value that can be changed. In addition, some programming languages make a distinction between arguments, which are passed in only one direction, and parameters, which can be passed back and forth, but this distinction is by no means universal.
    An argument can also be an option to a command, in which case it is often called a command-line argument.

    parameter
    : a variable which takes on the meaning of a corresponding argument passed in a call to a subroutine.

    command line argument
    : argument sent to a program being called

    command line


    a. Xcode에서 실행시키면 다음과 같이 나오고

    argc=1
    argv[0]=/Users/lym/cintro/week1/build/Debug/week1
    argv[1]=

    b. 터미널에서 실행시키면 다음과 같이 나오고

    argc=1
    argv[0]=./V2008122-01
    argv[1]=metelsmac:~/cintro/week1 lym$ ./V2008122-01 input.txt

    c. 터미널에서 "./V2008122-01 input.txt"라고 치면 다음과 같이 나옵니다.

    argc=2
    argv[0]=./V2008122-01
    argv[1]=input.txt
    서 교수님:
    main(argc, argv[])에서
    argv[0] = 실행프로그램 이름; 1번째는 항상 실행프로그램의 패스/이름 이 들어갑니다.

    매개변수를 터미널에서 입력하는 것은 사람이 입력하지만, 사실은 shell 프로그램이 fileio 함수를 호출할 때 매개변수로 주는 것이고, 좀 더 엄밀하게는 OS가 main 함수를 호출할 때 주는 것입니다.

    나는 argv[0]라는 게 굉장히 tricky하게 느껴진다. 그럼 자기 자신을 매개변수로 갖는다는 말 아닌가? 완전... '내 이름을 불러 주오~'잖아.

    아~ 교수님께서 말씀하셨던 fileio.exe가 내 경우 week1.exe이구나... 내가 새 프로젝트(week1)를 만들어서 다시 작성했기 때문에. Xcode에서는 프로젝트명으로 실행파일이 만들어지고 그것은 자동으로 Debug 폴더에 자리를 잡는다. 그러므로 다음과 같이 들어가서 치면 된다. 헤매인 끝에, 나는 week1폴더에 .cpp파일을 만들어 컴파일했으므로 V2008122-01.exe가 만들어졌던 것을 썼던 것인데. Xcode와 쉘에서의 접근 경로가 이번에도 다르다.
    999:~/cintro/week1/build/Debug lym$ ./week1 input.txt
    Their sum is 1969.
    The maximum number is 999.
    The minimum number is 1.
    argc=2
    argv[0]=./week1
    argv[1]=input.txt





    질문>> "using namespace std;"에 대하여

    서 교수님:
    한 개의 프로그램에서 여러 개의 동일한 이름을 가지는 함수를 사용하게 될  때namespace 라는 것을 사용하여 구분하기 쉽도록 한 것입니다.  C++ 의 한 가지 기능입니다.
    그 줄 (using namespace std;) 은
    #include <fstream>
    #include <iostream>
    이 있을 때 포함시키면 편리합니다.


    (1) using namespace std; 을 사용하고 싶지 않은 경우
    (2) 다른 헤더파일에서도 ifstream, cout, endl 등의 함수를 정의하고 있어서 그 함수들을 사용할 때 구별이 필요한 경우 다음과 같이 하면 됩니다.

    ifstream -> std::ifstream
    cout -> std::cout
    endl -> std::endl



    '@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

    week 2 review  (0) 2008.03.15
    [Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
    hw1  (0) 2008.03.10
    Key concepts in programming: statement & expression  (1) 2008.03.09
    vi  (0) 2008.03.07
    posted by maetel

    vi

    '@GSMC > 서용덕: DMD Programming' 카테고리의 다른 글

    week 2 review  (0) 2008.03.15
    [Steve Oualline] 4. Basic Declarations and Expressions  (0) 2008.03.10
    hw1  (0) 2008.03.10
    Key concepts in programming: statement & expression  (1) 2008.03.09
    week 1 review - keywords & file I/O  (0) 2008.03.07
    posted by maetel

    '@GSMC > 정문열: Generative Art' 카테고리의 다른 글

    Monte Carlo method + random sampling  (0) 2008.03.08
    week 1 review  (0) 2008.03.08
    Random Walk and Fractal Growth  (0) 2008.03.07
    Computational Beauty of Nature (by Gary William Flake) - Introduction  (0) 2008.02.29
    L-System  (0) 2008.02.27
    posted by maetel
    2008. 2. 29. 17:36 @GSMC/정문열: Generative Art
    Computational Beauty of Nature:
    Computer Explorations of Fractals, Chaos, Complex Systems, and Adaptation
    Gary William Flake
    MIT Press (catalog)

    Google book
    Google preview: Introduction



    Reductionism is the idea that a system can be understood by examining its individual parts. (Implicit in this idea is that one may have to examine something at multiple levels.)

    Traditional scientists study two types of phenomena: agents and interactions of agents.



    1) 환원주의적 접근으로 해부하기
    2) 보다 넓은 시야로 전체 집합을 이해하기
    - 몇 개의 agents가 전체적인 패턴을 형성하는지 (예) 뇌세포:인간 지능)
    3) 1과 2의 사이에서 agents 간의 상호작용을 연구하기
    - The interactions of agents can be seen to form the glue that binds one level of understanding to the next level.



    1.1 Simplicity and Complexity

    emergent의 예:
    개미 굴/군집, 예측을 벗어나는 경제 시장, 척추동물의 패턴 인식 능력, 바이러스와 박테리아에 저항하는 인간의 면역 체계, 지구 생명체의 진화
    => 간단한 단위들로 이루어져 있는데 결합하면 전체적으로 복잡한 형상을 띤다.
    => 단지 부분들의 합으로는 설명할 수 없는 거대한 체계를 이룬다.

    The whole of the system is greater than the sum of the parts(, which is a fair definition of holism -- the very opposite of reductionism).

    Agents that exist on one level of understanding are very different from agents on another level. Yet the interactions on one level of understanding are often very similar to the interactions on other levels.


    # 자기상사성 (self-similarity)
    예) 생물 (나무, 양치식물, 나뭇잎, 나뭇가지), 무생물 (눈송이, 산맥, 구름)

    상사12 (相似)
    「명」「1」서로 모양이 비슷함. 「2」『생』종류가 다른 생물의 기관이 발생적으로 기원과 구조가 다르나 형상과 작용이 서로 일치하는 현상. 예를 들면, 새의 날개와 벌레의 날개 관계, 또는 잎이 변하여 된 완두콩의 덩굴손과 줄기가 변하여 된 포도 나무의 덩굴손 관계 따위이다. 「3」『수1』=닮음〔1〕.
    「참」상동04(相同).
    ref. 표준국어대사전


    # 예측불능성 (unpredictability)
    예) 주식 시장, 날씨

    # 복잡성 complexity
    예) 개미 군, 인간 뇌, 경제 시장
    => By self-organizing, complex behavior of collectives is much richer than the behavior of the individual component units.

    # 적응력 (adaptation)
    예) 진화, 학습, 적응 체계와 주변 환경과의 관계

    Nature often uses the simplest.




    '@GSMC > 정문열: Generative Art' 카테고리의 다른 글

    Monte Carlo method + random sampling  (0) 2008.03.08
    week 1 review  (0) 2008.03.08
    Random Walk and Fractal Growth  (0) 2008.03.07
    Steven Rooke  (0) 2008.03.04
    L-System  (0) 2008.02.27
    posted by maetel
    2008. 2. 27. 03:41 @GSMC/정문열: Generative Art

    '@GSMC > 정문열: Generative Art' 카테고리의 다른 글

    Monte Carlo method + random sampling  (0) 2008.03.08
    week 1 review  (0) 2008.03.08
    Random Walk and Fractal Growth  (0) 2008.03.07
    Steven Rooke  (0) 2008.03.04
    Computational Beauty of Nature (by Gary William Flake) - Introduction  (0) 2008.02.29
    posted by maetel