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 40eaaf1

Browse files
author
hasibulislam999
committed
Evaluate Division problem solved
1 parent fb9ea86 commit 40eaaf1

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* Title: Evaluate Division
3+
* Description: You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.
4+
* Author: Hasibul Islam
5+
* Date: 04/05/2023
6+
*/
7+
8+
/**
9+
* @param {string[][]} equations
10+
* @param {number[]} values
11+
* @param {string[][]} queries
12+
* @return {number[]}
13+
*/
14+
var calcEquation = function (equations, values, queries) {
15+
const UF = new UnionFind();
16+
for (let i = 0; i < equations.length; i++) {
17+
const [dividend, divisor] = equations[i];
18+
const value = values[i];
19+
20+
UF.union(dividend, divisor, value);
21+
}
22+
23+
const results = [];
24+
25+
for (let i = 0; i < queries.length; i++) {
26+
const [dividend, divisor] = queries[i];
27+
28+
if (!UF.arr[dividend] || !UF.arr[divisor]) {
29+
results[i] = -1;
30+
} else {
31+
let [dividendGid, dividendWeight] = UF.find(dividend);
32+
let [divisorGid, divisorWeight] = UF.find(divisor);
33+
if (dividendGid !== divisorGid) {
34+
results[i] = -1;
35+
} else {
36+
results[i] = dividendWeight / divisorWeight;
37+
}
38+
}
39+
}
40+
41+
return results;
42+
};
43+
44+
class UnionFind {
45+
arr = {};
46+
47+
find(key) {
48+
if (!this.arr[key]) this.arr[key] = [key, 1];
49+
const [entryKey, entryValue] = this.arr[key];
50+
51+
if (entryKey !== key) {
52+
const [newEntryKey, newEntryValue] = this.find(entryKey);
53+
this.arr[key] = [newEntryKey, entryValue * newEntryValue];
54+
}
55+
return this.arr[key];
56+
}
57+
union(dividend, divisor, value) {
58+
let [dividendGid, dividendWeight] = this.find(dividend);
59+
let [divisorGid, divisorWeight] = this.find(divisor);
60+
61+
if (dividendGid !== divisorGid) {
62+
this.arr[dividendGid] = [
63+
divisorGid,
64+
(divisorWeight * value) / dividendWeight,
65+
];
66+
}
67+
}
68+
}

0 commit comments

Comments
(0)

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