Skip to content

Commit 51cdda7

Browse files
committed
exercism 84 Complex Numbers
1 parent b03230c commit 51cdda7

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
309309
81. [Prime Factors](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/prime_factors.rb)
310310
82. [Linked List](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/linked_list.rb)
311311
83. [ISBN Verifier](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/isbn_verifier.rb)
312+
84. [Complex Number](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/complex_number.rb)
312313

313314
<a name="leetcode"/>
314315

exercism/complex_number.rb

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Problem
2+
3+
# Solution
4+
class ComplexNumber
5+
attr_accessor :real,:imaginary
6+
7+
def initialize(real=0,imaginary=0)
8+
@real = real
9+
@imaginary = imaginary
10+
end
11+
12+
def +(other)
13+
raise ArgumentError unless other.is_a?(ComplexNumber)
14+
real = self.real + other.real
15+
imaginary = self.imaginary + other.imaginary
16+
ComplexNumber.new(real,imaginary)
17+
end
18+
19+
def -(other)
20+
raise ArgumentError unless other.is_a?(ComplexNumber)
21+
real = self.real - other.real
22+
imaginary = self.imaginary - other.imaginary
23+
ComplexNumber.new(real,imaginary)
24+
end
25+
26+
def *(other)
27+
raise ArgumentError unless other.is_a?(ComplexNumber)
28+
real = (self.real*other.real)-(self.imaginary*other.imaginary)
29+
imaginary = (self.real*other.imaginary)+(self.imaginary*other.real)
30+
ComplexNumber.new(real,imaginary)
31+
end
32+
33+
def /(other)
34+
raise ArgumentError unless other.is_a?(ComplexNumber)
35+
real = ((self.real*other.real)+(self.imaginary*other.imaginary) )/ other.abs**2
36+
imaginary = ((self.imaginary*other.real)-(self.real*other.imaginary)) / other.abs**2
37+
ComplexNumber.new(real,imaginary)
38+
end
39+
40+
def ==(other)
41+
raise ArgumentError unless other.is_a?(ComplexNumber)
42+
(self.real-other.real).abs <1e-15 and (self.imaginary-other.imaginary).abs < 1e-15
43+
end
44+
45+
def abs
46+
Math.sqrt(@real**2+@imaginary**2)
47+
end
48+
49+
def conjugate
50+
ComplexNumber.new(@real,-1*@imaginary)
51+
end
52+
53+
def exp
54+
real = Math.exp(@real)*Math.cos(@imaginary)
55+
imaginary = Math.exp(@real)*Math.sin(@imaginary)
56+
ComplexNumber.new(real,imaginary)
57+
end
58+
end

0 commit comments

Comments
 (0)