Home > Back-end >  How do I fix this algorithm to generate branching and converging path?
How do I fix this algorithm to generate branching and converging path?

Time:10-21

I'm trying to specify an input of nodes per layer, such as [1,2,5,3,1] and generate connected nodes in a directed graph enter image description here

Here is the javascript code:

function getConnectedIndices(m, n) {
    let a = new Array(m).fill(0).map((x, i) => (i)/(m) (1/2/m));
    let b = new Array(n).fill(0).map((x, i) => (i)/(n) (1/2/n));

    let ab = a.map(x => b.map(y => Math.abs(x - y)));
    
    let threshold = 1/Math.max(m, n);
    
    return ab.map(x => x.map((y, i) => y <= threshold ? i : null).filter(x => x !== null));
}

let result = getConnectedIndices(3, 5);
result.forEach((x, i) => console.log(`Node ${i} in first row is connected to nodes (${x}) of the second row`));

  • Related