티스토리 뷰

Algorithms

Electronics Shop

seoca 2020. 9. 25. 23:00

Solution I in Javascript 

const keyboards = [3, 1];
const drives = [5, 2, 8];
const b = 10;

function getMoneySpent(keyboards, drives, b) {

    let valid = [];
    keyboards.forEach(k => drives.forEach(d => k + d <= b ? valid.push(k + d) : 0));
    const result = valid.length === 0 ? -1 : Math.max(...valid);
    console.log(result); //9
}

getMoneySpent(keyboards, drives, b);

1. 두개의 array의 합이 필요한 문제는 forEach 안에 arrow function을 사용해서 forEach 를 다시 사용해서 풀자.

2. 그 결과값을 push로 새로운 array에 push해주고

3. Question mark operator (condition ? true : false)를 적극사용해주자.

 

 

 

Solution II in Javascript

const keyboards = [3, 1];
const drives = [5, 2, 8];
const b = 10;

function getMoneySpent(keyboards, drives, b) {

    const result = keyboards.reduce((acc, curr) => //1. reduce: arrow function 이용 single value return.

        //2. max: 조건에 맞게 max value를 리턴.
        //3. map: 함수이용 each elements 변화시킨다. -> drives와 keyboards each elements 더하기.
        //4. 합한 값을 budget보다 작거나 같은 값으로 filter 해주기.
        Math.max(acc, ...drives.map(usb => usb + curr).filter(ku => b >= ku)), -1);

    console.log(result);
}

getMoneySpent(keyboards, drives, b);

 

 

Reference

www.hackerrank.com/challenges/electronics-shop/problem

'Algorithms' 카테고리의 다른 글

Migratory Birds  (0) 2020.10.01
Utopian Tree  (0) 2020.10.01
The Hurdle Race  (0) 2020.09.25
Cats and a Mouse  (0) 2020.09.17
Find Digits  (0) 2020.09.13