-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfraction-addition-and-subtraction.go
104 lines (89 loc) · 1.71 KB
/
fraction-addition-and-subtraction.go
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"strconv"
)
func gcd(a, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
func lcm(a, b int) int {
return (a * b) / gcd(a, b)
}
func fractionAddition(exp string) string {
var nums []int
// parsing numbers
for l, r := 0, 1; r < len(exp); r++ {
if exp[r] == '+' || exp[r] == '-' || exp[r] == '/' {
x, _ := strconv.Atoi(exp[l:r])
nums = append(nums, x)
l = r
if exp[r] == '/' {
l++
}
} else if r == len(exp)-1 {
x, _ := strconv.Atoi(exp[l:])
nums = append(nums, x)
}
}
// calculating
var x, y = nums[0], nums[1]
for i := 2; i < len(nums); i += 2 {
dx, dy := nums[i], nums[i+1]
if y != dy {
dd := lcm(y, dy)
d1, d2 := dd/y, dd/dy
x, y, dx, dy = d1*x, d1*y, d2*dx, d2*dy
}
x += dx
}
// minimize
for gcd(x, y) != 1 && gcd(x, y) != -1 {
d := gcd(x, y)
if d < 0 {
d *= -1
}
x, y = x/d, y/d
}
return strconv.Itoa(x) + "/" + strconv.Itoa(y)
}
func main() {
testCases := []struct {
expression string
want string
}{
{
expression: "1/2-4/1-4/3+1/2-5/1",
want: "-28/3",
},
{
expression: "1/3-1/2",
want: "-1/6",
},
{
expression: "-1/2+1/2",
want: "0/1",
},
{
expression: "-1/2+1/2+1/3",
want: "1/3",
},
}
successes := 0
for _, tc := range testCases {
x := fractionAddition(tc.expression)
status := "ERROR"
if fmt.Sprint(x) == fmt.Sprint(tc.want) {
status = "OK"
successes++
}
fmt.Println(status, " Expected: ", tc.want, " Actual: ", x)
}
if l := len(testCases); successes == len(testCases) {
fmt.Printf("===\nSUCCESS: %d of %d tests ended successfully\n", successes, l)
} else {
fmt.Printf("===\nFAIL: %d tests failed\n", l-successes)
}
}