(codeWars) Merge two arrays

호두파파·2021년 2월 28일
0

알고리즘 연습

목록 보기
7/60
post-thumbnail

Description

Write a function that combines two arrays by alternatingly taking elements from each array in turn.

Examples:

  • [a, b, c, d, e], [1, 2, 3, 4, 5] becomes [a, 1, b, 2, c, 3, d, 4, e, 5]
  • [1, 2, 3], [a, b, c, d, e, f] becomes [1, a, 2, b, 3, c, d, e, f]

Points

  • The arrays may be of different lengths, with at least one character/digit.
  • One array will be of string characters (in lower case, a-z), a second of integers (all positive starting at 1).

두 개의 배열이 주어지는, 배열은 길이가 달라질 수 있다. 각 배열의 요소를 순서대로 번갈아 넣은 새로운 배열을 반환하는 문제.

문제 풀이

투 포인터 알고리즘 문제,

배열의 길이를 판별할 수 있는 변수를 판별할 수 있는 함수를 작성하고, 판별된 길이만큼 for문을 돌며 빈 배열에 요소를 집어 넣는다.

빈 배열에 요소를 담을때는 기준 배열에 요소가 있을때만 들어가도록 if문을 작성한다.

if(a[i]) {
  result.push(a[i]);
}
if(b[i]) {
  result.push(b[i]);
}

코드 보기

// 배열을 번갈아 넣는 문제
// 투 포인터 알고리즘

function solution(s, n) {
  let answer = [];
  const sLen = s.length;
  const nLen = n.length;
  let longer; 
  
  if (sLen >= nLen) {
    longer = sLen;
  } else {
    longer = nLen;
  }
  for (let i = 0; i < longer; i++) {
    if (s[i]) {
      answer.push(s[i]);
    }
    if (n[i]) {
      answer.push(n[i]);
    }
  } 
  return answer;
}

const s = ['a', 'b', 'c', 'd', 'e'];
const n = [1, 2, 3, 4, 5, 6];

console.log(solution(s, n));


다른 문제 풀이 1

function mergeArrays(a, b) {
  const result = [];
  while (a.length || b.length) {
    if (a.length) {
      result.push(a.shift()); // 가장 앞에 위치한 배열의 요소를 반환하는 shift()
    }
    if (b.length) {
      result.push(b.shift());
    }
  }
  return result;
}

다른 문제 풀이 2

function mergeArrays(a, b) {
  let answer = [];
  for (i = 0; i < Math.max(a.length, b.length); i++) { // 배열의 길이를 알아서 판단하도록 Math.max를 이용한 풀이식
    if (i < a.length) {
        answer.push(a[i]);
  	}
    if (i < b.length) {
      answer.push(b[i]);
    }
  }
  return answer; 
}

Lodash 라이브러리

const _ = require('loadash')

function mergeArras(a, b) {
  return _.compact(_.flatten(_.zip(a, b)))
}
profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글