Skip to content

Instantly share code, notes, and snippets.

@tjhanley
Last active March 1, 2016 16:06
Show Gist options
  • Save tjhanley/5072970 to your computer and use it in GitHub Desktop.
Save tjhanley/5072970 to your computer and use it in GitHub Desktop.
Simple Problems
def add_1_to_n(n)
return n <= 0 ? 0 : n + add_1_to_n( n - 1 )
end
puts add_1_to_n(10) #=> 55
# create a function that generates a deck of cards
# a deck has many suits
# a suit has many cards
# a card has a suit and a rank
suits = %w{ C D H S }
ranks = [ *2..10, *%w{ J Q K A } ] #splat
card_deck = suits.product(ranks).shuffle
card_deck.first(13)
ary = ["A", "B", "C", "B", "A"]
#ary.group_by { |e| e }.select { |k, v| v.size > 1 }.map(&:first)
#
#ary.sort.chunk { |e| e }.select { |e, count| count.size > 1 }.map(&:first)
ary.select { |e| ary.count(e) > 1 }.uniq
100.times do |n|
str = ''
str += 'Fizz' if n % 3 === 0
str += 'Buzz' if n % 5 === 0
puts str.length > 1 && str || n
end
def palindrome?(value)
if value.kind_of? String
value.eql?(value.to_s.reverse)
elsif value.kind_of? Integer
value.eql?(value.to_s.reverse.to_i)
else
puts "not a string or integer"
return false
end
end
#irb(main):028:0> palindrome?('racecar')
#=> true
#irb(main):029:0> palindrome?('liam')
#=> false
#irb(main):030:0> palindrome?(121)
#=> true
#irb(main):031:0> palindrome?(122)
#=> false
#irb(main):032:0> palindrome?(1221)
#=> true
#irb(main):033:0> palindrome?([1233])
#not a string or integer
#=> false
require 'set'
set = Set.new([1,2,3])
result = Set.new(set) #1,2,3
result << Set.new() # {}
class Set
def pop
temp = self.to_a.pop
self.delete(temp)
temp
end
end
set.each do |e, index|
while set.size >= 1 do
last_element = set.pop() #=>3
result << last_element #=> {3}, {2}, {1}
set.each do |e|
result << Set.new([e,last_element])
end
end
end
# convert array of tuples to hash
# [['a',1], ['b',2], ['c','3' ]]
# with values as ints
# {"a"=>1, "b"=>2, "c"=>3}
a = [['a',1], ['b',2], ['c','3' ]]
h = Hash[*a.flatten]
#=> {"a"=>1, "b"=>2, "c"=>"3"}
h.each do |k,v|
h[k] = v.to_i
end
#=> {"a"=>1, "b"=>2, "c"=>3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment