Skip to content

Instantly share code, notes, and snippets.

@soydianapinto
Last active September 14, 2018 21:49
Show Gist options
  • Select an option

  • Save soydianapinto/6e7302913f063ca3b2bb61a5ec2fa82d to your computer and use it in GitHub Desktop.

Select an option

Save soydianapinto/6e7302913f063ca3b2bb61a5ec2fa82d to your computer and use it in GitHub Desktop.
HackerRank Ruby

HackerRank Ruby exercises

1. Hello HackerRank.

print "Hello HackerRank!!"

2. Everything is an object in Ruby.

print self

3. Object methods

return number.even?

4. Object methods parameters

a.range?(b, c)

5. Each

array.each do |user| user.update_score end

6. Unless

array.each do |user| user.update_score unless user.is_admin? end

7. Infinite loop

loop do
    coder.practice
    break if coder.oh_one?
end

8. Until

coder.practice until coder.oh_one?

9. Case (bonus question)

def identify_class(obj)
    # write your case control structure here
    case obj
        when Hacker
            puts "It's a Hacker!" 
        when Submission
            puts "It's a Submission!"
        when TestCase
            puts "It's a TestCase!"
        when Contest
            puts "It's a Contest!"
        else
            puts "It's an unknown model"
    end
end

10. Array initialization

array = Array.new
array_1 = [nil]
array_2 = [10,10]

11. Array index -1-

return arr[index]
return arr[start_pos..end_pos]
return arr[start_pos...end_pos]
return arr[start_pos,length]

12. Array index -2-

return arr[-index]
return arr.first
return arr.last
return arr.take(n)
return arr.drop(n)

13. Array addition

return arr.push(element)
return arr.unshift(element)
return arr.insert(index,element)
return arr.insert(index,index+1,index+2)

14. Array deletion

return arr.pop
return arr.shift
arr.delete_at(index)
arr.delete(val)

15. Array selection

arr.select {|a| a%2!=0}
arr.reject {|a| a%3==0}
arr.drop_while {|a| a<0}
arr.keep_if{|a| a>=0}

16. Hash initialization

empty_hash = Hash.new
default_hash = Hash.new(1)
hackerrank = {"simmy" => 100, "vivmbbs" => 200}

17. Hash each

    hash.each do |key, value|
        puts key
        puts value
    end

18. Hash addition, deletion y selection

hackerrank = Hash.new
hackerrank.store(543121,100)
hackerrank.keep_if{|key, value| value.is_a? Integer}
hackerrank.delete_if{|key, value| key % 2 == 0}

19. Enumerable introduction

colors.enum_for.to_a

20. Enumerable each-index

arr = []
animals.drop(skip).each_with_index{|item,index| arr.push("#{index+skip}:#{item}")}
arr

21. Enumerable collect

secret_messages.map { |c| c.tr("a-z", "n-za-m") }
#"hello".tr('el', 'ip')      #=> "hippo"

22. Enumerable reduce

(0..n).inject {|sum, i| sum + (i * i + 1)}
(5..10).reduce(:+)            #=> 45
#The inject and reduce methods are aliases. There is no performance benefit to either.

23. Enumerable 'any', 'all', 'none' and 'find'

hash.any? {|a| a.is_a? Integer}
hash.all? {|a| a.is_a? Integer and a<10}
hash.none? {|a| a.nil? }
hash.find {|key, value| (key.is_a?(Integer) && value.is_a?(Integer) && value < 20) or (key.is_a?(String) && value.is_a?(String) && value.start_with?('a'))}

24. Enumerable group by

def group_by_marks(marks, pass_marks)
    return marks.group_by {|x,y| y < pass_marks ? "Failed" : "Passed" }
    #    h.delete("") # For some reason it did not consider empty values
end

25. Methods introduction

def prime?(number)
    return false if [0, 1].include?(number)
    (2...number).none? { |n| number % n == 0}
end
#Solo es divisible entre 1 y él mismo. Con lo cual solo tiene 2 divisores.

26. Methods arguments

def take(arr, index)
    arr[index..arr.length] 
end

27. Methods variable arguments

def full_name(f_name,*rest,l_name)
    a = rest.reduce(f_name){|x,y| "#{x} #{y}"}
    "#{a} #{l_name}"
end 

28. Methods keyword arguments

def convert_temp(temp, input_scale:, output_scale: 'Celsius')
    case input_scale.downcase
    when 'fahrenheit'
        return output_scale == 'kelvin' ? 
        ((temp - 32) / 1.8) + 273.15 : (temp - 32) / 1.8
    when 'celsius'
        return output_scale == 'kelvin' ? 
        temp + 273.15 : (temp * 1.8) + 32
    when 'kelvin'
        return output_scale == 'celsius' ? 
        temp - 273.15 : (temp - 273.15) * 1.8
    end
end

29. Blocks

def factorial(n)
  result = (1..n).reduce(1) { |all,x| all *= x }
  yield(result)
end
n = gets.to_i
factorial(n) do |result| 
  puts result
end

30. Procs

...
proc_square_number = proc { |n| n**2 }
proc_sum_array     = proc { |n| n.reduce(:+) }
...

31. Lambdas

square      = ->(n){n**2}
plus_one    = ->(n){n+1}
into_2      = ->(n){n*2}
adder       = ->(n,m){n+m}
values_only = ->(n){n.values}
#lambda = lambda {}
#Alternative Syntax lambda = ->() {}

32. Closures

if block_given?
        yield
    end
my_proc.call
my_lambda.call

33. Partial applications

combination = combination = -> (n) do
    -> (r) do
        (n-r+1..n).inject(:*) / (1..r).inject(:*)
    end
end

34. Currying

raise_to_power = power_function.curry.call base

35. Lazy evaluation

require 'prime'
n = gets.to_i
p Prime.each.lazy.select{|x| x == x.to_s.reverse.to_i}.first(n)
#To avoid timeouts and memory allocation exceptions, we use lazy.

36. Strings introduction

'Hi'
"Hello"
<<-ALO
        hello guys! 
        it's a boautiful day
   ALO

37. Strings encoding

def transcode(s)
    #s.encode('UTF-8','ISO-8859-1') # wtf?
    s.force_encoding('UTF-8')
end

38. Strings indexing

def serial_average(str)
    arr = str.split('-')
    sss = arr[0]
    zz = ((arr[1].to_f + arr[2].to_f)/2).round(2)
    str = "#{sss}-#{zz}"
end
#" now's  the time".split        #=> ["now's", "the", "time"]

39. Strings iteration

letter.each_char.select { |c| c.bytesize > 1 }.count
#arr = [1, 2, 4, 2]
#arr.count             #=> 4

40. Strings methods I

def process_text(arr)
    arr.map {|s| s.strip}.join(" ")
end
#"    hello    ".strip   #=> "hello"
#"\tgoodbye\r\n".strip   #=> "goodbye"

41. Strings methods II

def mask_article(letter, arr)
  arr.each {|a| letter.gsub!(a,strike(a))}
  letter
end
def strike (s)
  "<strike>#{s}</strike>"
end
#"hello".gsub(/[aeiou]/, '*')     => "h*ll*"
#"hello".gsub(/([aeiou])/, '<\1>') => "h<e>ll<o>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment