-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchem.ts
78 lines (62 loc) · 1.7 KB
/
chem.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class Count {
data: Record<string, number> = Object.create(null)
merge(other: Count, multiplyBy = 1) {
for (const key in other.data) {
this.data[key] = (this.data[key] ?? 0) + other.data[key]! * multiplyBy
}
}
}
function count([text]: readonly [string] | TemplateStringsArray): Count {
const data = new Count()
const regex = /([A-Za-z]+)\s*(\d*)|\(([^)]+)\)\s*(\d*)/g
let m: RegExpExecArray | null
while ((m = regex.exec(text!))) {
if (m[1]) {
data.data[m[1]] = (data.data[m[1]] ?? 0) + Number(m[2] ?? 1)
} else {
data.merge(count([m[3]!]), +(m[4] ?? 1))
}
}
return data
}
function det(matrix: number[][]) {
if (matrix.length == 0) {
return 0
}
if (matrix.length == 1) {
return 1
}
if (matrix.length == 2) {
return matrix[0]![0]! * matrix[1]![1]! - matrix[0]![1]! * matrix[1]![0]!
}
let sum = 0
for (let i = 0; i < matrix.length; i++) {
const next = withoutColumn(matrix.slice(1), i)
sum += (i % 2 ? -1 : 1) * matrix[0]![i]! * det(next)
}
return sum
}
function withoutColumn(data: number[][], column: number) {
return data.slice(1).map((x) => {
const copy = x.slice()
copy.splice(column, 1)
return copy
})
}
function getColumn(data: number[][], col: number) {
return data.map((row) => row[col]!)
}
function withColumnAs(data: number[][], col: number, colData: number[]) {
return data.map((row, index) => {
const copy = row.slice()
copy[col] = colData[index]!
return col
})
}
function solve(data: number[][]) {
const vars = withoutColumn(data, data.length - 1)
const D = det(vars)
return Array.from({ length: vars.length }, (_, index) => {
return det(withoutColumn(vars, index)) / D
})
}