Merge pull request #1 from l3kn/master

Add examples in ruby
This commit is contained in:
Aditya Bhargava
2016-03-03 09:24:02 -08:00
16 changed files with 308 additions and 0 deletions

View File

@@ -0,0 +1,26 @@
def binary_search(list, item)
low = 0
high = list.length - 1
while low <= high
mid = (low + high) / 2
guess = list[mid]
if guess == item
return mid
elsif guess > item
high = mid - 1
else
low = mid + 1
end
end
return nil
end
my_list = [1, 3, 5, 7, 9]
puts binary_search(my_list, 3) # => 1
# We need to use .inspect here because just printing nil
# would output an empty string
puts binary_search(my_list, -1).inspect # => nil

View File

@@ -0,0 +1,29 @@
# Finds the smallest value in an array
def find_smallest(arr)
# Stores the smallest value
smallest = arr[0]
# Stores the index of the smallest value
smallest_index = 0
# (1...n) is the same as (1..(n-1))
(1...(arr.length)).each do |i|
if arr[i] < smallest
smallest = arr[i]
smallest_index = i
end
end
smallest_index
end
# Sort array
def selection_sort(arr)
new_arr = []
arr.length.times do
# Finds the smallest element in the array and adds it to the new array
smallest = find_smallest(arr)
new_arr.push(arr.delete_at(smallest))
end
new_arr
end
# 'p obj' is the same as 'puts obj.inspect'
p selection_sort([5, 3, 6, 2, 10])

View File

@@ -0,0 +1,12 @@
def countdown(i)
puts i
# base case
if i <= 0
return
# recursive case
else
countdown(i - 1)
end
end
countdown(5)

View File

@@ -0,0 +1,16 @@
def greet2(name)
puts "how are you, #{name}?"
end
def bye
print "ok bye!"
end
def greet(name)
puts "hello, #{name}!"
greet2(name)
puts "getting ready to say bye..."
bye
end
greet("adit")

View File

@@ -0,0 +1,9 @@
def fact(x)
if x == 1
1
else
x * fact(x - 1)
end
end
puts fact(5)

View File

@@ -0,0 +1,10 @@
def sum(arr)
total = 0
arr.each do |x|
total += x
end
total
end
puts sum([1, 2, 3, 4])

View File

@@ -0,0 +1,4 @@
def sum(list)
return 0 if list.empty?
list[0] + sum(list[1..-1])
end

View File

@@ -0,0 +1,4 @@
def count(list)
return 0 if list.empty?
1 + count(list[1..-1])
end

View File

@@ -0,0 +1,9 @@
def max(list)
if list.length == 2
# condition ? then : else
list[0] > list[1] ? list[0] : list[1]
else
sub_max = max(list[1..-1])
list[0] > sub_max ? list[0] : sub_max
end
end

View File

@@ -0,0 +1,18 @@
def quicksort(array)
if array.length < 2
# base case, arrays with 0 or 1 element are already "sorted"
array
else
# recursive case
pivot = array[0]
# sub-array of all the elements less than the pivot
rest = array[1..-1]
less = rest.select { |i| i <= pivot }
# sub-array of all the elements greater than the pivot
greater = rest.select { |i| i > pivot }
quicksort(less) + [pivot] + quicksort(greater)
end
end
print quicksort([10, 5, 2, 3])

View File

@@ -0,0 +1,8 @@
# {} is the same as Hash.new
book = {}
# an apple costs 67 cents
book["apple"] = 0.67
# milk costs $1.49
book["milk"] = 1.49
book["avocado"] = 1.49
puts book

View File

@@ -0,0 +1,16 @@
# in order to be accessible from within the check_voter function
# voted has to be an instance variable (or global / class)
@voted = {}
def check_voter(name)
if @voted.key?(name) && @voted[name]
puts "kick them out!"
else
@voted[name] = true
puts "let them vote!"
end
end
check_voter("tom")
check_voter("mike")
check_voter("mike")

View File

@@ -0,0 +1,40 @@
def person_is_seller(name)
name[-1] == "m"
end
@graph = {}
# %w(string1 string2 ...) is a shorter way to define arrays of strings
@graph["you"] = %w(alice bob claire)
@graph["bob"] = %w(anuj peggy)
@graph["alice"] = %w(peggy)
@graph["claire"] = %w(thom jonny)
@graph["anuj"] = []
@graph["peggy"] = []
@graph["thom"] = []
@graph["jonny"] = []
def search(name)
search_queue = []
search_queue += @graph[name]
# This array is how you keep track of which people you've searched before.
searched = []
until search_queue.empty?
person = search_queue.shift
# Only search this person if you haven't already searched them.
next if searched.member?(person)
if person_is_seller(person)
puts "#{person} is a mango seller!"
return true
else
search_queue += @graph[person]
# Marks this person as searched
searched.push(person)
end
end
false
end
search("you")

View File

@@ -0,0 +1,69 @@
# the graph
graph = {}
graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2
graph["a"] = {}
graph["a"]["fin"] = 1
graph["b"] = {}
graph["b"]["a"] = 3
graph["b"]["fin"] = 5
graph["fin"] = {}
# the costs table
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = Float::INFINITY
# the parents table
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = nil
@processed = []
def find_lowest_cost_node(costs)
lowest_cost = Float::INFINITY
lowest_cost_node = nil
# Go through each node.
costs.each do |node, cost|
# If it's the lowest cost so far and hasn't been processed yet...
if cost < lowest_cost && !@processed.member?(node)
# ... set it as the new lowest-cost node.
lowest_cost = cost
lowest_cost_node = node
end
end
lowest_cost_node
end
# Find the lowest-cost node that you haven't processed yet.
node = find_lowest_cost_node(costs)
# If you've processed all the nodes, this while loop is done.
until node.nil?
cost = costs[node]
# Go through all the neighbors of this node.
neighbors = graph[node]
neighbors.keys.each do |n|
new_cost = cost + neighbors[n]
# If it's cheaper to get to this neighbor by going through this node...
if costs[n] > new_cost
# ... update the cost for this node.
costs[n] = new_cost
# This node becomes the new parent for this neighbor.
parents[n] = node
end
end
# Mark the node as processed.
@processed << node
# Find the next node to process, and loop.
node = find_lowest_cost_node(costs)
end
puts "Cost from the start to each node:"
puts costs

View File

@@ -0,0 +1,31 @@
require "set"
# You pass an array in, and it gets converted to a Set.new.
states_needed = Set.new(%w(mt wa or id nv ut ca az))
stations = {}
stations["kone"] = Set.new(%w(id nv ut))
stations["ktwo"] = Set.new(%w(wa id mt))
stations["kthree"] = Set.new(%w(or nv ca))
stations["kfour"] = Set.new(%w(nv ut))
stations["kfive"] = Set.new(%w(ca az))
final_stations = Set.new
until states_needed.empty?
best_station = nil
states_covered = Set.new
stations.each do |station, states|
covered = states_needed & states
if covered.length > states_covered.length
best_station = station
states_covered = covered
end
end
states_needed -= states_covered
final_stations << best_station
end
p final_stations

View File

@@ -0,0 +1,7 @@
if word_a[i] == word_b[j]
# The letters match.
cell[i][j] = cell[i-1][j-1] + 1
else
# The letters don't match.
cell[i][j] = [cell[i-1][j], cell[i][j-1]].max
end