T
T
timonck2019-11-08 14:41:55
JavaScript
timonck, 2019-11-08 14:41:55

How to find the node with the minimum value in a graph and return that node using recursion and pure functions?

I have a graph whose nodes are represented by objects:

Node = {
    value: <number>,
    children: [Node]
}

var graph = {value:75,children:[{value:18,children:[{value:35,children:[{value:35,children:[{value:66}]}]}]}]}

My code:
const min = (graph) => {

    let nodes = [];
    let mas = null;

    const getNodeValue = (graph) =>{
     Object.keys(graph).map(i => {
         if (typeof graph[i] === 'object') {
                getNodeValue(graph[i])
            } else {
                nodes.push(graph[i])
            }

            let min = Math.min.apply(null, nodes)
                if(graph[i] === min){
             mas = (graph)
            }
     })
    }

    getNodeValue(graph);
    // console.log(mas)
    return mas

};
console.log(min(graph));

It outputs the node with the minimum value, but the solution itself is not correct.
How can be solved without object.keys?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-11-08
@timonck

const findMin = obj =>
  (obj.children || []).reduce((min, n) => {
    n = findMin(n);
    return min.value < n.value ? min : n;
  }, obj);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question