본문 바로가기
알고리즘/Codewars

[Codewars] Holiday VI - Shark Pontoon (8 kyu) / JavaScript

by fluss 2022. 10. 11.

https://www.codewars.com/kata/57e921d8b36340f1fd000059

 

Codewars - Achieve mastery through coding practice and developer mentorship

Coding practice for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Your friend invites you out to a cool floating pontoon around 1km off the beach. Among other things, the pontoon has a huge slide that drops you out right into the ocean, a small way from a set of stairs used to climb out.

As you plunge out of the slide into the water, you see a shark hovering in the darkness under the pontoon... Crap!

You need to work out if the shark will get to you before you can get to the pontoon. To make it easier... as you do the mental calculations in the water you either freeze when you realise you are dead, or swim when you realise you can make it!

You are given 5 variables;

  • sharkDistance = distance from the shark to the pontoon. The shark will eat you if it reaches you before you escape to the pontoon.
  • sharkSpeed = how fast it can move in metres/second.
  • pontoonDistance = how far you need to swim to safety in metres.
  • youSpeed = how fast you can swim in metres/second.
  • dolphin = a boolean, if true, you can half the swimming speed of the shark as the dolphin will attack it.
  • The pontoon, you, and the shark are all aligned in one dimension.

If you make it, return "Alive!", if not, return "Shark Bait!".

 

설명:

당신의 친구가 당신을 해변에서 1km쯤 떨어진 멋진 폰툰으로 초대했습니다. 무엇보다도, 폰툰은 바다로 바로 떨어지는 커다란 미끄럼틀이 있고, 내려가는 계단에서 조금 떨어져 있습니다.

미끄럼틀에서 물속으로 뛰어들 때, 당신은 상어가 폰툰 아래의 어둠 속에서 맴도는 것을 보았습니다... 젠장! 당신이 폰툰에 도착하기 전에 상어가 당신에게 도착하는지 확인해야 합니다. 쉽게 만들자면... 물속에서 정신적인 계산을 할 때 당신은 당신이 죽었다는 것을 알고 얼어붙거나 당신이 해낼 수 있다는 것을 깨닫고 수영을 할 수 있습니다.

 

당신에게 5가지 변수가 주어집니다;

  • sharkDistance = 상어에서 폰툰까지의 거리. 당신이 폰툰으로 달아나기 전에 상어가 당신에게 닿으면 상어는 당신을 잡아먹을 것입니다.
  • sharkSpeed = 상어가 얼마나 빠르게 움직일 수 있는지(미터/초 단위).
  • pontoonDistance = 안전해지려면 얼마나 수영해야하는지(미터 단위).
  • youSpeed = 수영할 수 있는 속도(미터/초 단위).
  • dolphin = 불리언, 참이라면, 돌고래가 상어를 공격하므로써 상어의 수영속도를 절반으로 줄일 수 있습니다..
  • 폰툰, 당신, 그리고 상어는 일차원에 정렬되어 있습니다.

당신이 해낸다면, "Alive!"를 반환하고, 그렇지 않다면, "Shark Bait!"를 반환합니다.

 

풀이

function shark(pontoonDistance, sharkDistance, youSpeed, sharkSpeed, dolphin){
  if(dolphin) sharkSpeed /= 2;
  if(sharkDistance / sharkSpeed < pontoonDistance / youSpeed) return "Shark Bait!";
  else return "Alive!"
}

sharkDistance에서 sharkSpeed를 나누면 상어가 폰툰까지 도착하는 데 걸리는 시간이 나오고 pontoonDistance에서 youSpeed를 나누면 사람이 폰툰까지 도착하는 시간이 걸리는데 시간이 짧을수록 빨리 도착하는 것이므로 상어가 폰툰까지 도착하는 데 걸리는 시간이 사람이 폰툰까지 도착하는 데 걸리는 시간보다 짧으면 "Shark Bait!"를 반환 그렇지 않은 경우에는 "Alive!"를 반환한다.

댓글