오늘은 Leetcode에서 2634번 배열에 관한 문제를 풀었다. 매일 아침 9시 마다 Leetcode문제를 풀고 공부를 시작하니 뭔가 뇌가 더 액티브 해진 느낌이다. (아님 말고) 문제는 다음과 같다. 사실 영어라서 문제 읽고 이해하는데 시간이 많이 간다.. 적어도 번역기 돌리지 않는 실력에 감사해야지.
Given an integer array arr and a filtering function fn, return a filtered array filteredArr.
The fn function takes one or two arguments:
arr[i] - number from the arri - index of arr[i]filteredArr should only contain the elements from the arr for which the expression fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where Boolean(value) returns true.
Please solve it without the built-in Array.filter method.
Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
Output: [20,30]
// Explanation:
// const newArray = filter(arr, fn); // [20, 30]
// The function filters out values that are not greater than 10
Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
Output: [1]
// Explanation:
// fn can also accept the index of each element
// In this case, the function removes elements not at index 0
Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
Output: [-2,0,1,2]
// Explanation:
// Falsey values such as 0 should be filtered out
오늘 문제 풀면서 깨닳은 건데, 어지간한 코드 문제에서 어떠한 반복문 메소드를 사용하지 말라는건 그냥 for문 쓰라는 소리인것 같다.
.filter 메소드를 사용하지 말라고했으니 마찬가지로 for문으로 문제를 풀기 시작했다.
Example 1에서 input에 arr와 fn을 받는다. 즉, 내가 만들 filter 함수는 2가지 매개변수를 받아야한다. 그것부터 시작하자.
const filter = (arr, fn) => {
}
그리고 배열을 리턴해야하니 임시 배열을 filter 함수 스코프 내에서 생성해주자.
const filter = (arr, fn) => {
const tempArr = [];
}
example 1 에서 arr = [0,10,20,30]과 function greaterThan10(n) { return n > 10; }를 넣어서 20과 30이 나와야 하니까 반복문으로 if문을 만들어서 truthy되는 값을 tempArr에 넣어준다음 tempArr를 리턴해주면 될 것 같다는 생각이 들었다.
const filter = (arr, fn) => {
const tempArr = [];
for (let i = 0; i < arr.length - 1; i++) {
if (fn(arr[i])) {
tempArr.push(arr[i]);
}
} return tempArr;
}
여기에서 바보같이 해맨게, 처음 이 식을 세우고 example 1의 매개변수를 넣어보니 자꾸 [20]만 나오는 것이었다. 분명 배열의 길이는 4고, 0부터 시작해서 3까지만 가니까 for문에서 조건을 arr.length - 1로 해준건데, 이것도 몇 분 동안 왜지 하다가 <니까 굳이 -1을 안 해줘도 된다는 사실을 깨닳았다...
아무튼, 이렇게 example 1은 통과하였고, example 2를 보니까 fn에서 매개변수를 두 개를 받는 다는 것을 봤다. 두 번째 매개변수는 arr의 index니까 i로 놓으면 되겠다.
const filter = function(arr, fn) {
const tempArr = [];
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i], i)) {
tempArr.push(arr[i])
}
} return tempArr;
};
이렇게 만드니 example 2도, 3도 통과를 했다.
제출 하니 패스되었다고 떴다! 아 좋다! easy 문제라도 풀면 기분 좋긴 똑같다.
오 ! 근데 solution에서 좋아요 3k, 6k를 받은 답들도 내것과 똑 같 다. 잘하고 있는 것 같다!