مدونة البرمجةمدونة الأنترنت

حل المسائل البرمجية للغة Ruby بموقع hackerrank

Ruby HackerRank

حل المسائل البرمجية للغة Ruby بموقع hackerrank , تعتبر لغة البرمجة Ruby مميزة لإنشاء تطبيقات سطح المكتب والمواقع الثابتة وخدمات معالجة البيانات وحتى أدوات التشغيل الآلي. 

  • للتسجيل بموقع هكررانك hackerrank قم بالاطلاع على هذه المقالة : شرح موقع hackerrank
  • رابط المسائل الخاصة بلغة Ruby على موقع hackerrank : أضغط هنا

1 – Ruby Tutorial – Hello HackerRank!

# Enter your code here. Read input from STDIN. Print output to STDOUT

print "Hello HackerRank!!"

2 – Ruby Tutorial – Everything is an Object

# Enter your code here. Read input from STDIN. Print output to STDOUT

print self

3 – Ruby Tutorial – Object Method Parameters

# write your code here

a.range?(b, c)

4 – Ruby Tutorial – Object Methods

# add your code here

number.even?

5 – Ruby Hash – Initialization

# Initialize 3 variables here as explained in the problem statement
empty_hash=Hash.new
default_hash=Hash.new(1)
hackerrank={"simmy" => 100, "vivmbbs" => 200}

6 – Ruby Hash – Each

def iter_hash(hash)
    # your code here
    hash.each do |key, value|
        puts key
        puts value
    end
end

7 – Ruby Hash – Addition, Deletion, Selection

# Enter your code here. 

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

8 – 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 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)    
    
######################################################################################  

9 – Partial Applications

combination = -> (n) do
        -> (r) do
        # https://en.wikipedia.org/wiki/Combination
        (n-r+1..n).inject(:*) / (1..r).inject(:*)
    end
end

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

10 – 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)

11 – Lazy Evaluation

# Enter your code here. Read input from STDIN. Print output to STDOUT
require 'prime'

require 'prime'
primes = []
puts "[#{Prime.each.lazy.select{|x| x.to_s == x.to_s.reverse}.first(gets.to_i).join(", ")}]"

12 – Procs

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

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

puts square_of_sum(my_array, proc_square_number, proc_sum_array)

13 – Lambdas

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

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

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

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

# Write a lambda which takes a hash and returns an array of hash values
values_only = -> (h) { h.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

14 – Ruby Enumerables: ‘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.
    return 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.
    return 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.
    return 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) && value.is_a?(Integer) && value < 20) || (key.is_a?(String) && value.is_a?(String) && value.start_with?("a")) }
end

15 – Ruby – Enumerable – group_by

def group_by_marks(marks, pass_marks)
  # your code here
    marks.group_by { |student, mark| mark >= pass_marks ? "Passed" : "Failed" }
end

16 – Ruby – Strings – Encoding

# Enter your code here. 
def transcode(my_string)
    my_string.force_encoding("utf-8")
end    

17 – Ruby – Strings – Indexing

def serial_average(string_values)
  values = string_values.split('-')
  prefix = values[0]  
  average = (values[1].to_f + values[2].to_f) / 2
  formatted_average = format("%.2f", average.round(2))
  new_string = prefix + "-" + formatted_average
end

18 – Ruby – Strings – Iteration

# Your code here
def count_multibyte_char(str)
    char_count = 0
    
    str.each_char do |character|
        char_count += 1 if character.bytesize > 1
    end
    
    return char_count
end   

19 – Ruby Control Structures – Each

def scoring(array)
    # iterate through each of the element in array using *each* and call update_score on 
    array.each do |user|
        user.update_score
    end    
end

20 – Ruby Control Structures – Unless

def scoring(array)
  # update_score of every user in the array unless the user is admin
    array.each do |user|
       user.update_score unless user.is_admin? 
    end    
end

21 – Ruby Control Structures – Infinite Loop

# Enter your code here. Read input from STDIN. Print output to STDOUT

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

22 – Ruby Control Structures – Until

# Enter your code here. Read input from STDIN. Print output to STDOUT

coder.practice until coder.oh_one?

23 – Ruby Control Structures – Case (Bonus Question)

def identify_class(obj)
    # write your case control structure here
    case obj.class.to_s
        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

24 – Blocks

def factorial
    yield
end

n = gets.to_i
factorial do 
    puts (1..n).inject(:*)
end

25 – Ruby – Strings – Methods I

def process_text(array)
    array.map {|string| string.strip}.join(" ")
end

26 – Ruby – Strings – Methods II

def mask_article(text, words_array)
  words_array.each { |word| text.gsub!(word, strike(word)) }
  return text
end

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

27 – Ruby Array – 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]
    return arr[-index]
end

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

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

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

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

28 – Ruby Array – Addition

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

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

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

def index_arr_multiple_add(arr, index)
    # add any two elements to the arr at the index
    return arr.insert(index, 10, 11)
end

29 – Ruby Array – Deletion

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

def start_arr_delete(arr)
    # delete the element at the beginning of the array and return the deleted element
    return 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

30 – Ruby Array – Initialization

# Initialize 3 variables here as explained in the problem statement

array = Array.new()

array_1 = Array.new(1)

array_2 = Array.new(2, 10)

31 – Ruby Array – 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]
    return 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)
    return 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
    return 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`
    return arr[start_pos, length]
end

32 – Ruby Array – Selection

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

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

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

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

33 – Ruby – Methods – Arguments

# Your code here
def take(arr, start=1)
    return arr[start..-1]
end  

34 – Ruby – Methods – Variable Arguments

# Your code here
def full_name(first_name, *middle_names, last_name)
    full_name = ''
    full_name += first_name
    middle_names.each do |name|
       full_name += " "
       full_name += name
    end
    
    full_name += " "
    full_name += last_name
    
end  

35 – Ruby – Methods – Keyword Arguments

def convert_temp(temp, input_scale: , output_scale: 'celsius')
    return temp if input_scale == output_scale
    #Convert everything to Celsius
    case input_scale
    when "kelvin"
        temp = temp - 273.15
    when "fahrenheit"
        temp = (temp-32) * (5.0/9.0)
    end
    
    case output_scale
    when "celsius"
        return temp
    when "fahrenheit"
        return temp * (9.0/5.0) + 32
    when "kelvin"
        return temp + 273.15
    end
end

| مقالات قد تهمك |

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *

هذا الموقع يستخدم Akismet للحدّ من التعليقات المزعجة والغير مرغوبة. تعرّف على كيفية معالجة بيانات تعليقك.

زر الذهاب إلى الأعلى