檢查兩個陣列是否可以形成一個序列 - JavaScript
我們需要編寫一個 JavaScript 函式,該函式採用兩個數字陣列。
並且該函式應該返回 true,如果這兩個陣列在組合和洗牌後可以形成連續的序列,否則返回 false。
例如 − 如果陣列是 −
const arr1 = [4, 6, 2, 9, 3]; const arr2 = [1, 5, 8, 7];
那麼輸出應該是 true。
舉例
以下是程式碼 −
const arr2 = [1, 5, 8, 7];
const canFormSequence = (arr1, arr2) => {
const combined = [...arr1, ...arr2];
if(combined.length < 2){
return true;
};
combined.sort((a, b) => a-b);
const commonDifference = combined[0] - combined[1];
for(let i = 1; i < combined.length-1; i++){
if(combined[i] - combined[i+1] === commonDifference){
continue;
};
return false;
};
return true;
};
console.log(canFormSequence(arr1, arr2));輸出
以下是控制檯中的輸出 −
true
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP