(codeWars) Merge two arrays
13361 ワード
Description
Write a function that combines two arrays by alternatingly taking elements from each array in turn.
Examples:
Points
問題を解く
二重ポインタアルゴリズムの問題
配列の長さを判別できる変数の関数を作成し、ドアの周りを回転して要素を空の配列に入れます.
空の配列に要素が含まれている場合は、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)))
}
Reference
この問題について((codeWars) Merge two arrays), 我々は、より多くの情報をここで見つけました https://velog.io/@yunsungyang-omc/codeWars-Merge-two-arraysテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol