코딩공부/프로그래머스

※[프로그래머스]Lv.2 과제 진행하기 C#

usingsystem 2023. 6. 21. 23:21
728x90

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

 

프로그래머스

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

programmers.co.kr

소스코드

처음에 문제를 풀 때 다음 문제설명에 있는 "진행 중이던 과제를 끝냈을 때, 잠시 멈춘 과제가 있다면, 멈춰둔 과제를 이어서 진행합니다." 부분이 잠시 멈춘 과제가 그다음 진행 중인 시간 안에 온전히 포함될 때 한번에 끝내야 하는 줄 알았다 만약 멈춰둔 과제가 10분이 남았고 진행 중이던 과제가 종료되고 다음 과제까지 5분이 남았다면 멈춰둔 과제는 -5분을 해줘야 하는 것 을 나중에 깨달았으며 그래서 while문 안에 로직을 풀어 냈다. c# stack은 수정이 안되기 때문에 pop을 한 후 push를 하였다. List<(string, int, int)> 부분은 좋기는 하지만 수정이 안된다. tuple과 같은 것 같다. ㅠ

using System;
using System.Collections.Generic;
using System.Linq;
public class Solution
{
    public string[] solution(string[,] plans)
    {
        var answer = new List<string>();

        List<(string, int, int)> list = new List<(string, int, int)>();
        for (int i = 0; i < plans.GetLength(0); ++i)
        {
            string[] split = plans[i, 1].Split(':');
            int item2 = (int.Parse(split[0]) * 60) + int.Parse(split[1]);
            int item3 = int.Parse(plans[i, 2]);

            list.Add((plans[i, 0], item2, item3));
        }

        list = list.OrderBy(o => o.Item2).ToList();

        Stack<(string, int)> temp = new Stack<(string, int)>();
        for (int i = 0; i < list.Count - 1; i++)
        {
            string plan = list[i].Item1;
            int finishT = list[i].Item2 + list[i].Item3;
            int futerT = list[i + 1].Item2;

            if (finishT <= futerT)
            {
                answer.Add(plan);

                int betweenT = futerT - finishT;
                while (betweenT > 0 && temp.Count > 0)
                {
                    string name = temp.Peek().Item1;
                    var pastT = temp.Peek().Item2;
                    int div = betweenT - pastT;

                    if (div >= 0)
                    {
                        answer.Add(temp.Pop().Item1);
                        betweenT = div;
                    }
                    else
                    {
                        temp.Pop();
                        temp.Push((name, pastT - betweenT));
                        betweenT = div;
                        break;
                    }
                }
            }
            else
            {
                temp.Push((list[i].Item1, finishT - futerT));
            }
        }
        answer.Add(list[list.Count - 1].Item1);

        answer.AddRange(temp.Select(x => x.Item1));
        return answer.ToArray();
    }
}
728x90