[PCCP 기출문제] 1번 / 동영상 재생기

2024. 10. 25. 01:56코딩테스트 문제 풀이/[프로그래머스]

핵심 : 뒤로가기 혹은 앞으로가기 할때마다 오프닝 구간에 속해 있는지를 체크하라

using System;

public class Solution
{
    private const string TO_PREV = "prev";
    private const string TO_NEXT = "next";
    private const int MOVE_VALUE = 10;
    private const int ONE_MINUTE = 60;
    private int _posTime;

    public string solution(string video_len, string pos, string op_start, string op_end, string[] commands)
    {
        _posTime = ConvertTimeToSeconds(pos);

        var videoTime = ConvertTimeToSeconds(video_len);        
        var opStartTime = ConvertTimeToSeconds(op_start);
        var opEndTime = ConvertTimeToSeconds(op_end);

        SkipOpening(opStartTime, opEndTime);

        for (int i = 0; i < commands.Length; i++)
        {
            var command = commands[i];
            if(command.Equals(TO_PREV))
            {
                _posTime -= MOVE_VALUE;
            }
            else if (command.Equals(TO_NEXT))
            {
                _posTime += MOVE_VALUE;
            }

            CheckVideoLength(videoTime);
            SkipOpening(opStartTime, opEndTime);
        }

        return ConvertSccondsToTime(_posTime);
    }
    
    private void CheckVideoLength(int videoTime)
    {
        if (_posTime < 0)
        {
            _posTime = 0;
        }
        else if (_posTime > videoTime)
        {
            _posTime = videoTime;
        }
    }

    private void SkipOpening(int startTime, int endTime)
    {
        _posTime = startTime <= _posTime && _posTime <= endTime ? endTime : _posTime;
    }

    private int ConvertTimeToSeconds(string time)
    {
        var splitTime = time.Split(':');
        var minute = splitTime[0];
        var second = splitTime[1];

        var parsedMinute = int.Parse(minute);
        var convertedTime = parsedMinute != 0 ? parsedMinute * ONE_MINUTE : 0;

        return convertedTime + int.Parse(second);
    }

    private string ConvertSccondsToTime(int secondsTime)
    {
        var minute = secondsTime / ONE_MINUTE;
        var seconds = secondsTime - minute * ONE_MINUTE;
        return $"{minute:D2}:{seconds:D2}";
    }
}

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