Skip to content

Commit f05928d

Browse files
mesutcanmesutcan
mesutcan
authored and
mesutcan
committed
my implementation of various algorithms in Ruby
0 parents  commit f05928d

7 files changed

+199
-0
lines changed

README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Various implementations of Ruby algorithms, all the codes have explanations.

definewords.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
require "open-uri"
2+
3+
unless ARGV[0]
4+
puts "You must supply a word to define."
5+
puts "USAGE: ruby define.rb <word to define>"
6+
exit
7+
end
8+
9+
word = ARGV[0].strip
10+
11+
url = "http://dictionary.reference.com/browse/#{word}"
12+
13+
begin
14+
15+
open(url) do |source|
16+
source.each_line do |x|
17+
if x=~ /No results found/
18+
puts "\nPlease check spelling,no definition was found."
19+
exit
20+
end
21+
if x=~ /(1\.)<\/td><td valign="top">(.*)<\/td/
22+
puts "\n#{$1} #{$2}"
23+
exit
24+
end
25+
end
26+
puts "Sorry, unable to find a definition."
27+
end
28+
rescue => e
29+
puts "An error occurred, please try again."
30+
puts e
31+
end
32+
#appending a word to the URL will automatically return the definition.
33+
34+
#open-uri lets us type open(), pass the URL to the method and retrieve a webpage.
35+
36+
#if the definition is found, the script will begin isolating exactly where the definition resides in the source code.
37+
38+

dijkstra.rb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes.
2+
# Mark all nodes except the initial node as unvisited. Set the initial node as current. Create a set of the unvisited nodes called the unvisited set consisting of all the nodes except the initial node.
3+
# For the current node, consider all of its unvisited neighbors and calculate their tentative distances. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B (through A) will be 6+2=8. If this distance is less than the previously recorded distance, then overwrite that distance. Even though a neighbor has been examined, it is not marked as visited at this time, and it remains in the unvisited set.
4+
#When we are done considering all of the neighbors of the current node, mark it as visited and remove it from the unvisited set. A visited node will never be checked again; its distance recorded now is final and minimal.
5+
# The next current node will be the node marked with the lowest (tentative) distance in the unvisited set.
6+
# If the unvisited set is empty, then stop. The algorithm has finished. Otherwise, set the unvisited node marked with the smallest tentative distance as the next "current node" and go back to step 3.
7+
# Using adjacent lists and using a binary heap, pairing heap and Fibonacci heap as a priority queue to implement extracting minimum efficiency.
8+
9+
10+
require 'pqueue'
11+
12+
class Dijkstra
13+
INFINITY = 1 << 32
14+
15+
def self.dijkstra(source, edges, weights, n)
16+
visited = Array.new(n, false)
17+
shortest_distances = Array.new(n,infinity)
18+
previous = Array.new(n,nil)
19+
pq = PQueue.new(proc {|x,y| shortest_distances[x] < shortest_distances[y]})
20+
21+
pq.push(source)
22+
visited = true
23+
shortest_distances = 0
24+
25+
while pq.size != 0
26+
v=pq.pop
27+
visited[v] = true
28+
if edges[v]
29+
edges[v].each do |w|
30+
if !visited[w] and shortest_distances[w] > shortest_distances[v] + weights[v][w]
31+
shortest_distances[w]=shortest_distances[v] + weights[v][w]
32+
previous[w] = v
33+
pq.push(w)
34+
end
35+
end
36+
end
37+
end
38+
return [shortest_distances, previous]
39+
end
40+
end
41+
42+

