JavaScript 组数组 - 使用定义的边查找可以到达的数字集
javascriptweb developmentfront end technologyobject oriented programming
考虑以下输入和输出数组 −
const input = ["0:3", "1:3", "4:5", "5:6", "6:8"]; const output = [ [0, 1, 3], [4, 5, 6, 8] ];
将每个数字视为图中的节点,将每个配对 x:y 视为节点 x 和 y 之间的边,我们需要找到可以使用定义的边到达的数字集。
也就是说,从图论的角度来看,在这样的图中找到不同的连通分量。例如,在上面的数组中,没有办法从 4 移动到 0,所以它们在不同的组中,但有一种方法可以从 1 移动到 0(通过 3),所以它们在同一个组中。"重申一下,所需的输出是基于潜在随机输入集的可横向节点分组。
我们需要编写一个 JavaScript 函数,根据给定的输入构造所需的输出。
示例
const input = ["0:3", "1:3", "4:5", "5:6", "6:8"];
const groupRange = (arr = []) => {
const res = [[]];
let count = 0;
const a = [0];
let array = arr.map(el => el.split(':').sort((a, b) => a - b)). sort((a, b) => a[0] - b[0]); array.forEach(el => {
if (el[0] > a[a.length - 1]) {
res.push(el);
a.push(el[1]);
count++;
} else {
res[count] = res[count].concat(el);
a[a.length - 1] = el[1];
};
});
return res.map(el => [...new Set(el)].sort((a, b) => a - b));
}
console.log(groupRange(input));
输出
控制台中的输出将是 −
[ [ '0', '1', '3' ], [ '4', '5', '6', '8' ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

