2016년 7월 29일 금요일

[Python] pyenv 로 Python 버전 및 개발 환경 관리

pyenv 로 Python 버전 및 개발 환경 관리

설치

  • OS X
    $ brew update
    $ brew install pyenv
    $ brew install pyenv-virtualenv
    
  • 기타 OS
    1. installer 활용 설치
      $ curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash
      
    2. PATH 설정
      • ~/.bash_profile 에 다음 내용 추가
      export PATH="~/.pyenv/bin:$PATH"
      eval "$(pyenv init -)"
      eval "$(pyenv virtualenv-init -)"
      
      • 적용
      $ source ~/.bash_profile
      

사용

  1. pyenv로 Python 설치
    • 설치 가능 버전 확인
    $ pyenv install --list
    
    • 설치는 `pyenv install 3.5.2' 형태로 가능
  2. pyenv-virtualenv 로 가상 환경 관리
    https://github.com/yyuu/pyenv-virtualenv
    pyenv-installer 에 포함이 되어있기 때문에 추가로 설치할 것은 없다.
    1. 가상 환경 생성
      $ pyenv virtualenv 3.5.2 v352
      
      • pyenv virtualenv 버전 환경명 형태로 사용
      • 버전을 지정하지 않으면 현재 지정된 버전으로 적용됨
    2. 가상 환경 활성화
      $ pyenv activate v352
      
      • pyenv activate 환경명 형태로 사용
      • pyenv deactivate 로 비활성화


2016년 7월 25일 월요일

[Algorithm] Codility Lesson 7 Stacks and Queues - Brackets



A string S consisting of N characters is considered to be properly nested
if any of the following conditions is true:
        - S is empty;
        - S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
        - S has the form "VW" where V and W are properly nested strings.

For example, the string "{[()()]}" is properly nested but "([)()]" is not.

Write a function:
        class Solution { public int solution(String S); }
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.

For example, given S = "{[()()]}", the function should return 1
and given S = "([)()]", the function should return 0, as explained above.

Assume that:
        - N is an integer within the range [0..200,000];
        - string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".

Complexity:
        - expected worst-case time complexity is O(N);
        - expected worst-case space complexity is O(N) (not counting the storage required for input arguments).
     

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

N개의 문자로 구성된 문자열 S는 다음 조건 중 하나라도 true일 경우 제대로 중첩된다고 간주된다.
        - S는 공백이다;
        - S가 "(U)" 또는 "[U]" 또는 "{U}" 형태를 가지고 U는 제대로 중첩된 문자열이다.;
        - S가 "VW" 형태를 가지고 V와 W는 제대로 중첩된 문자열이다.

예를 들어, 문자열 "{[()()]}"는 제대로 중첩되었지만 "([)()]" 는 그렇지 않다.

함수 작성:
        class Solution { public int solution(String S); }
N개의 문자로 구성된 문자열 S가 주어지고, S가 제대로 중첩된 경우 1을 리턴하고 그렇지 않으면 0을 리턴한다.

예를 들어, S = "{[()()]}" 가 주어지면 함수는 1을 리턴해야 하고,
S = "([)()]" 가 주어지면 위에서 설명한 것처럼 함수는 0을 리턴해야 한다.

가정:
        - N은 [0..200,000] 범위의 정수
        - 문자열 S는 다음 문자로만 구성된다: "(", "{", "[", "]", "}", ")".

복잡도:
        - 최악의 시간 복잡도는 O(N);
        - 최악의 공간 복잡도는 O(N) (입력 공간 제외).

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


100%:
https://codility.com/demo/results/trainingHXGBJ5-V8X/



2016년 7월 5일 화요일

[Django] Django Tutorial 1





Django Tutorial


설치

  1. python 설치
  2. Django 설치
    • pip install Django
    • 설치 확인은 python -m django --version

프로젝트 생성

  1. 커맨드로 기본 프로젝트 구조 생성
    • django-admin startproject mysite
  2. 생성 파일 확인
    mysite/
        manage.py
        mysite/
            __init__.py
            settings.py
            urls.py
            wsgi.py
    
    • 바깥쪽 mysite/ 폴더는 프로젝트를 감싸는 역할을 하고, 이름은 Django 에게 중요하지 않아서 원하면 바꿔도 된다.
    • manage.py : Django 프로젝트와 상호작용 할 수 있도록 해주는 커맨드라인 유틸리티이다. 더 상세한 내용은 django-admin and manage.py 에서 확인할 수 있다.
    • 안쪽 mysite/ 폴더는 프로젝트를 위한 실제 Python 패키지이다. 이 폴더명은 Python 패키지 이름이 되며 안에 있는 것을 import 하려면 이 이름을 사용해야 한다. (예: mysite.urls).
    • mysite/__init__.py : Python에게 이 디렉토리가 Python 패키지라고 간주하도록 하는 빈 파일이다. Python 초심자라면 공식 Python 문서인 more about packages를 읽어라.
    • mysite/settings.py 이 Django 프로젝트의 설정이다. Django settings에서 설정하는 방법에 대해 알려준다.
    • mysite/urls.py : 이 Django 프로젝트의 URL 선언이다; Django로 생성된 사이트의 목차이다. (URL dispatcher)[https://docs.djangoproject.com/en/1.9/topics/http/urls/]에서 URL에 대해 더 읽을 수 있다.
    • mysite/wsgi : 프로젝트를 WSGI 호환 웹 서버로 제공하기 위한 엔트리 포인트이다. (How to deploy with WSGI)[https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/]에서 WSGI과 함께 배포하는 방법에 대한 자세한 내용을 참조할 수 있다.

개발 서버 실행

  1. 실행
    • 바깥쪽 mysite 폴더로 이동한 뒤 커맨드를 이용해 실행한다. python manage.py runserver
    • 실행시 나오는 데이터베이스 관련 경고는 곧 다룰 것이므로 지금은 무시한다.
    • Django 에 경량 웹서버를 포함해두어서 배포 전 까지 Apache 등의 서버 설정을 고려하지 않고 빠르게 개발할 수 있다.
    • 개발 서버는 실제 환경에서 사용하지 말고 개발 중에만 사용하도록 한다.
  2. 접속 확인



2016년 7월 2일 토요일

[Algorithm] Codility Lesson 7 Stacks and Queues - Fish

You are given two non-empty zero-indexed arrays A and B consisting of N integers.
Arrays A and B represent N voracious fish in a river,
ordered downstream along the flow of the river.

The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q,
then fish P is initially upstream of fish Q. Initially, each fish has a unique position.

Fish number P is represented by A[P] and B[P].
Array A contains the sizes of the fish. All its elements are unique.
Array B contains the directions of the fish. It contains only 0s and/or 1s, where:
- 0 represents a fish flowing upstream,
- 1 represents a fish flowing downstream.

If two fish move in opposite directions and there are no other (living) fish between them,
they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one.
More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0,
and there are no living fish between them. After they meet:
- If A[P] > A[Q] then P eats Q, and P will still be flowing downstream,
- If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream.
We assume that all the fish are flowing at the same speed.
That is, fish moving in the same direction never meet.
 The goal is to calculate the number of fish that will stay alive.

For example, consider arrays A and B such that:
- A[0] = 4    B[0] = 0
- A[1] = 3    B[1] = 1
- A[2] = 2    B[2] = 0
- A[3] = 1    B[3] = 0
- A[4] = 5    B[4] = 0
Initially all the fish are alive and all except fish number 1 are moving upstream.
Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too.
Finally, it meets fish number 4 and is eaten by it. The remaining two fish,
number 0 and 4, never meet and therefore stay alive.

Write a function:
class Solution { public int solution(int[] A, int[] B); }
that, given two non-empty zero-indexed arrays A and B consisting of N integers,
returns the number of fish that will stay alive.

For example, given the arrays shown above, the function should return 2, as explained above.

Assume that:
- N is an integer within the range [1..100,000];
- each element of array A is an integer within the range [0..1,000,000,000];
- each element of array B is an integer that can have one of the following values: 0, 1;
- the elements of A are all distinct.
Complexity:
- expected worst-case time complexity is O(N);
- expected worst-case space complexity is O(N), beyond input storage
(not counting the storage required for input arguments).

Elements of input arrays can be modified.

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

N개의 정수로 구성된 배열 A와 B가 주어진다. 배열 A와 B는 강의 흐름에 따라 순서가 매겨진,
강 안의 게걸스러운 물고기 N마리를 나타낸다.

물고기는 0부터 N-1 까지로 숫자가 매겨져 있다. 만약 P < Q인 두 물고기가 있다면,
물고기 P는 물고기 Q보다 초기에 상류에 있다. 초기에 각 물고기는 유일한 위치를 가진다.

물고기 P는 A[P]와 B[P]로 표현된다. 배열 A는 물고기의 크기를 포함한다. 모든 요소는 유일하다.
배열 B는 물고기의 방향을 포함한다. 오직 0 또는 1만 포함한다.
- 0은 물고기가 상류로 흐르고 있음을 나타내고,
- 1은 물고기가 하류로 흐르고 있음을 나타낸다.

만약 두 물고기가 반대되는 방향으로 움직이고 그 사이에 (살아있는) 다른 물고기가 없다면,
그들은 결국 서로 만나게 된다. 그렇게 되면 오직 한 물고기만 살아남을 수 있다
- 더 큰 물고기가 작은 물고기를 먹는다. 더 정확하게는 P < Q,  B[P] = 1, B[Q] = 0 이고
그사이에 살아있는 물고기가 없는 물고기 P와 Q가 서로 만나게 되면 그들이 만난 이후에는
- 만약 A[P] > A[Q]이면 P가 Q를 먹고 P는 계속 하류로 흐르고,
- 만약 A[P] < A[Q]이면 Q가 P를 먹고 Q는 계속 상류로 흐른다.

모든 물고기는 같은 속도로 흐른다고 가정한다. 물고기가 같은 방향으로 움직인다면
절대 만나지 않는다는 것이다. 목표는 살아남은 물고기의 숫자를 구하는 것이다.

예를 들어, 배열 A와 B가 다음과 같다고 생각하면:
A[0] = 4    B[0] = 0
A[1] = 3    B[1] = 1
A[2] = 2    B[2] = 0
A[3] = 1    B[3] = 0
A[4] = 5    B[4] = 0
초기에는 모든 물고기가 살아있고, 물고기 1을 제외한 모든 물고기가 상류로 움직인다.
물고기 1은 물고기 2를 만나고 먹는다. 그리고 물고기 3을 만나서 역시 먹는다.
마지막으로 물고기 4를 만나서 먹힌다. 남은 두 물고기 0과 4는 절대 만나지 않고 영원히 살아남는다.

함수 작성
class Solution { public int solution(int[] A, int[] B); }
N개의 정수로 구성된 배열 A와 B가 주어지고, 살아남은 물고기의 숫자를 리턴한다.

예를 들어, 위에 본 배열들이 주어진다면, 위에서 설명한 것처럼 함수는 2를 리턴해야한다.

가정:
- N은 [1..100,000] 범위의 정수;
- 배열 A의 요소는 [0..1,000,000,000] 범위의 정수;
- 배열 B의 요소는 다음 값 중 하나를 가질 수 있다: 0, 1;
- 배열 A의 요소는 모두 다르다.

복잡도:
- 최악의 시간복잡도는 O(N);
- 최악의 공간복잡도는 O(N), 입력 공간 제외

배열의 요소는 수정될 수 있다.

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


100%:
https://codility.com/demo/results/trainingDA4BVB-S6N/


2016년 6월 29일 수요일

[Algorithm] Codility Lesson 6 Sorting - NumberOfDiscIntersections

We draw N discs on a plane. The discs are numbered from 0 to N − 1.
A zero-indexed array A of N non-negative integers, specifying the radiuses of the discs, is given.
The J-th disc is drawn with its center at (J, 0) and radius A[J].

We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs
have at least one common point (assuming that the discs contain their borders).

The figure below shows discs drawn for N = 6 and A as follows:
    A[0] = 1
    A[1] = 5
    A[2] = 2
    A[3] = 1
    A[4] = 4
    A[5] = 0

There are eleven (unordered) pairs of discs that intersect, namely:
    - discs 1 and 4 intersect, and both intersect with all the other discs;
    - disc 2 also intersects with discs 0 and 3.

Write a function:
    class Solution { public int solution(int[] A); }

that, given an array A describing N discs as explained above,
returns the number of (unordered) pairs of intersecting discs.
The function should return −1 if the number of intersecting pairs exceeds 10,000,000.

Given array A shown above, the function should return 11, as explained above.

Assume that:
    - N is an integer within the range [0..100,000];
    - each element of array A is an integer within the range [0..2,147,483,647].

Complexity:
    - expected worst-case time complexity is O(N*log(N));
    - expected worst-case space complexity is O(N),
beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

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

우리는 평면에 N개의 디스크를 그린다. 디스크 들은 0 부터 N - 1로 번호가 매겨진다.
디스크의 반지름으로 구분되는 N개의 음수가 아닌 정수 배열 A가 주어진다.

J번째 디스크는 중앙이 (J, 0)이고 반지름 A[J] 으로 그려진다.

J ≠ K이고 J번째 디스크와 K번째 디스크가 적어도 하나의 공통 지점이 있다면(디스크에 경계선도 포함한다고 가정한다.)
J번째 디스크와 K번째 디스크가 '교차'(intersect)한다고 말한다.

N = 6이고 A가 다음과 같다면 디스크들이 그려진 도형은 아래처럼 보여진다:
A[0] = 1
A[1] = 5
A[2] = 2
A[3] = 1
A[4] = 4
A[5] = 0

11개의 디스크가 교차하는 쌍이 11개(정렬되지 않은) 있다:
디스크 1과 디스크 4는 서로 교차하고, 다른 모든 디스크들과 교체한다;
디스크 2도 디스크 0, 디스크 3과 교차한다.

함수 작성:
class Solution { public int solution(int[] A); }
위에 설명한 것 같은 N개의 디스크로 표현되는 배열 A가 주어지고, 교차되는 디스크 쌍의 갯수(정렬되지 않은)를 리턴한다.
교차 쌍이 10,000,000를 초과하면 함수는 -1을 리턴해야 한다.

위에서 본 배열 A가 주어지면, 위에서 설명한 것 처럼 함수는 11을 리턴해야한다.

가정:
- N은 [0..100,000] 범위의 정수;
- A의 각 요소는 [0..2,147,483,647] 범위의 정수.

복잡도:
- 최악의 시간 복잡도는 O(N*log(N));
- 최악의 공간 복잡도는 O(N), 입력 공간 제외.

입력된 배열의 요소는 수정할 수 있다.





62%:
https://codility.com/demo/results/trainingEYPYR6-UPQ/



100%:
https://codility.com/demo/results/trainingAF88MJ-ZAP/

2016년 6월 27일 월요일

[Algorithm] Codility Lesson 6 Sorting - MaxProductOfThree

A non-empty zero-indexed array A consisting of N integers is given.
The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N).

For example, array A such that:
    A[0] = -3
    A[1] = 1
    A[2] = 2
    A[3] = -2
    A[4] = 5
    A[5] = 6

contains the following example triplets:
    - (0, 1, 2), product is −3 * 1 * 2 = −6
    - (1, 2, 4), product is 1 * 2 * 5 = 10
    - (2, 4, 5), product is 2 * 5 * 6 = 60

Your goal is to find the maximal product of any triplet.

Write a function:
    class Solution { public int solution(int[] A); }
that, given a non-empty zero-indexed array A, returns the value of the maximal product of any triplet.

For example, given array A such that:
    A[0] = -3
    A[1] = 1
    A[2] = 2
    A[3] = -2
    A[4] = 5
    A[5] = 6
the function should return 60, as the product of triplet (2, 4, 5) is maximal.

Assume that:
    - N is an integer within the range [3..100,000];
    - each element of array A is an integer within the range [−1,000..1,000].

Complexity:
    - expected worst-case time complexity is O(N*log(N));
    - expected worst-case space complexity is O(1),
    beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.


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


N개의 정수로 구성된 비어 있지 않은 배열 A가 주어진다.
세 요소 (P, Q, R)의 'product'(곱)는 A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N)와 같다.

예를 들어 배열 A가 다음과 같다면:
    A[0] = -3
    A[1] = 1
    A[2] = 2
    A[3] = -2
    A[4] = 5
    A[5] = 6

아래의 예시 세 요소를 포함하고:
- (0, 1, 2), product 는 −3 * 1 * 2 = −6 이다.
- (1, 2, 4), product 는 1 * 2 * 5 = 10 이다.
- (2, 4, 5), product 는 2 * 5 * 6 = 60 이다.

목표는 세 요소의 product 중 가장 큰 것을 찾는 것이다.

함수 작성:
    class Solution { public int solution(int[] A); }
N개의 정수로 구성된 비어 있지 않은 배열 A가 주어지고, 세 요소의 product 중 최대 값을 리턴한다.

예를 들어, 배열 A가 다음과 같다면:
    A[0] = -3
    A[1] = 1
    A[2] = 2
    A[3] = -2
    A[4] = 5
    A[5] = 6
세 요소 (2, 4, 5)의 product 가 최대 값 이므로 함수는 60을 리턴해야 한다.

가정:
    - N은 [3..100,000] 범위의 정수이다.
    - 배열 A의 각 요소는 [−1,000..1,000] 범위의 정수이다.

복잡도:
    - 최악의 시간 복잡도는 O(N*log(N));
    - 최악의 공간 복잡도는 O(1), 입력 공간 제외

배열의 요소는 수정할 수 있다.


100%:
https://codility.com/demo/results/trainingYWMGGK-VSR/

2016년 6월 23일 목요일

[GitHub] GitHub Page 도메인 연결하기

다른 사람 질문에 답변하느라 진행해본 김에 필요한 사람이 있을듯 싶어 작성함


https://help.github.com/articles/setting-up-your-pages-site-repository/ 보고 진행했는데 간단히 요약하면



1. www.xxx.kr 로 연결 하려면


1) GitHub 쪽 준비

  • 리파지토리 루트에 CNAME 라는 이름의 파일을 생성해서 www.xxx.kr 라는 내용을 추가

2) DNS 설정

  • Type: CNAME / NAME: www / value: 닉네임.github.io





2. xxx.kr 로 연결 하려면

1) GitHub 쪽 준비

  • 리파지토리 루트에 CNAME 라는 이름의 파일을 생성해서 xxx.kr 라는 내용을 추가

2) DNS

  • Type: A / NAME: xxx.kr / value: 192.30.252.153
  • Type: A / NAME: xxx.kr / value: 192.30.252.154 (둘 다 추가)

3) (선택사항) 추가로 www.xxx.kr 로도 연결하려면

  • Type: CNAME / NAME: www / value: 닉네임.github.io 도 추가





CloudFlare 기준 설정 후 5~10분 이내에 금방 연결 확인되었다.


hangaebal.github.io <- hangaebal.tk


2016년 6월 22일 수요일

[Node.js] GitHub API 활용 (2)

GitHub API 활용 (2)


ajax 방식에서 페이지 갱신 방식으로 변경


routes/github.js 수정

  • 데이터를 직접 리턴하던 형태에서, 뷰와 데이터를 같이 리턴하도록

...
-   res.send(data);
+   res.render('github', {data: data, q: req.query.q});
...




views/github.jade 수정

  • jade를 거의 처음 사용하지만 레퍼런스 참고하니 크게 어려울 것은 없었다.
  • 뷰 코드 작성 시 태그를 열고 닫는 등의 단순 반복 타이핑이 확 줄었다.






현재까지의 코드 :

https://github.com/hangaebal/dictionary-node-express/tree/github-api2

2016년 6월 20일 월요일

[Algorithm] Codility Lesson 6 Sorting - Distinct

Write a function
    class Solution { public int solution(int[] A); }

that, given a zero-indexed array A consisting of N integers,
returns the number of distinct values in array A.

Assume that:
    - N is an integer within the range [0..100,000];
    - each element of array A is an integer within the range [−1,000,000..1,000,000].

For example, given array A consisting of six elements such that:
    A[0] = 2    A[1] = 1    A[2] = 1
    A[3] = 2    A[4] = 3    A[5] = 1
the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.

Complexity:
    - expected worst-case time complexity is O(N*log(N));
    - expected worst-case space complexity is O(N),
    beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

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

함수 작성:
    class Solution { public int solution(int[] A); }

N개의 정수로 구성된 배열 A가 주어지고, 배열 A의 값의 수를 리턴한다.

가정:
    - N은 [0..100,000] 범위의 정수;
    - 배열의 각 요소는 [−1,000,000..1,000,000] 범위의 정수

예를 들어 다음과 같은 여섯 요소로 구성된 배열 A가 주어진다면:
    A[0] = 2    A[1] = 1    A[2] = 1
    A[3] = 2    A[4] = 3    A[5] = 1
함수는 3을 리턴 해야한다, 왜냐하면 배열 A에 별개의 값이 '1, 2, 3' 3개 있기 때문이다.

복잡도:
    - 최악의 시간 복잡도는 O(N*log(N));
    - 최악의 공간 복잡도는 O(N), 입력 공간 제외

배열의 요소는 수정할 수 있다.





100%:
https://codility.com/demo/results/trainingT5QPBD-7CC/

2016년 6월 16일 목요일

[Node.js] Github API 활용 (1)

만들던 앱을 활용해서 GitHub API 활용


네이버 백과사전 검색 API 결과가 기대했던 것과 달라서 계속 개선해나가기가 아쉬워졌다.
(검색 결과가 특정 길이 이상 출력되지 않고 링크로 직접 가서 확인해야 한다든지..)

다른 API 중에 괜찮은 게 없을까 찾다가 GitHub API를 선택했다.

리파지토리 검색 API 적용



app.js 에 routes 추가
...
app.use('/github', require('./routes/github'));
...


routes/github.js 파일 생성


views/github.jade 파일 생성


현재까지의 소스
https://github.com/hangaebal/dictionary-node-express/tree/github-api1

2016년 6월 15일 수요일

[Node.js] Express.js 활용 사전 앱 만들기 (3)

뷰 적용 및 API 결과 처리

  1. XML parser 설치
    • 네이버 API가 xml 형태로만 리턴하므로 XML 처리 라이브러리 설치
    • npm install --save xml2js



  2. 뷰 수정
    • public/stylesheets/style.css (기존 css 제거)




    • layout.jade (bootstrap 사용을 위해 div.container 추가)




    • dictionary.jade (검색어 입력 부분과 ajax 호출 부분 추가)




  3. dictionary.js 수정




현재까지의 코드 :
https://github.com/hangaebal/dictionary-node-express/tree/blog3


2016년 6월 14일 화요일

[Node.js] Express.js 활용 사전 앱 만들기 (2)

사전 API 적용


다음에 검색 API는 있지만 사전 검색은 없어서 사용 불가

네이버에는 사전 검색 API를 지원하고 있다. 처리한도가 25,000 / 일 이지만 개발 용도로 쓰기에 무리가 없어서 선택





API 개발 가이드 내용에 따라 진행해보자

  1. 개인 애플리케이션을 등록한다. (ID, SECRET 발급에 필요)

    • 페이스북 계정 개발자 등록시 처럼 네이버 계정에 휴대폰 인증이 최초 1회 필요하다고 한다. 인증을 진행한다.
    • 대부분 기본적인 정보를 입력하고 사용할 API 권한관리에서 검색 API를 잊지말고 체크한다.
    • 이후 내 애플리케이션> 해당 앱 메뉴에서 Client ID / Client Secret 을 확인할 수 있다.


  2. API 호출 코드 작성

    • dictionary.js 파일에 호출 코드를 추가한다.
    • 일단 API 정상 동작을 확인하기 위해 뷰 코드 수정 없이 서버 자체에서 임의의 텍스트(개발)로 검색한 결과를 리턴하게 해보자

    var express = require('express');
    var router = express.Router();
    
    var https = require('https');
    
    var CLIENT_ID = '발급받은 ID';
    var CLIENT_SECRET = '발급받은 SECRET';
    var API_URI = '/v1/search/encyc.xml?query=';
    
    var options = {
      host: 'openapi.naver.com',
      port: 443,
      path: API_URI,
      method: 'GET',
      headers: {'X-Naver-Client-Id':CLIENT_ID, 'X-Naver-Client-Secret': CLIENT_SECRET}
    };
    
    router.get('/', function(req, res, next) {
      var searchText = encodeURIComponent('개발');
      options.path = API_URI + searchText;
      var apiReq = https.request(options, function(apiRes) {
        console.log('STATUS: ' + apiRes.statusCode);
        apiRes.setEncoding('utf8');
        apiRes.on('data', function (chunk) {
          res.setHeader('Content-Type', 'application/xml');
          res.send(chunk);
        });
      });
      apiReq.end();
    });
    
    module.exports = router;
    

    • nodemon을 설치했다면 파일 수정시 서버가 자동으로 재시작 된다.


  3. 접속 확인



현재까지의 전체 소스:
- https://github.com/hangaebal/dictionary-node-express/tree/blog2

2016년 6월 13일 월요일

[Node.js] Express.js 활용 사전 앱 만들기 (1)

개발 환경 준비

  1. 먼저 기본 앱 구조를 편하게 잡기 위해 Express generator를 사용한다.
  2. 개발 중 소스 수정시마다 서버 재시작하려면 불편하니 nodemon을 이용
    • 개발 dependency로 설정하기 위해 --save-dev 옵션 사용
    • package.json파일에 devDependencies로 따로 관리된다.
    $ npm install nodemon --save-dev
    
    이후 서버 구동은
    $ nodemon
    
  3. Code Style 확인을 위해 Linter를 사용
    • 편집기로 SublimeText3를 사용하고 있어서 SublimeLinter를 선택했다.
    • 설치 순서 : https://github.com/roadhump/SublimeLinter-eslint
    • 설치 후 설정에서 Lint Mode를 Save only로 해두면 저장할 때마다 표시를 해준다.
  4. 의존성 관리를 위해 bower를 설치
    $ npm install bower --save
    
    • bower 패키지 관리를 위해 bower init 커맨드로 bower.json 파일 생성
    $ bower init
    

  1. bower를 이용해서 bootstrap(+jquery) 설치
    • bootstrap 의존성에 jquery 2.2.4 버전이 포함되어있어서 같이 설치 된다.
    $ bower install bootstrap
    


코드 작성

  1. app에서 bower_components 디렉토리에 접근 가능하도록 app.js에 아래 내용을 추가
    app.use(express.static(path.join(__dirname, 'bower_components')));
    
  2. 레이아웃에 bootstrap.css 와 jquery를 추가
    • views/layout.jade 파일 수정
    doctype html
    html
    head
        title= title
        link(rel='stylesheet', href='/bootstrap/dist/css/bootstrap.min.css')
        link(rel='stylesheet', href='/stylesheets/style.css')
        script(src='/jquery/dist/jquery.min.js')
    body
        block content
    
  3. /dictionary 경로로 접근 가능하도록 routes와 view를 추가
    1. app.js 파일에 아래 내용 추가 javascript app.use('/dictionary', require('./routes/dictionary'));
    2. routes/dictionary.js 파일 추가 (index.js를 복사해서 약간 수정한다.)
      var express = require('express');
      var router = express.Router();
      
      router.get('/', function(req, res, next) {
      res.render('dictionary', {title: 'dic'});
      
      });
      
      module.exports = router;
      
    3. view/dictionary.jade 파일 추가 (마찬가지로 index.jade를 복사해서 수정한다.)
      extends layout
      
      block content
        h1 사전
        p Welcome to #{title}
      
  4. 접속 확인


아직 사전 관련 기능은 하나도 없지만...일단 앱 기본 토대가 완료 되었다.
현재까지의 소스 https://github.com/hangaebal/dictionary-node-express/tree/blog1

[Algorithm] Codility Lesson 6 Sorting - Triangle

A zero-indexed array A consisting of N integers is given.
A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and:
    - A[P] + A[Q] > A[R],
    - A[Q] + A[R] > A[P],
    - A[R] + A[P] > A[Q].

For example, consider array A such that:
    A[0] = 10    A[1] = 2    A[2] = 5
    A[3] = 1     A[4] = 8    A[5] = 20
Triplet (0, 2, 4) is triangular.

Write a function:
    class Solution { public int solution(int[] A); }

that, given a zero-indexed array A consisting of N integers,
returns 1 if there exists a triangular triplet for this array and returns 0 otherwise.

For example, given array A such that:
    A[0] = 10    A[1] = 2    A[2] = 5
    A[3] = 1     A[4] = 8    A[5] = 20

the function should return 1, as explained above. Given array A such that:
    A[0] = 10    A[1] = 50    A[2] = 5
    A[3] = 1
the function should return 0.

Assume that:
    - N is an integer within the range [0..100,000];
    - each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].

Complexity:
    - expected worst-case time complexity is O(N*log(N));
    - expected worst-case space complexity is O(N),
    beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.


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


정수 N개로 구성된 배열 A가 주어진다.
만약 3요소 (P, Q, R)가 0 ≤ P < Q < R < N 이고 다음과 같다면 'triangular' 라고 할 수 있다:
    - A[P] + A[Q] > A[R],
    - A[Q] + A[R] > A[P],
    - A[R] + A[P] > A[Q].

예를 들어 배열 A가 다음과 같다면:
    A[0] = 10    A[1] = 2    A[2] = 5
    A[3] = 1     A[4] = 8    A[5] = 20
3요소 (0, 2, 4) 는 triangular 이다.

함수 작성:
    class Solution { public int solution(int[] A); }

정수 N개로 구성된 배열 A가 주어지고, triangular인 3요소가 있다면 1을 리턴, 그렇지 않다면 0을 리턴한다.

예를 들어 배열 A가 다음과 같이 주어지면:
    A[0] = 10    A[1] = 2    A[2] = 5
    A[3] = 1     A[4] = 8    A[5] = 20

함수는 위에 설명한대로 1을 리턴해야한다. 주어진 배열 A 가 다음과 같다면:
    A[0] = 10    A[1] = 50    A[2] = 5
    A[3] = 1
함수는 0을 리턴해야 한다.

가정:
- N은 [0..100,000] 범위의 정수;
- 배열 A의 각 요소는 [−2,147,483,648..2,147,483,647] 범위의 정수

복잡도:
- 최악의 시간 복잡도는 O(N*log(N)).
- 최악의 공간 복잡도는 O(N), (입력 공간 제외)

배열의 요소는 수정할 수 있다.





93%:
https://codility.com/demo/results/trainingYNR6RF-E4N/

100%:
https://codility.com/demo/results/trainingTDQPVB-PZ7/




2016년 6월 10일 금요일

[npm] 개발 전용으로 npm install (npm install --save develop)



개발 전용으로 npm install 하려면


$ npm install --save-dev 패키지명

package.json에 devDependencies 부분에 따로 관리된다.
 




 


- npm install dev save
- npm install --save dev
- npm install --save 개발


참고:
https://docs.npmjs.com/cli/install

2016년 6월 9일 목요일

[Algorithm] Codility Lesson 5 Prefix Sums - MinAvgTwoSlice

A non-empty zero-indexed array A consisting of N integers is given.
A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A
(notice that the slice contains at least two elements).
The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice.
To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1).

For example, array A such that:
    A[0] = 4
    A[1] = 2
    A[2] = 2
    A[3] = 5
    A[4] = 1
    A[5] = 5
    A[6] = 8

contains the following example slices:
- slice (1, 2), whose average is (2 + 2) / 2 = 2;
- slice (3, 4), whose average is (5 + 1) / 2 = 3;
- slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5.

The goal is to find the starting position of a slice whose average is minimal.

Write a function:
class Solution { public int solution(int[] A); }

that, given a non-empty zero-indexed array A consisting of N integers,
returns the starting position of the slice with the minimal average.
If there is more than one slice with a minimal average,
you should return the smallest starting position of such a slice.

For example, given array A such that:
    A[0] = 4
    A[1] = 2
    A[2] = 2
    A[3] = 5
    A[4] = 1
    A[5] = 5
    A[6] = 8

the function should return 1, as explained above.

Assume that:
- N is an integer within the range [2..100,000];
- each element of array A is an integer within the range [−10,000..10,000].

Complexity:
- expected worst-case time complexity is O(N);
- expected worst-case space complexity is O(N),
beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

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

N개의 정수로 구성된 비어있지 않은 배열 A가 주어진다. 0 ≤ P < Q < N 인 정수 쌍(P, Q)은 배열 A의 'slice'라고 부른다.
(slice 는 최소 두 요소를 포함 한다는 것을 참고)
slice (P, Q)의 평균은 A[P] + A[P + 1] + ... + A[Q] 를 slice의 길이로 나눈 것이다.
정확하게는  (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1) 이다.

예를 들어 배열 A가 다음과 같다면:
    A[0] = 4
    A[1] = 2
    A[2] = 2
    A[3] = 5
    A[4] = 1
    A[5] = 5
    A[6] = 8

다음과 같은 예시 slice를 포함한다.
- slice (1, 2), 평균은 (2 + 2) / 2 = 2;
- slice (3, 4), 평균은 (5 + 1) / 2 = 3;
- slice (1, 4), 평균은 (2 + 2 + 5 + 1) / 4 = 2.5.

목표는 평균이 최소인 slice 의 시작 지점을 찾는것이다.

함수 작성:
class Solution { public int solution(int[] A); }

N개의 정수로 구성된 비어있지 않은 배열 A가 주어지고, 최소 평균을 가지는 slice의 시작 지점을 리턴한다.
만약 최소 평균인 slice가 한 개 이상이라면, slice의 가장 작은 시작 지점을을 리턴해야 한다.

예를 들어 배열 A가 다음과 같다면:
    A[0] = 4
    A[1] = 2
    A[2] = 2
    A[3] = 5
    A[4] = 1
    A[5] = 5
    A[6] = 8

위에서 설명한대로 함수는 1을 리턴해야 한다.

가정:
- N은 [2..100,000] 사이의 정수
- 배열 A의 각 요소는 [−10,000..10,000] 사이의 정수

복잡도:
- 최악의 시간복잡도는 O(N);
- 최악의 공간복잡도는  O(N), (입력 공간 제외)





60%:
https://codility.com/demo/results/trainingMSQBM8-JVJ/

*** length 2 or 3의 슬라이스에서 최소 평균이 나온다는 증명을 활용
(https://codesays.com/2014/solution-to-min-avg-two-slice-by-codility/)

100%:
https://codility.com/demo/results/trainingMQ2A8R-9W2/

2016년 6월 7일 화요일

[Algorithm] Codility Lesson 5 Prefix Sums - GenomicRangeQuery

DNA 서열은 연속적인 뉴클레오티드의 종류에 대응하여 문자 A ,C, G, T로 구성된 문자열로 나타낼 수 있다.
각 뉴클레오티드는 정수인 'impact factor'를 가지고 있다.
뉴클레오티드 종류 A, C, G, T는 각각 1, 2, 3, 4의 'impact factor'를 가지고 있다.
당신은 다음 몇 가지 쿼리에 답 할 것이다:
주어진 DNA 서열의 특정 부분에 포함 되어있는 뉴클레오티드의 가장 작은 'impact factor'는 무엇인가?

DNA 서열은 N개의 문자로 구성 된 비어있지 않은 문자열 S = S[0]S[1]...S[N-1] 로 주어진다.
각 M개의 정수로 구성된 비어있지 않은 배열 P, Q 안에 M개의 쿼리가 있다.
K번째 쿼리(0 ≤ K < M)는
P[K]와 Q[K] 사이의 DNA 서열이 포함된 뉴클레오티드의 가장 작은 'impact factor'를 찾기를 요구한다.

예를 들어 문자열 S = CAGCCTA 이고 array P, Q 가 다음과 같다면:
    P[0] = 2    Q[0] = 4
    P[1] = 5    Q[1] = 5
    P[2] = 0    Q[2] = 6

M = 3 쿼리들의 답변들은 다음과 같을 것이다:
- 2와 4 사이의 DNA는 뉴클레오티드 G 와 C(두 번)를 포함하고 있다.
'impact factor'는 각각 3, 2이므로 답변은 2이다.
- 5와 5 사이에는 단일 뉴클레오티드 T를 포함하고, 'impact factor'는 4 이므로 답변은 4 이다.
- 0과 6 사이(전체 문자열)에는 모든 뉴클레오티드를 포함하고,
뉴클레오티드 A의 'impact factor'는 1 이므로 답변은 1 이다.

함수 작성:
class Solution { public int[] solution(String S, int[] P, int[] Q); }

N개의 문자로 구성된 비어있지 않은 문자열 S와 M개의 정수로 구성 된 비어있지 않은 배열 P, Q 두 개가 주어지면
모든 쿼리에 대한 연속적인 답변을 나타내는 M개의 정수로 구성된 배열을 리턴한다.

숫자열은 다음과 같아야 한다:
- 구조체 (C),
- 정수 벡터 (C++),
- 레코드 (Pascal),
- 정수 배열 (그 밖의 다른 프로그래밍 언어).

예를 들어 문자열 S = CAGCCTA 이고 array P, Q 가 다음과 같다면:
    P[0] = 2    Q[0] = 4
    P[1] = 5    Q[1] = 5
    P[2] = 0    Q[2] = 6
함수는 위에서 설명한 대로 [2, 4, 1]를 리턴해야 한다.

가정 :
- N 은 [1..100,000] 범위의 정수;
- M 은 [1..50,000] 범위의 정수;
- 배열 P, Q의 각 요소는 [0..N − 1] 범위의 정수;
- 0 ≤ K < M라면 P[K] ≤ Q[K];
- 문자열 S는 알파벳 대문자 A, C, G, T로만 구성된다.

복잡도 :
최악의 시간복잡도는 O(N+M);
최악의 공간복잡도는 O(N) (입력 공간 제외)

배열의 요소는 수정할 수 있다.





75%:
https://codility.com/demo/results/trainingSCPXKP-K28/

100% :
https://codility.com/demo/results/trainingFQSN7X-U64/

2016년 6월 4일 토요일

[Algorithm] Codility Lesson 5 Prefix Sums - CountDiv

 함수 작성:
 class Solution { public int solution(int A, int B, int K); }
 정수 A, B, K가 주어지고, 범위 [A..B] 안에서 K로 나누어 떨어지는 정수의 값을 리턴
 즉 : { i : A ≤ i ≤ B, i mod K = 0 }

 예를 들어 A = 6, B = 11, K = 2 면, 함수는 3을 리턴해야 한다.
 왜냐하면 범위 [6..11] 안에 2로 나누어 떨어지는 숫자가 6, 8, 10 3개 있기 때문이다.

 가정:
 A,B는 [0..2,000,000,000] 범위의 정수;
 K는 [1..2,000,000,000] 범위의 정수;
 A ≤ B.

 복잡도:
 최악의 시간복잡도는 O(1);
 최악의 공간복잡도는 O(1);





https://codility.com/demo/results/trainingBTWCPP-XMG/

2016년 6월 3일 금요일

[Algorithm] Codility Lesson 5 Prefix Sums - Prefix Sums

N개의 정수로 구성된 비어있지 않은 배열 A가 주어진다.
배열 A의 연속된 요소는 길 위의 연속된 자동차를 나타낸다.

배열 A는 0,1 만 포함한다:
- 0 은 자동차가 동쪽으로 이동중임을 나타내고,
- 1 은 자동차가 서쪽으로 이동중임을 나타낸다.

목표는 통과하는 자동차를 세는것이다.
자동차 한 쌍(P,Q)은 0 ≤ P < Q < N이고 P는 동쪽으로 이동하고 Q 는 서쪽으로 이동하며 통과할 때를 말한다.

예를 들어 배열 A가 다음과 같다고 하면:
A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1
우리는 통과하는 차 중에 다섯 쌍을 가지고 있다 : (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).

함수 작성:
class Solution { public int solution(int[] A); }
정수 N개의 비어있지 않은 배열 A가 주어지고, 통과하는 차의 쌍 수를 리턴한다.

통과하는 차의 쌍 수가 1,000,000,000를 초과하면 함수는 -1을 리턴해야 한다.

예를들어 다음과 같이 주어진다면:
A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1
위에서 설명한대로 함수는 5를 리턴해야 한다.

가정:
- N은 [1..100,000] 범위의 정수이다.
- 배열 A의 각 요소는 0, 1 중 하나의 값만을 가질 수 있다.

복잡도:
- 최악의 시간복잡도는 O(N);
- 최악의 공간복잡도는 O(1), 입력 값 제외

배열의 요소는 수정할 수 있다.





90%
https://codility.com/demo/results/trainingBN4EAQ-52Q/

100%
https://codility.com/demo/results/trainingVNJ5UB-TCQ/

2016년 6월 2일 목요일

[Algorithm] Codility Lesson 4 Counting Elements - MaxCounters

0으로 초기화 되어있는 N개의 카운터가 주어지고, 두 가지 연산이 있다.
- increase(X) − 카운터 X 를 1 증가시킨다.
- max counter − 모든 카운터를 카운터 최대값으로 설정한다.

M개의 정수로 구성된 비어있지 않은 배열 A가 주어진다. 이 배열은 다음의 연속적인 연산을 나타낸다.
- 만약 A[K] = X 가 1 ≤ X ≤ N 면 연산 K는 increase(X)이고,
- 만약 A[K] = N + 1 이면 연산 K 는 max counter 이다.

예를 들어, N = 5 이고 배열 A가 다음과 같이 주어진다면
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4

연속되는 각각의 연산 후에 카운터들의 값은 다음과 같을 것이다.
(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)

목표는 모든 연산 후에 모든 카운터의 값을 산출하는 것이다.

함수 작성:
class Solution { public int[] solution(int N, int[] A); }
정수 N과 M개의 정수로 구성된 비어있지 않은 배열 A가 주어지고
카운터들의 값을 나타낸 연속된 정수를 리턴한다.

수열은 다음과 같아야 한다:
- 구조체 (C),
- 정수 벡터 (C++),
- 레코드 (Pascal),
- 정수 배열 (그 밖의 다른 프로그래밍 언어).

예를들어 다음과 같이 주어진다면
A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4

위에서 설명한대로 함수는 [3, 2, 2, 4, 2]를 리턴해야 한다.

가정:
N 과 M은 [1..100,000] 범위의 정수이다.
배열 A의 각 요소는 [1..N + 1] 범위의 정수이다.

복잡도:
최악의 시간복잡도는 O(N+M);
최악의 공간복잡도는 O(N), 입력 공간 제외.

입력된 배열의 요소는 수정 될 수 있다.





88%
https://codility.com/demo/results/trainingUKVD8F-3R7/

100%
https://codility.com/demo/results/trainingFVZK33-75M/

2016년 5월 31일 화요일

[Algorithm] Codility Lesson 4 Counting Elements - MissingInteger

 함수 작성:
 class Solution { public int solution(int[] A); }
 N개의 정수로 구성된 배열 A가 주어지고, A에 없는 가장 작은 양수 (0보다 큰)를 리턴한다.

 예를들어
 A[0] = 1
 A[1] = 3
 A[2] = 6
 A[3] = 4
 A[4] = 1
 A[5] = 2
 가 주어지면 함수는 5를 리턴해야 한다.

 가정:
 N 은 [1..100,000] 범위의 정수
 배열 A의 각 요소는  [−2,147,483,648..2,147,483,647] 범위의 정수

 복잡도:
 최악의 시간복잡도는 O(N);
 최악의 공간복잡도는 O(N) (입력 공간 제외)
 배열의 요소들은 수정될 수 있다.






https://codility.com/demo/results/trainingR78BM7-68F/

2016년 5월 30일 월요일

[Algorithm] Codility Lesson 4 Counting Elements - PermCheck

정수 N개로 구성된 비어있지 않은 배열 A가 주어진다.
permutation이란 1부터 N까지 각 요소를 단 한 번만 포함하는 숫자들이다.

예를들어 배열 A가 다음과 같다면:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
permutation이다. 하지만 배열 A가 다음과 같다면:
A[0] = 4
A[1] = 1
A[2] = 3
permutation이 아니다. 왜냐하면 2가 빠졌기 때문이다.

목표는 배열 A가 permutation인지 아닌지 확인하는 것이다.

함수 작성:
class Solution { public int solution(int[] A); }
배열 A가 주어지고, 배열 A가 permutation이라면 1을 리턴 아니면 0을 리턴한다.

예를들어 배열 A가 다음과 같다면
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
함수는 1을 리턴해야한다.

배열 A가 다음과 같다면:
A[0] = 4
A[1] = 1
A[2] = 3
함수는 0을 리턴해야한다.

가정:
N은 [1..100,000] 범위의 정수이다.
배열 A의 각 요소는 [1..1,000,000,000] 범위의 정수이다.

복잡도:
최악의 시간복잡도는 O(N);
최악의 공간복잡도는 O(N) (입력공간 제외)
입력 배열의 요소는 수정할 수 있다.





https://codility.com/demo/results/trainingWXN3W6-5WB/

2016년 5월 29일 일요일

[Algorithm] Codility Lesson 4 Counting Elements - FrogRiverOne

작은 개구리는 강의 반대편으로 가고 싶어 한다.
개구리는 처음에 강 둑 한 곳(위치 0)에 위치해 있고 반대쪽 둑(위치 X+1)으로 가고 싶어 한다.
잎들은 나무에서 강 표면으로 떨어진다.

떨어진 잎을 표현하는 N 개의 정수로 이루어진 배열 A가 주어진다.
A[K]는 K초에 떨어지는 잎의 위치를 표시한다.

목표는 개구리가 강의 반대편으로 점프할 수 있는 가장 빠른 시간을 찾는것이다.
개구리는 1부터 X 위치 까지 강을 건너는 동안 잎이 나타날 때만 이동할 수 있다.
(우리는 잎이 있는 위치만으로 1부터 X까지 이동하는 가장 빠른 시간을 찾기 원한다는 것이다.)
강에 있는 동안의 속도는 무시할 만큼 작다고 가정할 것이다.
즉 잎은 강에 떨어진 후에 위치가 변하지 않는다.

예를 들어 정수 X = 5 이고 배열 A가 다음과 같다면
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
6초에 잎이 위치 5에 떨어진다.
이것이 잎이 강을 가로 지르는 모든 위치에 나타나는 가장 빠른 시간이다.

함수 작성:
class Solution { public int solution(int X, int[] A); }
N개의 정수로 구성된 비어있지 않은 배열 A와 정수X가 주어지면
개구리가 강의 반대편으로 점프할 수 있는 가장 작은 시간을 리턴한다.

만약 개구리가 강의 반대편으로 점프할 수 없다면, 함수는 -1을 리턴해야 한다.

예를들어 정수 X = 5 이고 배열 A가 다음과 같다면
A[0] = 1
A[1] = 3
A[2] = 1
A[3] = 4
A[4] = 2
A[5] = 3
A[6] = 5
A[7] = 4
위에서 설명한 것처럼 함수는 6을 리턴해야한다.

가정 :
N 과 X는 [1..100,000] 범위의 정수;
A의 모든 요소는 [1..X] 범위의 정수이다.

복잡도 :
최악의 시간복잡도는 O(N);
최악의 공간복잡도는 O(X) (입력 공간 제외)
배열의 모든 요소는 수정 가능하다.





https://codility.com/demo/results/training9GNH47-G8Z/

2016년 5월 25일 수요일

[Algorithm] Codility Lesson 3 - PermMissingElem

배열 A는 N개의 각기 다른 정수로 구성된다.
배열은 [1..(N + 1)] 범위의 정수를 포함하며, 단 하나의 요소만 빠져있다. 목표는 빠진 요소를 찾는 것이다.

함수 작성 :
class Solution { public int solution(int[] A); }
배열 A를 받아서, 빠진 요소를 리턴한다.

예를 들어 배열 A 가 다음과 같다면:
A[0] = 2
A[1] = 3
A[2] = 1
A[3] = 5
함수는 빠진 요소인 4를 리턴 할 것이다.

가정 :
N은 [0..100,000] 범위의 정수;
A의 요소는 모두 다르다.
A의 각 요소는 [1..(N + 1)] 범위의 정수이다.

복잡도:
최악의 경우 시간복잡도는 O(N);
최악의 경우 공간복잡도는 O(1), 입력 받을 공간 제외
입력받은 배열의 요소는 수정될 수 있다.





https://codility.com/demo/results/trainingB3DXRP-WUF/

2016년 5월 23일 월요일

[Algorithm] Codility Lesson 3 - TapeEquilibrium

 비어있지 않은 배열 A는 N개의 정수로 구성되어 있다. 배열 A는 테잎의 숫자들을 나타낸다.

 0 < P < N 인 정수 P는 테잎을 비어있지 않은 두 파트로 나눈다:
 A[0], A[1], ..., A[P − 1], A[P], A[P + 1], ..., A[N − 1].

 두 파트간의 차이 값을 구하는 식은 :
 |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|

 다시 말하면, 첫 파트의 합계와 두번째 파트의 합계 차이값의 절대값이다.

 예를 들어 다음과 같은 배열 A가 있다면:
 A[0] = 3
 A[1] = 1
 A[2] = 2
 A[3] = 4
 A[4] = 3

 4가지 방법으로 나눌 수 있다.:
 P = 1, 차이 = |3 − 10| = 7
 P = 2, 차이 = |4 − 9| = 5
 P = 3, 차이 = |6 − 7| = 1
 P = 4, 차이 = |10 − 3| = 7

 함수 작성:
 int solution(int A[], int N);

 N 개의 정수로 구성된 비어있지 않은 배열 A, 차이값의 최소값을 리턴한다.

 예를 들어
 A[0] = 3
 A[1] = 1
 A[2] = 2
 A[3] = 4
 A[4] = 3
 가 주어진다면, 상술 한 바와 같이 함수는 1을 리턴하게 된다.

 가정:
 N 은 [2..100,000] 범위의 정수
 배열의 각 요소는 [−1,000..1,000] 범위의 정수

 복잡도 :
 최악의 시간복잡도는 O(N)
 최악의 공간복잡도는 O(N) (입력값을 위한 공간 제외)
 배열의 요소는 수정 가능하다.



https://codility.com/demo/results/trainingVW44CT-URM/

2016년 5월 20일 금요일

[Algorithm] Codility Lesson 3 - FrogJmp



작은 개구리는 길을 건너고 싶어한다. 개구리는 현재 X 위치에 있고 Y 보다 같거나 큰 위치로 이동하길 원한다. 개구리는 항상 고정된 D 거리 만큼을 점프한다.

작은 개구리가 목적을 달성할 수 있는 가장 작은 점프 횟수를 구해라.

함수는 X, Y, D 세 개의 int 파라미터가 주어지고, X에서 Y보다 같거나 큰 위치로 이동시 가장 작은 점프 횟수를 리턴하도록 작성

예를 들어
 X = 10
 Y = 85
 D = 30
 가 주어진다면 개구리가 아래처럼 이동하기 때문에 리턴은 3이다.
 첫 점프 후 위치는     10 + 30 = 40
 두 번째 점프 후 위치는   10 + 30 + 30 = 70
 세 번째 점프 후 위치는  10 + 30 + 30 + 30 = 100

 가정 :
 X, Y, D 는 [1..1,000,000,000] 범위의 정수;
 X ≤ Y.

 복잡성 :
 최악의 시간 복잡도는 O(1).
 최악의 공간 복잡도는 O(1).


https://codility.com/demo/results/trainingWDWBJC-B3J/

[Bootstrap] 버튼 로딩 효과 / button loading


<button type="button" id="myButton" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off">
  Loading state
</button>

<script>
  $('#myButton').on('click', function () {
    var $btn = $(this).button('loading');
    // business logic...
    $btn.button('reset');
  })
</script>






참고 :
http://getbootstrap.com/javascript/#buttons

2016년 5월 19일 목요일

[Algorithm] Codility Lessons

Lesson 1 / Iterations
- https://codility.com/demo/results/trainingBFYF8S-38C/


Lesson 2 / Arrays

1. CyclicRotation
- https://codility.com/demo/results/training94SFQB-X5K/

2. OddOccurrencesInArray
- https://codility.com/demo/results/training8547WH-RU7/





2016년 5월 2일 월요일

[Spring Boot] Building a RESTful Web Service 가이드

가이드에 따라 진행해보자


http://spring.io/guides/gs/rest-service/
==================================================








http://spring.io/guides/gs/sts/
Spring Tool Suite (STS) 이용하려면 위 페이지 스샷을 참고하고 마지막 프로젝트 템플릿 중 Consuming Rest 대신 Rest Service를 선택하면 된다.


선택하고 나면 두 개의 프로젝트가 생기게 되는데
gs-rest-service-initial 프로젝트는 초기화 된 상태의 프로젝트고
gs-rest-service-complete 프로젝트는 가이드를 완료한 결과 상태의 프로젝트이다.




따라서 gs-rest-service-initial 에 아래 코드를 작성하면 된다.




출력 될 데이터 형태를 정의한 Greeting.java 클래스를 작성한다.
package hello;

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}


컨트롤러인 GreetingController도 작성 한다.
package hello;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}


마지막으로 어플리케이션을 실행할 수 있도록 해주는 Application.java 를 작성한다.
package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


스프링을 사용해 봤다면 크게 새로운것은 없다.




필요한 항목은 모두 작성 되었고 실행은 STS 상에서 간단히 가능하다.
(프로젝트 우클릭 -> Run As -> Spring Boot App)




서버 구동 후
http://localhost:8080/greeting?name=User 접속시


{"id":2,"content":"Hello, User!"}
형태로 출력된다면 정상적으로 완료 된 것이다.



완료 소스 :