Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9bb46e0

Browse files
feat: 2 / 전력망을 둘로 나누기 / 새로운 문제
1 parent a5a3f97 commit 9bb46e0

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
//https://github.com/codeisneverodd/programmers-coding-test
2+
//더 좋은 풀이가 존재할 수 있습니다.
3+
//정답 1 - codeisneverodd
4+
function solution(n, wires) {
5+
const hasOneOfWire = (tree, [a, b]) => tree.includes(a) || tree.includes(b);
6+
7+
const convertWiresToTree = wires => [...new Set(wires.flat())];
8+
9+
const generateTree = (wires, tree) => {
10+
if (!wires.find(wire => hasOneOfWire(tree, wire))) return tree;
11+
12+
const nextWires = wires.filter(wire => !hasOneOfWire(tree, wire));
13+
const nextTree = [...tree, ...convertWiresToTree(wires.filter(wire => hasOneOfWire(tree, wire)))];
14+
15+
return [...new Set(generateTree(nextWires, nextTree))];
16+
};
17+
18+
let minDiff = Infinity;
19+
const length = convertWiresToTree(wires).length;
20+
21+
wires.forEach((_, i) => {
22+
const [initWire, ...remainWires] = wires.filter((_, j) => j !== i);
23+
const lengthA = generateTree(remainWires, convertWiresToTree([initWire])).length;
24+
const diff = Math.abs(lengthA - (length - lengthA));
25+
minDiff = Math.min(diff, minDiff);
26+
});
27+
28+
return minDiff;
29+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /