문제
Task
Each day a plant is growing by upSpeed meters. Each night that plant's height decreases by downSpeed meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know when the height of the plant will reach a certain level.
Example
For upSpeed = 100, downSpeed = 10 and desiredHeight = 910, the output should be 10.
After day 1 --> 100
After night 1 --> 90
After day 2 --> 190
After night 2 --> 180
After day 3 --> 280
After night 3 --> 270
After day 4 --> 370
After night 4 --> 360
After day 5 --> 460
After night 5 --> 450
After day 6 --> 550
After night 6 --> 540
After day 7 --> 640
After night 7 --> 630
After day 8 --> 730
After night 8 --> 720
After day 9 --> 820
After night 9 --> 810
After day 10 --> 910
For upSpeed = 10, downSpeed = 9 and desiredHeight = 4, the output should be 1.
Because the plant reach to the desired height at day 1(10 meters).
After day 1 --> 10
더 자세한 내용은 홈페이지 참고.
코드
CREATE OR REPLACE FUNCTION plant(down int, up int, desired_height int)
RETURNS INTEGER AS $$
DECLARE
day INTEGER := 0;
height INTEGER := 0;
BEGIN
WHILE height <= desired_height
LOOP
height := height + up;
day := day + 1;
IF height < desired_height THEN
height := height - down;
ELSE
RETURN day;
END IF;
END LOOP;
RETURN day;
END;
$$ LANGUAGE plpgsql;
SELECT
id,
plant(down_speed, up_speed, desired_height) as num_days
FROM growing_plant;
함수를 만들어서 풀었다.
더 쉽고 간단하게 하려면, 아래처럼 풀면 된다.
SELECT
id,
CASE WHEN desired_height <= up_speed THEN 1
ELSE CEIL((desired_height - up_speed)::decimal / (up_speed - down_speed))::int + 1 END AS num_days
FROM growing_plant;
설명
반복문을 활용하여 더하고 빼기를 반복하면 된다.
'컴퓨터과학 > Algorithm' 카테고리의 다른 글
[SQL] [Codewars] 7Kyu - SQL: Regex Replace (0) | 2021.11.04 |
---|---|
[Python] [백준] 1076번 저항 (0) | 2021.10.21 |
[SQL] [Codewars] 7Kyu - SQL with LOTR: Elven Wildcards (0) | 2021.10.21 |