Javascript
프로그래머스 솔루션
function solution(n, lost, reserve) {
let realLost = lost.filter(a => !reserve.includes(a));
let realReserve = reserve.filter(a => !lost.includes(a));
return n - realLost.filter(a => {
let b = realReserve.find(r => Math.abs(r-a) <= 1);
if(!b) return true;
realReserve = realReserve.filter(r => r !== b);
}).length;
}
1. what is "filter" in js?
filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Description
filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are skipped, and are not included in the new array.
find()
The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfies the testing function, undefined is returned.
Description
The find method executes the callback function once for each index of the array until the callback returns a truthy value. If so, find immediately returns the value of that element. Otherwise, find returns undefined.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
function solution(n, lost, reserve) {
let realLost = lost.filter(a => !reserve.includes(a));
let realReserve = reserve.filter(a => !lost.includes(a));
return n - realLost.filter(a => {
let b = realReserve.find(r => Math.abs(r-a) <= 1);
if(!b) return true;
realReserve = realReserve.filter(r => r !== b);
console.log(a,"|", b, realReserve, realLost);
console.log("--")
}).length;
}
solution(n=5, lost=[2,4], reserve=[1,3,5]);
// output //
// 2 | 1 [ 3, 5 ] [ 2, 4 ]
// --
// 4 | 3 [ 5 ] [ 2, 4 ]
// --
// 5
//
* filter 메서드는 해당 array의 element 마다 callback 함수를 호출하면서 callback 함수의 조건에 참인 element만을 포함한 새로운 array를 return.
* b 변수는 (realReserve - realLost ) <= 1, 즉 값이 1차이가 나는 처음 발견된 realReserve의 element를 할당.
* 만약 1차이가 나는 element가 없다면( if (!b) return true; ), 그 밑의 코드는 진행하지 않고 나옴.
* b가 존재할 경우, filter 메서드로 realReserve에서는 b를 , realLost에서는 a를 제외시킴.
1-1. 화살표 함수 표현(Arrow function expression) "=>"?
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
Python에서 lambda와 비슷한거 같다.
찾아보니, JavaScript arrow functions are roughly the equivalent of lambda functions in python or blocks in Ruby.
"=>" is called "fat arrow"
Arrow Function Syntax
Arrow functions have a single overarching structure, and then an number of ways they can be simplified in special cases.
The core structure looks like this:
(argument1, argument2, ... argumentN) => { // function body }
A list of arguments within parenthesis, followed by a 'fat arrow' (=>), followed by a function body.
What this first line of code does?
let realLost = lost.filter(a => !reserve.includes(a));
lost array에 대해 filter 메서드를 사용해서 !reserve.includes(a)의 결과물을 realLost 변수로 생성.
검색해보기 전에는 "!reserve.includes(a)"의 의미는 reserve array에서 a를 포함하지 않는 array를 의미.
docs를 통해 더 확실하게 정리하자면,
includes는 bool을 return.
filter 메서드의 리턴값은 A new array with the elements that pass the test.를 보면 a new array with filtered라고 이해할 수 있다.
filter 괄호 안에는 callback parameter가 있는데
callback returns a value that coerces to true to keep the element, or to false otherwise.
결론적으로, filter 안에 callback으로 includes메서드를 활용해서 나온 bool 값들에 대해 True인 element만 남긴 array를 반환한다.
fat arrow를 활용해서 좀 더 간결하게 코드를 짤 수 있다는 사실.
**
Exclamation mark에 대해 검색해보니 double exclamation에 대해 나온다
1. Single Exclamation mark
- In Javascript, the exclamation mark (“!”) symbol, called a “bang,” is the logical “not” operator. Placed in front of a boolean value it will reverse the value, returning the opposite.
- 눈에 띄이는 점은 boolean value앞에 써야한다는 점인데, 위에서 includes메서드가 bool를 return하기 때문에 includes에 대해 사용가능했던 것.
- Just like a conditional if statement, a bang (“!”) creates a boolean context. So, for example, the string abc, which is associated with true, will evaluate to false if a bang is placed in front of it.
- 풀어서 설명하자면, const x = 'abc'; x라는 상수를 abc라는 string으로 선언하는데 이것은 bool 관점에서 True로 된다. // Coerces to true in a boolean context
- 따라서 "!x"는 bool의 측면에서 봤을때 False가 되는데 if 절에서 특정 string에 대해 bool 조건을 사용할 수 있을 것 같다.
(In short)
So, the single bang does two things:
- Determines the values associated true/false value.
- Returns the opposite of the associated true/false value.
2. Double Exclamation marks
double exclamation marks is two times of single exclamation mark.
So, running a bang twice determines the opposite of value, and then returns the opposite of that.
Seems not useful though,
const x = 'abc'; // Associated with true.
const a = !x; // The ! determines x is associated with true and returns the opposite, false.
const b = !a; // The ! takes value 'a' of false and reverses it to true.
!!'abc' // Evaluates to true.
!!null // Evaluates to false.
How The Double Bang Can Be Used
Knowing the associated boolean value of any given value is helpful if you want to quickly reduce a value to a boolean:
const userA = getUser('existingUser'); // { name: Patrick, status: 'cool' }
const userB = getUser('nonExistingUser'); // null
const userAExists = !!userA; // true
const userBExists = !!userB; // false
(In short)
To make it quickly to boolean, use double exclamation marks.
*Exclamation marks
2. What is find in JS?
Return:
The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
Array.prototype.findIndex()
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
Conditional (ternary) operator
The conditional (ternary) operator is the only JavaScript operator that takes three operands(피연산자): a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.
function getFee(isMember) {
return (isMember ? '$2.00' : '$10.00');
}
console.log(getFee(true));
// expected output: "$2.00"
console.log(getFee(false));
// expected output: "$10.00"
console.log(getFee(null));
// expected output: "$10.00"
Array.prototype.splice()
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
<References>
for in VS. for of: victorydntmd.tistory.com/89
Javascript coding test ref: github.com/black7375/JS-PS
체육복: github.com/black7375/JS-PS/blob/master/programmers/level1/42862-%EC%B2%B4%EC%9C%A1%EB%B3%B5.js
'Algorithm' 카테고리의 다른 글
[프로그래머스] 2016년 (Python, JS) (0) | 2021.01.25 |
---|---|
[프로그래머스] 두 개 뽑아서 더하기 (JS, Python) (0) | 2021.01.25 |
[프로그래머스] k번째 수 (JS, Python) (0) | 2021.01.24 |
[프로그래머스] 체육복 (python) (0) | 2021.01.18 |
[프로그래머스] 모의고사 (python, javascript) (0) | 2021.01.17 |
댓글