주녘공부일지

[프로그래머스 C#] Lv.2 우박수열 정적분 본문

Programmers - C#/CodingTest Lv.2

[프로그래머스 C#] Lv.2 우박수열 정적분

주녘 2024. 1. 16. 16:23
728x90

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

 

프로그래머스

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

programmers.co.kr

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

주어진 조건에 따라 그래프에 둘러쌓인 영역의 넓이를 구하는 문제

- 조건에 따라 찍은 점을 이어서 생긴 우박수열 그래프와 y = 0, x = a, x = n - b 그래프로 둘러쌓인 영역의 넓이를 구하면 됨

( ranges 배열의 원소 [ a, b ], n : 우박수열의 개수 - 1 )

 

주석 참조

    using System;
    using System.Collections.Generic;

    public class Solution
    {
        public double[] solution(int k, int[,] ranges)
        {
            var answerList = new List<double>();
            var list = new List<int>() { k }; // 우박수열

            // 우박수열 세팅
            while (k > 1)
            {
                if (k % 2 == 0)
                    k /= 2;
                else
                    k = k * 3 + 1;

                list.Add(k);
            }

            // 한칸에 대한 넓이를 미리 연산 ( ex. 0 : 0 ~ 1 넓이 )
            var doubleArray = new double[list.Count - 1];
            for (int i = 0; i < doubleArray.Length; i++)
            {
                doubleArray[i] += Math.Min(list[i], list[i + 1]); // 사각형 영역
                doubleArray[i] += Math.Abs(list[i] - list[i + 1]) * 0.5d; // 삼각형 영역
            }

            // 주어진 범위 내의 넓이를 더해서 추가
            for (int i = 0; i < ranges.GetLength(0); i++)
            {
                int startPosX = ranges[i, 0];
                int endPosX = doubleArray.Length + ranges[i, 1];

                // 시작 점이 끝 점보다 클 경우 -1
                if (startPosX > endPosX)
                {
                    answerList.Add(-1);
                    continue;
                }

                // 구해놓은 넓이를 이용해 주어진 영역의 넓이를 구함
                double total = 0;
                for (int j = startPosX; j < endPosX; j++)
                    total += doubleArray[j];

                answerList.Add(total);
            }

            return answerList.ToArray();
        }
    }

 

728x90