-
Notifications
You must be signed in to change notification settings - Fork 252
/
Union&IntersectionOfArrays.rb
70 lines (58 loc) · 1.4 KB
/
Union&IntersectionOfArrays.rb
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
#Given two sorted arrays ,Print the elements in the union and intersection of these arrays
#Time-complexity:O(n+m)(n=length of array1 and m=length of array2),Auxiliary-space: O(1)
# Method for finding Union
def union(a,b)
len1=a.length
len2=b.length
ctr1=0
ctr2=0
puts "Union of the gives arrays:"
while (ctr1<len1 && ctr2<len2)
if a[ctr1]==b[ctr2]
print "#{a[ctr1]} "
ctr1+=1
ctr2+=1
elsif a[ctr1]<b[ctr2]
print "#{a[ctr1]} "
ctr1+=1
else
print "#{b[ctr2]} "
ctr2+=1
end
end
#Printing remaining elements(if any)
while ctr1<len1
print "#{a[ctr1]} "
ctr1+=1
end
while ctr2<len2
print "#{b[ctr2]} "
ctr2+=1
end
end
# Method for finding Intersection
def intersection(a,b)
len1=a.length
len2=b.length
ctr1=0
ctr2=0
puts "Intersection of the gives arrays:"
while (ctr1<len1 && ctr2<len2)
if a[ctr1]==b[ctr2]
print "#{a[ctr1]} "
ctr1+=1
ctr2+=1
elsif a[ctr1]<b[ctr2]
ctr1+=1
else
ctr2+=1
end
end
end
#Ruby magic: One line solutions
def union(a,b)
print a | b # union([1,2,3],[2,3,4]) => [1, 2, 3, 4]
end
def intersection(a,b)
print a & b # intersection([1,2,3],[2,3,4]) => [2, 3]
end