CodeWars 코딩 문제 2021/01/26 - zipWith

이호현·2021년 1월 26일
0

Algorithm

목록 보기
67/138

[문제]

zipWith takes a function and two arrays and zips the arrays together, applying the function to every pair of values.
The function value is one new array.

If the arrays are of unequal length, the output will only be as long as the shorter one.
(Values of the longer array are simply not used.)

Inputs should not be modified.

Examples

zipWith( Math.pow, [10,10,10,10], [0,1,2,3] ) => [1,10,100,1000]
zipWith( Math.max, [1,4,7,1,4,7], [4,7,1,4,7,1] ) => [4,7,7,4,7,7]

zipWith( function(a,b) { return a+b; }, [0,1,2,3], [0,1,2,3] ) => [0,2,4,6] Both forms are valid.
zipWith( (a,b) => a+b, [0,1,2,3], [0,1,2,3] ) => [0,2,4,6] Both are functions.

(요약) 두 배열의 각 요소를 fn함수에 넣어서 결과값을 배열에 담아 return. 두 배열 길이가 다르면 짧은 배열의 길이를 기준으로 할 것.

[풀이]

function zipWith(fn,a0,a1) {
  const answer = [];
  const length = a0.length > a1.length ? a1.length : a0.length;
 
  for(let i = 0; i < length; i++) {
    answer.push(fn(a0[i], a1[i]));
  }
                           
  return answer;
}

짧은 배열의 길이를 구하고, 그 길이만큼 반복문을 돌려서 fn의 요소에 넣은 결과값을 answer 배열에 push하고, 마지막에 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글

관련 채용 정보