주녘공부일지

[프로그래머스 C#] Lv.3 디스크 컨트롤러 본문

Programmers - C#/CodingTest Lv.3

[프로그래머스 C#] Lv.3 디스크 컨트롤러

주녘 2024. 5. 22. 18:36
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/42627

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 정답코드 및 핵심 아이디어, 유의사항

조건에 따라 요청된 작업들을 처리하는 데 걸리는 평균 시간의 최소 값을 반환하는 문제

- 한번 시작한 작업은 멈출 수 없음

- 수행 중인 작업이 없고 수행 할 수 있는 작업이 있다면 반드시 수행해야 함

- 현재 시간에 수행이 가능한 작업 중에 가장 소요 시간이 적은 작업을 우선 수행해야 함

 

풀이 핵심

- 요청 받기 전 작업과, 요청 받은 후 작업 리스트를 나누어 연산

- 현재 시간에 따라 요청 받은 리스트를 갱신

- 요청 받은 리스트 중에 작업 수행 시간이 가장 짧은 작업부터 우선 수행

 

주석 참조

using System;
using System.Collections.Generic;

public class Solution
{
    public class DataClass
    {
        public int startTime; // 요청 시작 시간
        public int playTime; // 작업 소요 시간

        public DataClass(int startTime, int playTime)
        {
            this.startTime = startTime;
            this.playTime = playTime;
        }
    }

    // 정렬 메서드
    public int CompareTo(int x, int y) => (x > y) ? 1 : -1;

    public int solution(int[,] jobs)
    {
        int answer = 0; // 소요 시간 토탈
        var jobList = new List<DataClass>(); // 요청받을 예정인 작업 리스트
        var list = new List<DataClass>(); // 요청받은 작업 리스트

        // 데이터 정제
        for (int i = 0; i < jobs.GetLength(0); i++)
            jobList.Add(new DataClass(jobs[i, 0], jobs[i, 1]));

        // 데이터 정렬 (요청 시간 기준 오름차순)
        jobList.Sort((x, y) => CompareTo(x.startTime, y.startTime));

        int currTime = 0; // 현재 시간

        // 작업할 디스크가 없을 때까지 수행
        while (jobList.Count > 0 || list.Count > 0)
        {
            // 요청 받은 작업 갱신
            while (jobList.Count > 0 && jobList[0].startTime <= currTime)
            {
                list.Add(jobList[0]);
                jobList.RemoveAt(0);
            }

            if (list.Count > 0)
            {
                // 작업 소요 시간을 기준으로 오름차순 정렬
                list.Sort((x, y) => CompareTo(x.playTime, y.playTime));

                // 작업 소요 시간이 가장 짧은 요청 받은 작업 수행
                currTime += list[0].playTime;
                answer += currTime - list[0].startTime;
                list.RemoveAt(0);
            }
            else
                currTime++;
        }

        return answer / jobs.GetLength(0); // 평균
    }
}
728x90