본문 바로가기
c#

프로그래머스 - 기능개발 Lv.2

by Oliver' 2022. 4. 6.

c# 자료형과 메서드에 익숙해지기 위해 코딩테스트 문제를 풀어봤다.

 

Stack / Que를 이용해서 풀면 좋을 것 같은데 첫 시도에서는 생각나는대로 풀어봤고, 기본적인 for문, continue 전체 조회 방식으로 해결했다. 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
public class Solution {
    public int[] solution(int[] progresses, int[] speeds) {
        List<int> dateList = new List<int>();
            List<int> cntList = new List<int>();
 
            // dateList에 각 progress별 완성까지 걸리는 시간 입력
            for (int i = 0; i < progresses.Length; i++)
            {
                int progress = progresses[i];
                int speed = speeds[i];
                int date = 0;
                while(progress < 100)
                {
                    progress += speed;
                    date++;
                }
                dateList.Add(date);
            }
 
            
           
// dateList를 조회. 조건에 따라 cnt++(하루에 배포되는 프로그램 수), cntList.Add()를 해준다.
            int cnt = 1; // cnt = 하루에 배포되는 프로그램 count
            int date1 = dateList[0]; // date1 = 완성 시간 비교를 위한 변수.
 
            for (int i = 0; i < dateList.Count; i++)
            {
                for(int j = i+1; j < dateList.Count; j++)
                {
                    if(date1 >= dateList[j])   
                    {
                        cnt++;
                        i = j - 1;  // 다음 for문에서 ++ 돼서 불필요한 i값 계산을 생략
                        if(i != dateList.Count - 1)
                            continue;
                    }
 
                    date1 = dateList[j];
                    cntList.Add(cnt);
                    cnt = 1;
                    i = j - 1;  // 다음 for문에서 ++ 돼서 불필요한 i값 계산을 생략. cnt++이 되던지, cntList.Add()가 되던지 i 생략이 필요.
                }
            }
 
            cntList.Add(cnt);   // 마지막 cnt 추가
            int[] answer = cntList.ToArray();   // Array로 형변환해서 반환
            return answer;
    }
}
cs

 

다른 사람 풀이를 보니 array.Select 라는 기능을 활용해 간단하게 progress별 완성에 소요되는 시간을 구한 경우가 있었다. 

progresses의 item, idx 정보를 가지고 Math.Ceiling((100 - item) / speeds[idx]) 를 tmp로 입력했다.

다음 문제 풀이 때 배열을 입력받아 해결하는 문제가 생기면 활용해봐야겠다.

1
var tmp = progresses.Select((item, idx) => (int)Math.Ceiling( (double)(100 - item) / speeds[idx] ));
cs