티스토리 뷰

Algorithms

Apple and Orange

seoca 2020. 8. 24. 22:05

 

Solution in JavaScript I

const s = 7;
const t = 10;
const a = 4;
const b = 12;
const apples = [2, 3, -4];
const oranges = [3, -2, -4];

function countApplesAndOranges(s, t, a, b, apples, oranges) {
    let k = 0;
    let j = 0;
    let i;

    for (i = 0; i < apples.length; i++) {
        if (a + apples[i] >= s && a + apples[i] <= t) {
            ++k;
        }
    }
    for (i = 0; i < oranges.length; i++) {
        if (b + oranges[i] >= s && b + oranges[i] <= t) {
            ++j;
        }
    }
    console.log(k); //1
    console.log(j); //2
}

countApplesAndOranges(s, t, a, b, apples, oranges);

 

 

 

 

Solution in JavaScript II

const s = 7;
const t = 10;
const a = 4;
const b = 12;
const apples = [2, 3, -4];
const oranges = [3, -2, -4];

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

    let apple = apples.filter(value => value + a >= s && value + a <= t).length;
    let orange = oranges.filter(value => value + b >= s && value + b <= t).length;

    console.log(apple); //1
    console.log(orange); //2
}

countApplesAndOranges(s, t, a, b, apples, oranges);

 

*조건식이 들어갈 떄는 filter() 사용을 그리고 갯수리턴은 length사용을 고려해보자

 

 

 

Reference

https://www.hackerrank.com/challenges/apple-and-orange/problem

 

Apple and Orange | HackerRank

Find the respective numbers of apples and oranges that fall on Sam's house.

www.hackerrank.com

 

'Algorithms' 카테고리의 다른 글

Divisible Sum Pairs  (0) 2020.09.05
Breaking the Records  (0) 2020.09.04
Grading Students  (0) 2020.08.22
Time Conversion  (0) 2020.08.22
Birthday Cake Candles  (0) 2020.08.16