티스토리 뷰

Algorithms

Angry Professor

seoca 2020. 10. 19. 18:49

 

Solution in Javascript I

const k = 3;
const a = [-1, -3, 4, 2];

function angryProfessor(k, a) {
    const p = a.filter(v => v < 1).length < k ? 'YES' : 'NO'
    return p;
}

angryProfessor(k, a);

 

1. To filter elements which are less than 1, use filter()

2. length() is used to get the number of the elements.

 

for loop 와 if 를 사용하는 것보다 내장 함수들을 사용하자. 

 

 

 

 

 

Solution in Javascript II

const k = 4;
const a = [-1, -3, -4, 2];

function angryProfessor(k, a) {
    const p = a.reduce((target, time) => { //reduce 의 callback function.
        return time < 1 ? ++target : target; //++target ???? -> target이 결국 0이니까...
    }, 0) >= k ? 'NO' : 'YES'; //0 은 뭐야? -> reduce 에는 callback function 과 initial value가 들어간다.
    //initial value is '0'

    console.log(p);
}

angryProfessor(k, a);

 

 

Reference

www.hackerrank.com/challenges/angry-professor/problem

'Algorithms' 카테고리의 다른 글

Sequence Equation  (0) 2020.10.30
Viral Advertising  (0) 2020.10.22
Beautiful Days at the Movies  (0) 2020.10.18
Migratory Birds  (0) 2020.10.01
Utopian Tree  (0) 2020.10.01