티스토리 뷰

Algorithms

Birthday Chocolate

seoca 2020. 9. 11. 22:11

 

Solution in JavaScript

const arr = [1, 2, 1, 3, 2];
const d = 3;
const m = 2;

function birthday(s, d, m) {
    let result = 0;

    for (let i = 0; i < s.length; i++) {
        //1. slice로 길이만큼의 new array생성.
        //2. reduce이용 new array의 each index 의 sum구하기.
        if (s.slice(i, i + m).reduce((x, y) => x + y) === d) {
            result++;
        }
    }

    //return result;
    console.log(result);
}

birthday(arr, d, m);


//1. 길이만큼 loop을 돌려야하나? -> 2번
//2. m만큼 순차적으로 index를 늘려서 합해야 하는데...어떻게하지? -> slice를 사용해서 길이만큼의 새로운 arr생성

 

 

 

Reference

www.hackerrank.com/challenges/the-birthday-bar/problem

'Algorithms' 카테고리의 다른 글

Find Digits  (0) 2020.09.13
Bon Appétit  (0) 2020.09.12
Divisible Sum Pairs  (0) 2020.09.05
Breaking the Records  (0) 2020.09.04
Apple and Orange  (0) 2020.08.24