Last active
September 4, 2015 11:41
-
-
Save hrumhrumble/f5184d940b4b41785bdd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# В системе авторизации есть ограничение: | |
# логин должен начинаться с латинской буквы, | |
# состоять из латинских букв, цифр, точки и минуса, | |
# но заканчиваться только латинской буквой или цифрой; | |
# минимальная длина логина — один символ, максимальная — 20. | |
# Напишите код, проверяющий соответствие входной строки этому правилу. Придумайте несколько способов решения задачи и сравните их. | |
class AuthOne | |
def initialize login | |
@login = login | |
@regexp = /^[a-zA-z]{1}[a-zA-Z0-9\.\-]{0,18}[a-zA-z0-9]$/ | |
end | |
def authorization | |
@regexp.match(@login).nil? ? 'Access denied' : 'You successfully authorized' | |
end | |
end | |
class AuthTwo | |
def initialize login | |
@login = login.downcase | |
@letters = ('a'..'z').to_a | |
@numbers = ('0'..'9').to_a | |
@symbols = %w(. -) | |
end | |
def authorization | |
length_pass? && first_letter_pass? && middle_letters_pass? && last_letter_pass? ? 'You successfully authorized' : 'Access denied' | |
end | |
private | |
def length_pass? | |
(1..20).include? @login.length | |
end | |
def first_letter_pass? | |
@letters.include? @login.chars.first | |
end | |
def middle_letters_pass? | |
@login[1..18].chars.all? { |char| (@letters + @numbers + @symbols).include?(char) } | |
end | |
def last_letter_pass? | |
(@letters + @numbers).include? @login.chars.last | |
end | |
end | |
# Есть два списка разной длины. В первом содержатся ключи, а во втором значения. | |
# Напишите функцию, которая создаёт из этих ключей и значений словарь. | |
# Если ключу не хватило значения, в словаре должно быть значение None. | |
# Значения, которым не хватило ключей, нужно игнорировать. | |
class Dictionary | |
def initialize | |
@keys = %w(key1 key2 key3 key4 key5) | |
@values = %w(1 2 3 4) | |
@index = 0 | |
end | |
def output | |
@keys.inject({}) do |memo, key| | |
@values[@index].nil? ? memo[key] = "None" : memo[key] = @values[@index] | |
@index += 1 | |
memo | |
end | |
end | |
end | |
# Description: | |
# The word i18n is a common abbreviation of internationalization the developer community use instead of typing the whole word and trying to spell it correctly. Similarly, a11y is an abbreviation of accessibility. | |
# Write a function that takes a string and turns any and all words within that string of length 4 or greater into an abbreviation following the same rules. | |
# Notes: | |
# A "word" is a sequence of alphabetical characters. By this definition, if there is a hyphen (eg. "elephant-ride"), this will produce two, one on either side (eg. "elephant" and "ride"). | |
# The abbreviated version of the word should have the first letter, then the number of removed characters, then the last letter (eg. "e6t-r2e"). | |
class Abbreviator | |
def self.abbreviate(string) | |
string.gsub(/(\w{4,})/) { |word| "#{word.chars.first}#{word.length-2}#{word.chars.last}" } | |
end | |
end | |
# Description: | |
# A palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction. Famous examples include "Amore, Roma", "A man, a plan, a canal: Panama" and "No 'x' in 'Nixon'". - wikipedia | |
# Our goal is to determine whether or not a given string is a valid palindrome or not. | |
# Like the above examples, here are a few test cases which are also populated: | |
# "Amore, Roma" => valid | |
# "A man, a plan, a canal: Panama" => valid | |
# "No 'x' in 'Nixon'" => valid | |
# "Abba Zabba, you're my only friend" => invalid | |
def palindrome(string) | |
str = string.gsub(/[^0-9a-zA-Z]+/, '').downcase | |
str == str.split(//).reduce([]) {|acc, x| [x] + acc}.join | |
end | |
# Description: | |
# Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number. | |
# Example: | |
# createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) => returns "(123) 456-7890" | |
# The returned format must be correct in order to complete this challenge. | |
# Don't forget the space after the closing parenthese! | |
def createPhoneNumber(numbers) | |
numbers.join.gsub(/([0-9]{3})([0-9]{3})([0-9]{4})/, '(\1) \2-\3') | |
end | |
# Description: | |
# Write a function that accepts a string, and returns true if it is in the form of a phone number. | |
# Assume that any integer from 0-9 in any of the spots will produce a valid phone number. | |
# Only worry about the following format: | |
# (123) 456-7890 (don't forget the space after the close parentheses) | |
# Examples: | |
# validPhoneNumber("(123) 456-7890") => returns true | |
# validPhoneNumber("(1111)555 2345") => returns false | |
# validPhoneNumber("(098) 123 4567") => returns false | |
def validPhoneNumber(phoneNumber) | |
phoneNumber.scan(/^\([0-9]{3}+\)\s[0-9]+\-[0-9]{4}$/).length > 0 ? true : false | |
end | |
# Description: | |
# Complete the squareSum method so that it squares each number passed into it and then sums the results together. | |
# For example: | |
# squareSum([1, 2, 2]) # should return 9 | |
def squareSum(numbers) | |
numbers.map.inject{|sum, element| sum + element**2} | |
end | |
# Description: | |
# Your goal is to write the group_and_count method, which should receive and array as unique parameter and return a hash. Empty or nil input must return nil instead of a hash. This hash returned must contain as keys the unique values of the array, and as values the counting of each value. | |
# Example usage: | |
# input = [1,1,2,2,2,3] | |
# group_and_count(input)# == {1=>2, 2=>3, 3=>1} | |
# The following methods were disabled: | |
# Array#count | |
# Array#length | |
def group_and_count(input) | |
input.nil? || input.empty? ? nil : input.inject(Hash.new(0)){ |hash, v| hash[v] = hash[v]+1; hash } | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment