Skip to content

Instantly share code, notes, and snippets.

@ricvillagrana
Last active September 13, 2018 20:02
Show Gist options
  • Save ricvillagrana/f37ff7d67f93eb60787b7a469d6fd4ab to your computer and use it in GitHub Desktop.
Save ricvillagrana/f37ff7d67f93eb60787b7a469d6fd4ab to your computer and use it in GitHub Desktop.

HackerRank Exercises

Introduction

Hello HackerRank

print "Hello HackerRank!!"

Everything is a Object

print self

Object Methods

def odd_or_even (number)
  number.even?

end autocompleted by plataform

Object Methods Parameters

a.range? b, c

Control Structures

Each

def scoring(array)
    array.each do |user| 
        user.update_score
    end
end

Unless

def scoring(array)
    array.each do |user|
        unless user.is_admin?
            user.update_score  
        end
    end
end

Infinite Loop

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

Until

until coder.oh_one?
    coder.practice
end

Case (Bonus Question)

def identify_class(obj)
    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

Strings

Introduction

def single_quote
  'Hello World and others!'
end

def double_quote
  "Hello World and others!"
end

def here_doc
  return <<-HERE
Hello World and others!    
HERE
end

Encoding

def transcode string
    string.force_encoding(Encoding::UTF_8)
end

Indexing

In this case we can split the string usign "-" as separator

def serial_average string
    s = string[0,3]
    x = string[4,5].to_f
    y = string[10,5].to_f
    z = ((x + y) /2).round(2).to_s
    if z.size < 5
        z = "0" + z
    end
    "#{s}-#{z}"
end

Iteration

def count_multibyte_char string
    multibyte_chars = 0

    string.each_char do |char|
        if char.bytesize > 1
            multibyte_chars += 1
        end
    end
    multibyte_chars
end

Methods I

def process_text strings # Check this https://stackoverflow.com/questions/12084507/what-does-the-map-method-do-in-ruby#12084555
   strings.map {|string| string.strip}.join(" ")
end

Methods II

def mask_article string, words
    words.each do |word|
        string = string.gsub(word, strike(word)) 
    end
    string
end

def strike word
   "<strike>#{word}</strike>"
end

Methods

Introduction

def prime? n
    n == 1 ? false : (2...n).none? {|m| n % m == 0}
end

Arguments

def take arr, q
    arr.shift q
    arr
end

Variable Arguments

def full_name(first, *rest)
    rest.reduce(first) { |o, x| "#{o} #{x}" }
end

Keywords Arguments

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

Currying

power_function = -> (x, z) {
    x**z
}

base = gets.to_i
raise_to_power = power_function.curry.(base)

power = gets.to_i
puts raise_to_power.(power)

Lazy Evaluation

require 'prime' ## https://ruby-doc.org/stdlib-1.9.3/libdoc/prime/rdoc/Prime.html

n = gets.to_i
primes = Prime.lazy.map { |x| x if x.to_s.reverse == x.to_s }.first 999999
primes.delete nil
print primes.take n

Partial Applications

combination = -> n do
   -> k do
       (factorial(n)) / (factorial(k) * factorial(n-k))
   end
end
def factorial n
   if n > 1
       n * factorial(n-1)
   else
       1
   end
end

n = gets.to_i
r = gets.to_i
nCr = combination.(n)
puts nCr.(r)

Procs

def square_of_sum (my_array, proc_square, proc_sum)
    sum = proc_sum.call(my_array)
    proc_square.call(sum)
end

proc_sum_array     = proc {|x| x.reduce{|y,z| y + z}}
proc_square_number = proc {|x| x**2}
my_array = gets.split().map(&:to_i)

puts square_of_sum(my_array, proc_square_number, proc_sum_array)

Arrays

Array Initialization

array = Array.new
array_1 = Array.new 1
array_2 = Array.new 2, 10

Index Part 1

def element_at(arr, index)
    # return the element of the Array variable `arr` at the position `index`
    arr.at(index) # or
    # arr[index]
end

def inclusive_range(arr, start_pos, end_pos)
    # return the elements of the Array variable `arr` between the start_pos and end_pos (both inclusive)
    arr[start_pos..end_pos]
end

def non_inclusive_range(arr, start_pos, end_pos)
    # return the elements of the Array variable `arr`, start_pos inclusive and end_pos exclusive
    arr[start_pos...end_pos]
end

def start_and_length(arr, start_pos, length)
    # return `length` elements of the Array variable `arr` starting from `start_pos`
    arr[start_pos...start_pos + length]
end

Index Part 2

def neg_pos(arr, index)
    # return the element of the array at the position `index` from the end of the list
    # Clue : arr[-index]
    arr[-index]
end

def first_element(arr)
    # return the first element of the array
    # arr.first
    arr.first
end

def last_element(arr)
    # return the last element of the array
    # arr.last
    arr.last
end

def first_n(arr, n)
    # return the first n elements of the array
    arr.take n
end

def drop_n(arr, n)
    # drop the first n elements of the array and return the rest
    arr.drop n
end

Addition

def end_arr_add(arr, element)
    # Add `element` to the end of the Array variable `arr` and return `arr`
    arr.push element
