2017-10-16 1 views
-1

나는 내가 뭘하려고하는지 내 질문을 시작할 것이다. 나는 배열 (nameList)을 가지고 있고 배열에 객체를 가지고있다. 이 객체들은 사람들의 이름 (잭, 제인, 제임스, 다니엘 등)과이 사람들이 누구와 관련되어 있는지 배열로 구성됩니다 (잭은 제인과 다니엘 등과 관련이 있습니다). 물론 한 사람은 둘 이상의 사람과 관련 될 수 있지만 두 자녀는 관련 될 수 없습니다. 나는 그 (것)들을 나무에서 지키고 싶, 나는 나무가 관계에 따라이기를 바란다. 대부분의 관계를 가진 사람부터 시작하고 싶습니다 (예 : Daniel은 7 명과 관련됩니다). 나는 가장 많은 관계를 가진 사람이 1 명 이상있을 수 있음을 압니다. 그러나 내가 묻는 질문의 단순함을 위해, 내가 누구인지를 알게되고, 나는 그것을 가장 많이 알리는 것과 같이 전달할 것이다.배열을 사용하여 트리를 생성

This is just an example of what I want to do

이것은 내가 그렇게 far.But 내가 그것을 촉진하는 방법을 잘 모르겠습니다있는 것입니다.

//my array of names is nameList 
//to check who they are related to nameList.relatedTo 

function Node(names) { 
this.data = names; 
this.parent = null; 
this.children = []; 
} 

function CreateTree(nameList, mostRelated) 
{ 
this._root=mostLinked; 
    for(var i=0; i < nameList[i].length;i++) 
    { 
    node= new Node(nameList[i]); 
    if(nameList[i].isChecked!)//if already add to the tree 
    { 
     if(nameList[i].isRelated)//to check if they have any relation 
     { 
      for(var j=0; i < nameList[i].relatedTo[j].length;j++) 
      { 
       if(nameList[i].relatedTo.isChecked!) 
       { 
        nameList[i]=Node.parent; 
        Node.children.push(nameList[i].relatedTo[j]); 
        nameList[i].isChecked=true; 
        } 
      } 
     } 
    } 
    } 
} 

이름 목록은 다음과 같이이

nameList 
this.name; 
this.relatedTo=[]; 
this.related=false; 
this.checked=false; 
+2

트리를 사용하는 것은 올바른 데이터 구조가 아닙니다. 두 명의 자녀도 관련이 있습니다. 그래프/맵을 사용해야합니다. – ControlAltDel

+0

설정이 여기 저기에 있습니다. 당신은 이미 누가 누가 부모의 자녀인지 확증하지 않습니까? 귀하의 정보가 이미 주어진 곳에서 귀하의 데이터 그래프를 만들기 위해 이미 그래프를 만들었습니다. 'nameList'의 한 요소가 어떻게 생겼는지에 대한 예제를 제공하십시오. 나는 너의 목표를 오해하고 있을지도 모른다. – Andrew

+0

@ControlAltDel, 제안에 감사드립니다. 그러나 나는 2 명의 아이들이 관련이 없도록 만들 수 있습니다. 나는 그 질문을 바꾸었다. – JJD

답변

0

뭔가처럼 보인다? 귀하의 질문은 근본적으로 그래프 데이터 구조를 요구하지만 우연히 나무처럼 보일 수 있습니다.

function Person(name) { 
    this.name = name 
    this.relatedTo = [] 
} 


function Graph(familyArr) { 
    this._familyArr = nameList.sort((a, b) => { 
    return b.relatedTo.length - a.relatedTo.length //reverse sort by relatedTo.length 
    }) 

    const familyObj = {} 
    this._familyArr.forEach(({name}) => { 
    familyObj[name] = new Person(name) //build object of name-person object key-val pairs 
    }) 
    this.head = familyObj[this._familyArr[0].name] //graphs don't have heads, but they can by 'coincidence' 
    this.family = familyObj // actual tree 
    this._children = Object.assign({}, this.family) //copies of children to keep proper track of them while building this.family 
} 

Graph.prototype.addRelative = function(parent, child) { 
    this.family[parent].relatedTo.push(this._children[child]) 
    // console.log(this.family); 
    return this 
} 

Graph.prototype.buildGraph = function() { 
    this._familyArr.forEach(parent => { 
    parent.relatedTo.forEach(child => { 
     this.addRelative(parent.name, child) 
    }) 
    }) 
} 

Graph.prototype.find = function(name) { 
    return this.family[name] 
} 

const john = {name: 'john', relatedTo: ['jane']} 
const jane = {name: 'jane', relatedTo: ['john']} 
const jack = {name: 'jack', relatedTo: ['andrew', 'jane']} 
const andrew = {name: 'andrew', relatedTo: ['jane', 'john']} 
const nameList = [john, jane, jack, andrew] 


const graph = new Graph(nameList) 
graph.buildGraph() 

console.log(graph.find('john')) 
// Person { 
// name: 'john', 
// relatedTo: [ Person { name: 'jane', relatedTo: [Object] } ] } 


console.log(graph.find('andrew')); 
// Person { 
// name: 'andrew', 
// relatedTo: 
// [ Person { name: 'jane', relatedTo: [Object] }, 
//  Person { name: 'john', relatedTo: [Object] } ] } 

console.log(graph.head) 
// Person { 
// name: 'jack', 
// relatedTo: 
// [ Person { name: 'andrew', relatedTo: [Object] }, 
//  Person { name: 'jane', relatedTo: [Object] } ] } 
+0

이것은 완벽합니다. 내가 요구 한 것 이상. 고맙습니다 – JJD

관련 문제