Skip to content

Instantly share code, notes, and snippets.

@lfborjas
Created April 16, 2012 18:34
Show Gist options
  • Save lfborjas/2400561 to your computer and use it in GitHub Desktop.
Save lfborjas/2400561 to your computer and use it in GitHub Desktop.
Mis soluciones a los cinco ejercicios que no usaban OOP
prueba = %w(ruby es divertido)
def longitudes arr
arr.map(&:length)
end
puts longitudes(prueba)
prueba = "Ruby es el mejor lenguaje porque ruby es el MEJOR"
def histograma paragraph
paragraph.downcase!
palabras = paragraph.split(/\s+/)
frecuencias = {}
palabras.uniq.each do |palabra|
frecuencias[palabra] = palabras.count(palabra)
end
frecuencias.each do |palabra, frecuencia|
puts "#{palabra}: #{ '*' * frecuencia}"
end
end
puts histograma(prueba)
class Fixnum
#from http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2
def prime?
(1..100).collect do
a = rand(1 .. self - 1)
a == expmod(a, self, self)
end.all?
end
private
def expmod(base, exp, m)
return 1 if exp.zero?
if exp.even?
(expmod(base, exp / 2, m) ** 2) % m
else
base * expmod(base, exp - 1, m) % m
end
end
end
2.upto(10){ |n| puts "#{n} es primo" if n.prime? }
def phone_code(phrase)
keymap = {
2 => %w(A B C),
3 => %w(D E F),
4 => %w(G H I),
5 => %w(J K L),
6 => %w(M N O),
7 => %w(P Q R S),
8 => %w(T U V),
9 => %w(W X Y Z),
0 => [' ']
}
phrase.each_char.map do |char|
char.upcase!
the_key, the_mapping = keymap.find{|key, mapping| mapping.include?(char) }
the_key.to_s * (the_mapping.index(char) + 1)
end.join(" ")
end
puts phone_code("hola mundo la silla y el estante")
def eval_rpn(exp)
operations = {}
%w(+ - * /).each do |operator|
operations[operator] = ->(a, b){ eval("a #{operator} b") }
end
tokens = exp.split /\s+/
stack = []
tokens.each do |token|
unless operations.include?(token)
stack.push token.to_i
else
operands = []
operation = operations[token]
operation.arity.times do
raise "Insufficient operands" if stack.empty?
operands << stack.pop
end
stack.push operation.call *operands
end
end
raise "Unbalanced expression" if stack.size > 1
stack.pop
end
loop do
print "RPN> "
exp = gets.chomp
puts "=> #{eval_rpn(exp)}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment