HR - Apple & Orange

Goody·2021년 2월 2일
0

알고리즘

목록 보기
24/122

문제

Sam's house has an apple tree and an orange tree that yield an abundance of fruit. Using the information given below, determine the number of apples and oranges that land on Sam's house.

In the diagram below:

  • The red region denotes the house, where s is the start point,
    and t is the endpoint. The apple tree is to the left of the house, and the orange tree is to its right.
  • Assume the trees are located on a single point, where the apple tree is at point a, and the orange tree is at point b .
  • When a fruit falls from its tree, it lands d units of distance from its tree of origin along the x-axis. A negative value of d means the fruit fell d units to the tree's left, and a positive value of d means it falls d units to the tree's right.

예시

// Input
7 11
5 15
3 2
-2 2 1
5 -6

// Output
1
1

풀이

  • 샘의 공간인 st 사이에 떨어진 사과와 오렌지의 개수를 구하는 문제이다.
  • d는 나무로부터 사과 혹은 오렌지가 떨어진 거리이며, 음수는 왼쪽 방향이다.
  • 사과나무와 오렌지나무의 위치인 ab 각각으로부터 apples[] , oranges[] 와의 합을 구하고, 결과 값을 s , t와 비교하면 될 것 같다.

코드

function countApplesAndOranges(s, t, a, b, apples, oranges) {

    let appleCount = 0;
    let orangeCount = 0;

    for(let i = 0; i < apples.length; i++) {
       const appleDropZone = a + apples[i];
       if(appleDropZone >= s && appleDropZone <= t) appleCount++;
    }

    for(let j = 0; j < oranges.length; j++) {
        const orangeDropZone = b + oranges[j];
        if(orangeDropZone >= s && orangeDropZone <= t) orangeCount++;
     }

    console.log(appleCount);
    console.log(orangeCount);

}

0개의 댓글