(codeWars) Merge two arrays


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).
  • 2つの配列があり、配列の長さが異なる場合があります.各配列要素の新しい配列を順番に順番に配置する問題を返します.

    問題を解く


    二重ポインタアルゴリズムの問題
    配列の長さを判別できる変数の関数を作成し、ドアの周りを回転して要素を空の配列に入れます.
    空の配列に要素が含まれている場合は、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)))
    }