flashcards.rb

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
unless ARGV[0]
2+
puts "\n\nUsage is flashCards.rb <file>\n\n"
3+
exit
4+
end
5+
6+
flash = []
7+
card = Struct.new(:question,:answer)
8+
# Use Struct to create our own data structure called card.
9+
File.open(ARGV[0],"rb").each do |line|
10+
if line =~ /(.*)\s{3,10}(.*)/
11+
flash << card.new($1.strip,$2.strip)
12+
end
13+
end
14+
15+
flash.replace(flash.sort_by{rand})
16+
17+
until flash.empty?
18+
drill = flash.pop
19+
print "#{drill.question}?"
20+
guess = $stdin.gets.chomp
21+
22+
if guess.downcase == drill.answer.downcase
23+
puts "\n\nCorrect -- The answer is: #{drill.answer}\n\n\n"
24+
else
25+
puts "\n\nWRONG -- The answers is :#{drill.answer}\n\n\n"
26+
end
27+
end
28+
29+
# Flash card file inline is broken down line by line. Each flash card is added to an aray called flash. Once it reaches the end-of-file, the array flash has a complete collection of cards with questions and answers on them.
30+
31+

luhn_algorithm.rb

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Luhn algorithm
2+
# 1. Starting with the next to last digit and continuing with every other
3+
# digit going back to the beginning of the card, double the digit
4+
# 2. Sum all doubled and untouched digits in the number
5+
# 3. If that total is a multiple of 10, the number is valid
6+
7+
card_num = ARGV.join
8+
9+
case
10+
when (card_num=~/^(34|37)\d{13}$/): print 'AMEX '
11+
# it is amex when it begins with 34 vor 36 and the length is 15 numbers in total.
12+
when (card_num=~/^6011\d{12}$/): print 'Discover '
13+
# it is discover when it begins with 6011 and the length is 16 numbers in total.
14+
when (card_num=~/^5[1-5]\d{14}$/): print 'MasterCard '
15+
# it is mastercard when it begins with 51-55 and the length is 16 numbers in total.
16+
when (card_num=~/^4(\d{12}|\d{15})$/): print 'Visa '
17+
# it is visa when it begins with 4 and the length is 13 or 16 numbers in total.
18+
else print 'Unknown '
19+
end
20+
21+
i = 0
22+
23+
luhn_number = ''
24+
25+
card_num.reverse.each_byte {|char|
26+
if (i%2==1) then
27+
char = (char.chr.to_i * 2).to_s
28+
else
29+
char = char.chr
30+
end
31+
luhn_number = char + luhn_number
32+
i += 1
33+
}
34+
35+
sum = 0
36+
37+
luhn_number.each_byte {|char| sum += char.chr.to_i }
38+
39+
if (sum%10==0) then
40+
print "Valid credit card\n"
41+
else
42+
print "Invalid credit card\n"
43+
end

piglatin.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#Implementation of piglatin algorithm
2+
class PigLatin
3+
def pig(word)
4+
leadingCap = word =~ /^A-Z?
5+
word.downcase!
6+
res = case word
7+
#when vowels word + way
8+
when /^aeiouy/
9+
word+"way"
10+
#otherwise, start from the back to concatanete with the first letter and add ay
11+
when /^([^aeiouy]+)(.*)/
12+
$2 + $1 + "ay"
13+
else
14+
word
15+
end
16+
leadingCap ? res.capitalize : res
17+
end
18+
19+
def showPig
20+
#split the value into array and collect the words and join them into a string.
21+
@text.value = @text.value.split.collect{|w| pig(w)}.join(" ")
22+
end
23+
end

word_frequency.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
puts 'What is the name and path of the file?'
2+
filename = gets.chomp
3+
text = String.new
4+
File.open(filename) { |f| text = f.read }
5+
6+
#matches anything that isn't alphabetical character
7+
words = text.split(/[^a-zA-Z]/)
8+
9+
freqs = Hash.new(o)
10+
#key will be a unique word and it's value is the # of times it occurs in the text.
11+
words.each{|word| freqs[word] +=1}
12+
freqs = freqs.sort_by{|x,y| y}
13+
freqs.reverse!
14+
freqs.each{|word,freq| puts word+ ' '+freq.to_s}
15+
16+
17+
words = File.open('filename.txt') {|f| f.read}.split
18+
freqs = Hash.new(0)
19+
words.each {|word| freqs[word] +=1}
20+
freqs.sort_by{|x,y| y}.reverse.each{|w,f| puts w+ '' + f.to_s}
21+

0 commit comments

Comments
 (0)