英文:
Add nodes in a Graph not working perfectly in js
问题
我已经创建了一个包含键值对的图表,其中键是节点编号,值是邻接边的数组,这里我编写了一个函数,将节点和邻接边添加到图表中,但是这个函数在这里不起作用,我应该修改什么地方,以便获得类似这样的图表:{ 1:[2,4],2:[1,3],3:[2,4],4:[1,4],5:[3,4]}
给定的代码如下:
var graph = {
1: [2, 4],
2: [1, 3],
3: [2, 4],
4: [1, 4]
};
function addNode(key, value = []) {
graph[key] = value;
}
addNode(5, [3, 4]);
console.log(graph);
英文:
I have created a graph which containing key and value pair ,key is for node number and value for adjacency list value which is an array of adjacent edges, here I wrote a function that will add the node and adjacency edges in the graph, but here the function is not working ,which thing should I have to modified here that I want graph like { 1:[2,4],2:[1,3],3:[2,4],4:[1,4],5:[3,4]}
code is given below
var graph = {
1: [2, 4],
2: [1, 3],
3: [2, 4],
4: [1, 4]
};
function addNode(key, value = []) {
graph[key].push({ value: value });
}
addNode(5, [3, 4]);
console.log(graph);
答案1
得分: 1
function addNode(key, value = []) {
graph[key] = value;
}
或者,如果您要给已存在的节点添加新值:
function addNode(key, values = []) {
(graph[key] ??= []).push(...values);
}
试试看:
var graph = {
1: [2, 4],
2: [1, 3],
3: [2, 4],
4: [1, 4]
};
function addNode(key, value = []) {
graph[key] = value;
}
function addValuesToNode(key, value = []) {
(graph[key] ??= []).push(...value);
}
addNode(5, [3, 4]);
console.log(graph);
addValuesToNode(5, [1]);
console.log(graph);
英文:
function addNode(key, value = []) {
graph[key] = value;
}
Or, if you want to add new values to the node, given it already existed:
function addNode(key, values = []) {
(graph[key] ??= []).push(...values);
}
Try it:
<!-- begin snippet: js hide: true console: true babel: false -->
<!-- language: lang-js -->
var graph = {
1: [2, 4],
2: [1, 3],
3: [2, 4],
4: [1, 4]
};
function addNode(key, value = []) {
graph[key] = value;
}
function addValuesToNode(key, value = []) {
(graph[key] ??= []).push(...value);
}
addNode(5, [3, 4]);
console.log(graph);
addValuesToNode(5, [1]);
console.log(graph);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论