Skip to content

Commit 8ad967d

Browse files
committed
Problem solving: recursion - rendering tree based on id-basedId
1 parent 86c6445 commit 8ad967d

File tree

1 file changed

+134
-0
lines changed

1 file changed

+134
-0
lines changed

Problem Solving/recursion.js

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
const inputs = [
2+
{
3+
id: 1,
4+
name: "Vietnam",
5+
basedId: null,
6+
},
7+
{
8+
id: 2,
9+
name: "HCM",
10+
basedId: 5,
11+
},
12+
{
13+
id: 3,
14+
name: "Hanoi",
15+
basedId: 9,
16+
},
17+
{
18+
id: 4,
19+
name: "Quang Ngai",
20+
basedId: 1,
21+
},
22+
{
23+
id: 5,
24+
name: "Quan 1",
25+
basedId: 2,
26+
},
27+
{
28+
id: 6,
29+
name: "Binh Thanh",
30+
basedId: 2,
31+
},
32+
{
33+
id: 7,
34+
name: "Thanh Xuan",
35+
basedId: 3,
36+
},
37+
{
38+
id: 9,
39+
name: "Pho Hien",
40+
basedId: 3,
41+
},
42+
{
43+
id: 8,
44+
name: "Thu Duc",
45+
basedId: 1,
46+
},
47+
];
48+
49+
/**
50+
* Expected output:
51+
*/
52+
53+
// {
54+
// "Vietnam": {
55+
// "HCM": {
56+
// "Quan 1": {},
57+
// "Binh Thanh": {}
58+
// },
59+
// "Hanoi": {
60+
// "Thanh Xuan": {}
61+
// },
62+
// "Quang Ngai": {}
63+
// }
64+
// }
65+
66+
/**
67+
* =========================
68+
*/
69+
70+
// tree("Vietnam")
71+
// tree("HCM")
72+
// tree("Quan 1")
73+
// tree("Binh Thanh")
74+
// tree("Hanoi")
75+
// tree("Thanh Xuan")
76+
// tree("Quang Ngai")
77+
78+
function tree(id) {
79+
let results = {};
80+
inputs
81+
.filter((item) => item.basedId === id)
82+
.map((item) => {
83+
results[item.name] = tree(item.id);
84+
});
85+
86+
return results;
87+
}
88+
89+
/**
90+
* Trường hợp có vòng, ví dụ: HCM: {id: 2, basedId: 5}, Quan 1: {id: 5, basedId: 2}
91+
*/
92+
93+
// Điều kiện để xảy ra vòng:
94+
// if (item1.baseId === item2.id && item2.basedId === item1.id) {
95+
// }
96+
97+
/**
98+
* Hướng xử lý:
99+
*
100+
* trước khi chạy hàm tree,
101+
* mình sẽ chạy hàm kiểm tra xem có hai phần tử nào thỏa mãn điều kiện vòng trên không
102+
*/
103+
104+
const isCycle = (inputs) => {
105+
if (inputs.length === 0) return false;
106+
107+
let results = [];
108+
for (let i = 0; i < inputs.length - 1; i++) {
109+
for (let j = i + 1; j < inputs.length; j++) {
110+
if (
111+
inputs[i].basedId === inputs[j].id &&
112+
inputs[i].id === inputs[j].basedId
113+
) {
114+
results.push([inputs[i], inputs[j]]);
115+
}
116+
}
117+
}
118+
119+
return results.length === 0 ? false : results;
120+
};
121+
122+
function printTree(inputs) {
123+
if (inputs.length === 0) return [];
124+
125+
let checkingCycle = isCycle(inputs); // O(n^2)
126+
127+
if (checkingCycle) {
128+
return `Có ${checkingCycle.length} vòng: ${JSON.stringify(checkingCycle)}`;
129+
} else {
130+
return JSON.stringify(tree(null), null, 2); // O(n)
131+
}
132+
}
133+
134+
console.log(printTree(inputs));

0 commit comments

Comments
 (0)