end

def begin_arr_add(arr, element)
    # Add `element` to the beginning of the Array variable `arr` and return `arr`
    arr.unshift element
end

def index_arr_add(arr, index, element)
    # Add `element` at position `index` to the Array variable `arr` and return `arr`
    arr.insert(index, element)
end

def index_arr_multiple_add(arr, index)
    # add any two elements to the arr at the index
    arr.insert(index, 0, 1)
end

Deletion

def end_arr_delete(arr)
    # delete the element from the end of the array and return the deleted element
    arr.pop
end

def start_arr_delete(arr)
    # delete the element at the beginning of the array and return the deleted element
    arr.shift
end

def delete_at_arr(arr, index)
    # delete the element at the position #index
    arr.delete_at index 
end

def delete_all(arr, val)
    # delete all the elements of the array where element = val
    arr.delete val
end

Selection

def select_arr(arr)
  # select and return all odd numbers from the Array variable `arr`
    arr.select {|n| n % 2 != 0}
end

def reject_arr(arr)
  # reject all elements which are divisible by 3
    arr.reject{|n| n % 3 == 0}
end

def delete_arr(arr)
  # delete all negative elements
    arr.delete_if{|n| n < 0}
end

def keep_arr(arr)
  # keep all non negative elements ( >= 0)
    arr.keep_if{|n| n >= 0}
end

Hashes

Initialitation

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

Each

def iter_hash(hash)
    hash.each do |key, value|
        puts key
        puts value
    end
end

Addition, Deletion, Selection

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

Lambdas

# Write a lambda which takes an integer and square it
square      = -> (n) {n**2} 

# Write a lambda which takes an integer and increment it by 1
plus_one    = -> (n) {n+1} 

# Write a lambda which takes an integer and multiply it by 2
into_2      = -> (n) {n*2} 

# Write a lambda which takes two integers and adds them
adder       = -> (x,y) {x+y} 

# Write a lambda which takes a hash and returns an array of hash values
values_only = -> (hash){hash.values} 


input_number_1 = gets.to_i
input_number_2 = gets.to_i
input_hash = eval(gets)

a = square.(input_number_1); b = plus_one.(input_number_2);c = into_2.(input_number_1); 
d = adder.(input_number_1, input_number_2);e = values_only.(input_hash)

p a; p b; p c; p d; p e

Closures

def block_message_printer
    message = "Welcome to Block Message Printer"
    if block_given?
        yield
    end
  puts "But in this function/method message is :: #{message}"
end

message = gets
block_message_printer { puts "This message remembers message :: #{message}" }

#####################################################################################

def proc_message_printer(my_proc)
    message = "Welcome to Proc Message Printer"
    my_proc.call #Call my_proc
    puts "But in this function/method message is :: #{message}"
end


my_proc = proc { puts "This message remembers message :: #{message}" }
proc_message_printer(my_proc)
    
######################################################################################    
    
def lambda_message_printer(my_lambda)
    message = "Welcome to Lambda Message Printer"
    my_lambda.call              #Call my_lambda
    puts "But in this function/method message is :: #{message}"
end

my_lambda = -> { puts "This message remembers message :: #{message}" }
lambda_message_printer(my_lambda)    
    
######################################################################################

Enumerable

Introduction

def iterate_colors(colors)
    colors.to_a
end

each_with_index

def skip_animals(animals, skip)
    animals_skkiped = Array.new
    animals.each_with_index { |animal, index| animals_skkiped.push "#{index}:#{animal}"}
    animals_skkiped.drop(skip)
end

Collect

def rot13(secret_messages)
    secret_messages.collect do |message|
        message. tr "a-zA-Z", "n-za-mN-ZA-M"
    end
end

Reduce

def sum_terms(n)
    (1..n).map{|m| m**2+1}.reduce 0, :+
end

'any', 'all', 'none', and 'find'

def func_any(hash)
    # Check and return true if any key object within the hash is of the type Integer
    # If not found, return false.
    hash.any? {|key, value| key.is_a?(Integer)}
end

def func_all(hash)
    # Check and return true if all the values within the hash are Integers and are < 10
    # If not all values satisfy this, return false.
    hash.all? {|key, value| value.is_a?(Integer) && value < 10}
end

def func_none(hash)
    # Check and return true if none of the values within the hash are nil
    # If any value contains nil, return false.
    hash.none? {|key, value| value == nil}
end

def func_find(hash)
    # Check and return the first object that satisfies either of the following properties:
    #   1. There is a [key, value] pair where the key and value are both Integers and the value is < 20 
    #   2. There is a [key, value] pair where the key and value are both Strings and the value starts with `a`.
    hash.find {|key, value| (key.is_a?(Integer) and value.is_a?(Integer) and value < 20) or (key.is_a?(String) and value.is_a?(String) and value.split("").first == 'a')}
end

group_by

def group_by_marks(marks, pass_marks)
  marks.group_by {|x| x[1] >= pass_marks ? "Passed" : "Failed"}
end

Blocks

def factorial n
    yield (1..n).reduce(1, :*)
end

n = gets.to_i
factorial n do |factorial|
    puts factorial
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment