منوعات

حل مشاكل كود روبي مع hackerrank | خليجي


حل مشاكل كود روبي مع hackerrank | خليجي

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

  • للتسجيل في hackerrank تحقق من هذا المقال: شرح hackerrank

1 – دروس روبي – مرحبًا HackerRank!

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

print "Hello HackerRank!!"

2 – دروس روبي – كل شيء هو كائن

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

print self

3 – دروس روبي – معلمات طريقة الكائن

# write your code here

a.range?(b, c)

4 – دروس روبي – طرق الكائن

# add your code here

number.even?

5 – تجزئة روبي – التهيئة

# 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 – روبي هاش – لكل منهما

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

7 – تجزئة روبي – إضافة وحذف واختيار

# 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 – الإغلاق

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- التطبيقات الجزئية

combination = -> (n) do
        -> (r) do
        # 
        (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 – الكاري

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- التقييم الكسول

# 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 – بروكس

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 – لامداس

# 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 – تعدادات روبي: “أي” و “الكل” و “لا شيء” و “اعثر”

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- روبي – عددي – group_by

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

16- روبي – سلاسل – ترميز

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

17- روبي – أوتار – فهرسة

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- روبي – أوتار – التكرار

# 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- هياكل التحكم روبي – كل

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- هياكل تحكم روبي – ما لم

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 – هياكل التحكم الياقوتية – الحلقة اللانهائية

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

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

22 – هياكل التحكم روبي – حتى

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

coder.practice until coder.oh_one?

23 – هياكل تحكم روبي – حالة (سؤال إضافي)

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 – الكتل

def factorial
    yield
end

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

25- روبي – أوتار – طرق 1

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

26- روبي – أوتار – طرق 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 – صفيف روبي – الفهرس ، الجزء الثاني

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 – صفيف روبي – إضافة

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 – صفيف روبي – الحذف

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- صفيف روبي – التهيئة

# 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 – صفيف روبي – الفهرس ، الجزء الأول

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- صفيف روبي- التحديد

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- روبي – طرق – حجج

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

34- الياقوت- الطرق- الحجج المتغيرة

# 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- روبي – طرق – حجج الكلمات المفتاحية

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

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

أقرأ أيضا  شخص يقوم بأعمال خيرية في الدمام، الأحساء، حفر الباطن، الجبيل، القطيف، الخبر، الخفجي ورأس تنورة.

مقالات ذات صلة

اترك تعليقاً

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

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