-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.6_pairing_data_structures.rb
139 lines (101 loc) · 2.31 KB
/
5.6_pairing_data_structures.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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# Release 0: Implement a Simple Search
=begin
def search_array(array, target)
for i in 0...array.length
index = i if array[i] == target
end
index
end
arr = ["apple", "bear", "cat", "dog"]
p search_array(arr, "cat") # => 2
p search_array(arr, "dog") # => 3
p search_array(arr, "apple") # => 0
p search_array(arr, "cats") # => nil
=end
# Release 1: Calculate Fibonacci Number
# Add a method to your file that takes a number of Fibonacci terms to generate and returns an array of the terms. For example, fib(6) would return [0,1,1,2,3,5]. Your method should work for a large number of terms. To verify your work: the last number in the array generated by fib(100) will be 218922995834555169026. (How can you verify this without having to compare this huge number manually? Be smart with your driver code!)
=begin
def fib(input)
fib_array = [0,1,1,2,3,5]
i = 94 + input
while i > fib_array.length
fib_array << fib_array[-1] + fib_array[-2]
i-=1
end
puts fib_array
end
fib(100)
=end
=begin
def fib(num)
array = [0,1,1]
num.times do |i|
array << array[-1] + array[-2]
end
p array[-4]
end
fib(100)
=end
# Release 2: Sort an Array
# Bubble Sort
=begin
---------Pseudocode---------
Create an array of integers
Start at 0 moving through the length of the array
When the index of your current index is larger than the index of the next index, swap positions
Repeat until you've gone through the length of the array
=end
def bubble_sort array
n = array.length
loop do
swapped = false
(n-1).times do |i|
if array[i] > array[i+1]
array[i], array[i+1]=array[i+1], array[i]
swapped = true
end
end
break if not swapped
end
array
end
a = [1, 4, 1, 3, 4, 1, 3, 3]
p bubble_sort(a)
=begin
def search_integers(arr, int)
index = 0
arr.each { |x|
while index < arr.length
if arr[index] == int
p index
else
p nil
end
index += 1
end
}
end
array = [1, 5, 3, 6]
search_integers(array, 8)
=end
=begin
def fibNums(n)
fib_array = []
a = 0
b = 1
if n == 0
fib_array = [0]
elsif n == 1
fib_array = [0, 1]
else
n.times {
sum = a + b
fib_array << sum
a = b
b = sum
}
end
fib_array
end
puts fibNums(3)
=end