2015년 12월 18일 금요일

자바스크립트 정렬코드 (2)

정렬코드를 위해 간단한 함수를 만들어 보았다.

stage_dt =[{stage:2, score:30},{stage:4, score:90},{stage:7, score:45}]
라고 한다면,

1. stage에 원하는 스테이지 값을 넣으면, 그 스테이지의 값을 리턴해준다.
2. stage값이 배열에 없다면, -로 넣어주어야 할 장소를 리턴한다.
3. stage값이 배열에 없고, 배열의 제일 처음에 넣어야 한다면 -1000을 리턴한다.
4. stage값이 배열에 없고, 배열의 제일 끝에 넣어야 한다면 -2000을 리턴한다.

string함수 중 하나인 splice를 써서 배열에 값을 추가해 주었다.

예제 소스는 다음과 같다.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
var stage_dt =[{stage:2, score:30},{stage:4, score:90},{stage:7, score:45}]
var stage = 4;
var temp_u = {};
temp_u.stage = stage;
temp_u.score = 11;
var position = find_top_score(stage, stage_dt);
if(position < 0){
    if(position == -1000){
        stage_dt.splice(0,0, temp_u);
    }else if(position == -2000){
        stage_dt.splice(stage_dt.length,0, temp_u);
    }else{
        position = position*(-1);
        stage_dt.splice(position,0, temp_u);
    }
}else{
    stage_dt[position].score = temp_u.score;
}
function find_top_score(stage, stage_dt){
    
    var position = 0;
    var m_p_f = 0;
    
    var stages_size = stage_dt.length;
    
    if(stage >= stages_size){
        position = stages_size-1;
    }else{
        position = stage -1;
    }
    
    do{
        value = stage - stage_dt[position].stage;
        if(value == 0){
            return position;
        }else if(value < 0){
            if(position == 0){
                return -1000;
            }else if(m_p_f == 1){
                return ((position+1)*(-1));
            }else{
                position --;
                m_p_f = -1;
            }
        }else{
            if(position == stages_size-1){
                return -2000;
            }else if(m_p_f == -1 ){
                return (-1*(position+1));
            }else{
                position ++;
                m_p_f = 1;
            }
        }
    }while(true);
}
cs

댓글 없음:

댓글 쓰기