-
Notifications
You must be signed in to change notification settings - Fork 0
/
Equation.ts
43 lines (39 loc) · 1.64 KB
/
Equation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//creates an equation of the type a_1*x_1 + a_2*x_2 + ... + a_n*x_n = b , where a_m is a coefficent and x_m is an unknown, and b is a constant
interface Equation {
coeffDict: Record<string, number>, //holds pairs of (unknown variable's coefficent, unknown variable's string representaion)
rhs: number
}
class Equation {
constructor() {
this.coeffDict = {}
}
addTerm(coeff: number, unknown: string) {
this.coeffDict[unknown] = coeff
}
setRhs(number: number) {
this.rhs = number
}
toString() {
let str = ""
for (let unknown in this.coeffDict) {
let coeff = this.coeffDict[unknown]
if (str === "") {
if (coeff > 0) { //do not add plus sign in front of the first term even if its coeff is positive (ex: "2x" instead of "+ 2x")
str += `${coeff === 1 ? "" : `${coeff}*`}${unknown}`
}
else if (coeff < 0) { //do not add a space after the negative sign for the first term's coeff (ex: "-2x" instead of "- 2x")
str += `-${coeff === -1 ? "" : `${Math.abs(coeff)}*`}${unknown}`
}
}
else if (coeff > 0) { //add plus sign and space in front of the later terms (ex: "____ + 2x")
str += ` + ${coeff === 1 ? "" : `${coeff}*`}${unknown}`
}
else if (coeff < 0) { //add a negative sign and space in front of the later terms (ex: "____ - 2x")
str += ` - ${coeff === -1 ? "" : `${Math.abs(coeff)}*`}${unknown}`
}
}
str += ` = ${this.rhs}`
return (str)
}
}
export = Equation