Skip to content

Instantly share code, notes, and snippets.

@alexaltair
Created July 8, 2013 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexaltair/5946280 to your computer and use it in GitHub Desktop.
Save alexaltair/5946280 to your computer and use it in GitHub Desktop.
Weekend Ruby practice
def fibonacci(n)
if (0..1) === n
n
else
fibonacci(n-1) + fibonacci(n-2)
end
end
def prime_list(highest)
list = Array.new(highest, true)
# Because 0 and 1 are not primes, and we want the indices to match.
list[0..1] = false, false
# If a number has a factor greater than its square root, then it also has a factor less than its square root.
limit = Math.sqrt(highest)
test = 2
while test < limit
multiple = 2*test
while multiple < highest
list[multiple] = false
multiple += test
end
# Find the first instance of true after test. This is our next highest prime.
test = list[(test+1)..highest].index(true) + test + 1
end
# Use this line without what's below to get the last prime.
# list.rindex(true)
list.each_with_index do |bool, index|
if bool
list[index] = index
end
end
list.select { |entry| entry }
end
def pair_array_to_hash(pair_array)
hash = Hash.new
pair_array.each do |pair|
hash[pair[0]] = pair[1]
end
hash
end
def string_compressor(string)
output_string = ''
char = 1
counter = 1
while char <= string.length
if string[char] == string[char-1]
counter += 1
else
unless counter == 1; output_string << counter.to_s end
output_string << string[char-1]
counter = 1
end
char += 1
end
output_string
end
def multiplication_table(n, m)
cell_size = (n*m).to_s.length + 1
(1..n).map do |row_num|
row = (1..m).map do |col_num|
number = (col_num*row_num).to_s
' '*(cell_size - number.length) + number
end
puts row.join('')
end
end
def pascal_triangle(rows)
row_array = Array.new(rows+1) {Hash.new(0)}
row_array[0][0] = 1
(1..rows).each do |size|
(0..size).each do |entry|
row_array[size][entry] = row_array[size-1][entry-1] + row_array[size-1][entry]
end
end
# Now convert to strings
biggest = row_array.last.length/2
cell_width = row_array.last[biggest].to_s.length * 2
row_array.map! do |row|
row.each_pair do |key, value|
row[key] = ' '*(cell_width - value.to_s.length) + value.to_s
end
row[0] = row[0].lstrip
row = row.values.join('')
end
row_width = row_array.last.length
row_array.each do |row|
puts row.center(row_width)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment