Tuesday, 12 July 2016

Select Map

Difficulty:
Easy

Tags:
enumerables, procs

Instructions:
The Pattern object not only functions as a Regexp. For example, check out what happens if you do Pattern === element. This problem demonstrates that using a Pattern with #grep will work much like using select and map in combination.

Problem and Solution:

# Solution to 'Select Map' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/select-map
assert_equal ["1", 2, "3", 4, "5"].grep(/[1-5]/){ |e| e.succ }, ["2", "4", "6"]
assert_equal [0, 1, 3, 5, 6].grep(1..5, &:succ), [2, 4, 6]
assert_equal ["1", "2", "3", "4", "5"].grep(proc{|ele| ele.to_i%2 ==1}){ |e| e.succ }, ["2", "4", "6"]
assert_equal [1, 2, 3, 4, 5].grep(proc{|ele| ele.to_i%2 ==1}, &:succ), [2, 4, 6]
view raw Select Map.rb hosted with ❤ by GitHub

Pack Template UTF-8

Difficulty:
Easy

Tags:
pack

Instructions:
Write pack template of UTF-8.

Problem and Solution:

# Solution to 'Pack Template UTF-8' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/pack-template-utf-8
# -*- coding: utf-8 -*-
assert_equal [0, 1].pack('U*'), "\000\001"
assert_equal [0x7f].pack('U*'), "\177"
assert_equal [0x80].pack('U*'), "\302\200"
assert_equal "\u3042".unpack('U*'), [0x3042]
assert_equal "あいうえお".unpack('U*'), [12354, 12356, 12358, 12360, 12362]
assert_equal [12354, 12356, 12358, 12360, 12362].pack('U*'), "あいうえお"

Simple String Substitution

Difficulty:
Easy

Tags:
strings

Instructions:
One of the challenges in implementing Rubeque is performing string substitution. See how well you can do.

Problem and Solution:

# Solution to 'Simple String Substitution' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/simple-string-substitution
class String
def simple_sub(pattern, replace)
gsub(/#{Regexp.escape(pattern)}/ ) {replace}
end
end
subject = "?? == ??"
assert_equal subject.simple_sub("==", "<="), "?? <= ??"
assert_equal subject.simple_sub("abc", "def"), "?? == ??"
assert_equal subject.simple_sub("??", "fun??"), "fun?? == fun??"
naruse_answer = "Date.parse(date.sub(/(\d+)[-\/](\d\d).(\d{4})/,'\\3-\\1-\\2')).strftime('%b %d, %Y')"
assert_equal subject.simple_sub("??", naruse_answer), "#{naruse_answer} == #{naruse_answer}"

Quelle Heure Est-Il?

Difficulty:
Easy

Tags:
dates, strings

Instructions:
Write a function to parse some dates and return a standard format. Hint: the help page might be of use.

Problem and Solution:

# Solution to 'Quelle Heure Est-Il?' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/quelle-heure-est-il-ques-
def pretty_date(date)
months = ["January","February","March","April","May","June","July","August","Sepetember","October","November","December"]
mon_to_mon3 = {}
mon_nbr_to_mon3 = {}
months.each_with_index {|m,i| mon_to_mon3[m] = m[0...3]; mon_nbr_to_mon3[i+1] = mon_to_mon3[m]}
case date
when /^\d*\d-\d*\d-\d{4}/ # mm-dd-yyyy
a = date.split('-')
"" << mon_nbr_to_mon3[a[0].to_i] << " " << a[1] << ", " << a[2]
when /^[a-zA-Z]+ \d*\d, \d{4}/ # MONTH dd, yyyy
a = date.split
mon_to_mon3[a[0]] << " " << a[1] << " " << a[2]
when /^\d{4}-\d*\d-\d*\d/ # yyyy-mm-dd
a = date.split('-')
mon_nbr_to_mon3[a[1].to_i] << " " << a[2] << ", " << a[0]
when /^\d*\d\/\d*\d\/\d{4}/ # mm/dd/dddd
a = date.split(/\//)
mon_nbr_to_mon3[a[0].to_i] << " " << a[1] << ", " << a[2]
else
puts "no match"
end
end
assert_equal pretty_date("11-30-1835"), "Nov 30, 1835"
assert_equal pretty_date("July 20, 1933"), "Jul 20, 1933"
assert_equal pretty_date("1922-11-11"), "Nov 11, 1922"
assert_equal pretty_date("9/20/1978"), "Sep 20, 1978"

Implement a Hash With Indifferent Access

Difficulty:
Easy

Tags:
hashes, classes

Instructions:
Implement a hash class which does not distinguish between symbols and strings for its keys.

Problem and Solution:

# Solution to 'Implement a Hash With Indifferent Access' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/implement-a-hash-with-indifferent-access
class HashWithIndifferentAccess
def initialize(hash = {})
@attributes = Hash.new
hash.each { |key, val| self[key] = val }
end
def []=(key, value)
@attributes[key.to_sym] = value
end
def [](key)
@attributes[key.to_sym]
end
def self.[](*arr)
self.new(Hash[*arr])
end
end
composers = HashWithIndifferentAccess.new
composers[:Janacek] = "Leos Janacek"
composers["Sweelinck"] = "Jan Pieterszoon Sweelinck"
mathematicians = HashWithIndifferentAccess["Yutaka", "Taniyama", :Alonzo, "Church"]
assert_equal composers["Janacek"], "Leos Janacek"
assert_equal composers[:Sweelinck], "Jan Pieterszoon Sweelinck"
assert_equal mathematicians[:Yutaka], "Taniyama"
assert_equal (mathematicians["Alonzo"] == mathematicians[:Alonzo]), true

Unidentified X Object

Difficulty:
Easy

Tags:
strings, operators

Instructions:
Use comparison operators.

Problem and Solution:

# Solution to 'Unidentified X Object' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/unidentified-x-object
assert_equal "X" * ( 2 <=> 2 ), ""
assert_equal "X" * ( 2 <=> 0 ), "X"

Join URL params

Difficulty:
Easy

Tags:
url, params

Instructions:
Join parameters to a link.

Problem and Solution:

# Solution to 'Join URL params' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/join-url-params
def join_params(link, url_parameters)
link+'?'+url_parameters.map{|k,v| "#{k}=#{v}"}.join('&')
end
url_params = {
'first_param' => 123,
'second_param' => 456,
'third_param' => 678
}
url = 'http://www.foobar.com'
assert_equal 'http://www.foobar.com?first_param=123&second_param=456&third_param=678', join_params(url, url_params)

The Gray Area

Difficulty:
Easy

Tags:
booleans

Instructions:
Write code that will make true equal false in the following problem.

Problem and Solution:

# Solution to 'The Gray Area' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/the-gray-area
class TrueClass
def == x
return !x
end
end
assert_equal true, false

Implement Array#interleave

Difficulty:
Easy

Tags:
arrays

Instructions:
Implement an Array method to interleave an array with a dynamic number of arguments or an array.

Problem and Solution:

# Solution to 'Implement Array#interleave' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/implement-array-hash-interleave
class Array
def interleave(*args)
args.flatten.each do |ele|
insert((ele.to_i-1), ele)
end
compact
end
end
assert_equal [1, 3, 5].interleave(2, 4, 6), [1, 2, 3, 4, 5, 6]
assert_equal [1, 3, 5].interleave([2, 4]), [1, 2, 3, 4, 5]
assert_equal [1, 3, 5].interleave("2", "4"), [1, "2", 3, "4", 5]
assert_equal [].interleave(2, 4, 6), [2, 4, 6]
assert_equal [1, 2, 3].interleave(), [1, 2, 3]

Counting Elements in Array

Difficulty:
Easy

Tags:
arrays

Instructions:
Count elements in an Array by returning a hash with keys of the elements and values of the amount of times they occur.

Hidden Code:
There is hidden code with assertions that is also being run to test out your code.

Problem and Solution:

# Solution to 'Counting Elements in Array' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/counting-elements-in-array
test = ['cat', 'dog', 'fish', 'fish']
def count(array)
hm={};
array.each{| ele| (hm[ele] ? (hm[ele]+=1) : (hm[ele] = 1))};
hm
end
assert_equal ({ 'cat' => 1, 'dog' => 1, 'fish' => 2 }), count(test)

Architecting a Solution

Difficulty:
Easy

Tags:
structs, classes

Instructions:
Use a Struct to define an Architect class.

Hidden Code:
There is hidden code with assertions that is also being run to test out your code.

Problem and Solution:

# Solution to 'Architecting a Solution' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/architecting-a-solution
Architect = Struct.new(:name, :works)
flr = Architect.new("frank loyd wright")
imp = Architect.new("I. M. Pei", ["new college dorms", "jfk library"])
flr.works = ["Guggenheim", "fallingwater"]
assert_equal flr.name, "frank loyd wright"
assert_equal imp.works, ["new college dorms", "jfk library"]

A Man, A Plan, A Canal--Panama!

Difficulty:
Easy

Tags:
strings

Instructions:
A palindrome is a string that is written the same forward as it is in reverse. Write a method to return the longest palindrome in a given string

Problem and Solution:

# Solution to 'A Man, A Plan, A Canal--Panama!' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/a-man-comma--a-plan-comma--a-canal--panama-excl-
def longest_palindrome(inp)
len = inp.length
longest = ''
inp.chars.to_a.each_with_index do |c, i|
# Check 1
str = inp[0..i]
rev = str.reverse
longest = str if (str == rev && longest.length < str.length)
# Check 2
i.times do |t|
sub_str = str[t..i]
sub_rev = sub_str.reverse
longest = sub_str if (sub_str == sub_rev && longest.length < sub_str.length)
end
end
longest
end
assert_equal longest_palindrome("xyzzy"), "yzzy"
assert_equal longest_palindrome("afbbbfjdjklgdfdhfdkjfffhhfffjkdfhdhkyejejfjkd"), "dhfdkjfffhhfffjkdfhd"
assert_equal longest_palindrome("bartarcarracecarbartar"), "racecar"
assert_equal longest_palindrome("3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982"), "46264"

Defusing a Bomb

Difficulty:
Easy

Tags:
nil, exceptions

Instructions:
Prevent the following code from throwing an expection

Problem and Solution:

# Solution to 'Defusing a Bomb' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/defusing-a-bomb
class NilClass
def length
0
end
def reverse
''
end
end
assert_equal nil.length == 5, false
assert_equal nil.reverse == "rubeque", false

Related keys of Hash

Difficulty:
Easy

Tags:
hashes

Instructions:
Get keys of a hash whose values equal to given arguments.

Problem and Solution:

Fixing Bad Code the Wrong Way

Difficulty:
Easy

Tags:
method_missing, classes

Instructions:
Your coworker did a bad job defining a class. Fix it for him using #method_missing.

Problem and Solution:

# Solution to 'Fixing Bad Code the Wrong Way' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/fixing-bad-code-the-wrong-way
class Person
def initialize(name, age, incoming_race)
@name = name
@age = age
self.race = incoming_race
end
def nam
@name.split.map(&:capitalize).join(" ")
end
def agE
@age
end
def method_missing(m, *args)
if (m.to_s.downcase.match /name/)
"Kurt Vonnegut"
elsif (m.to_s.downcase.match /race/)
"Caucasian"
elsif (m.to_s.downcase.match /age/)
89
else
super
end
end
end
person = Person.new("kurt vonnegut", 89, "caucasian")
assert_equal person.name, "Kurt Vonnegut"
assert_equal person.race, "Caucasian"
assert_equal person.age, 89

Random Boolean

Difficulty:
Easy

Tags:
rand, booleans

Instructions:
Return random booleans

Problem and Solution:

# Solution to 'Random Boolean' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/random-boolean
def random_boolean
rand < rand
end
array = []
100.times do
if random_boolean
array << :dummy
end
end
assert_equal (1..100) === array.size, true
assert_equal array.size != 100, true

Separating Numbers with Commas

Difficulty:
Easy

Tags:
strings, regular expressions

Instructions:
Separate numbers with a comma each three digits.

Problem and Solution:

# Solution to 'Separating Numbers with Commas' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/separating-numbers-with-commas
def separate_with_comma(n)
n.to_s.reverse.chars.each_slice(3).map {|s| s.join}.join(',').reverse
end
assert_equal "1", separate_with_comma(1)
assert_equal "10", separate_with_comma(10)
assert_equal "100", separate_with_comma(100)
assert_equal "1,000", separate_with_comma(1000)
assert_equal "10,000", separate_with_comma(10000)
assert_equal "100,000", separate_with_comma(100000)
assert_equal "1,000,000", separate_with_comma(1000000)

The Lambda Lambda Lambda Fraternity

Difficulty:
Easy

Tags:
lambdas, procs, ruby 1.9

Instructions:
Write a proc or lambda that'll take one or two numbers and return true if one or both numbers are even.

Problem and Solution:

# Solution to 'The Lambda Lambda Lambda Fraternity' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/the-lambda-lambda-lambda-fraternity
even_check = -> *args { args.all? &:even? }
assert_equal [[2, 4], [1, 2], [8, 12]].select{|arr| even_check.call(*arr)}, [[2, 4], [8, 12]]
assert_equal even_check.call(42), true
assert_equal [[2, 4], [2, 1], [8, 11]].select{|arr| even_check.call(*arr)}, [[2, 4]]

Each With Object

Difficulty:
Easy

Tags:
ruby 1.9, enumerables

Instructions:
ne of our favorite methods in Ruby 1.9 is each_with_object. It works much like inject. Use each_with_object to return an array containing one reversed string for each string that has an even number of characters.

Problem and Solution:

# Solution to 'Each With Object' on rubeque.com
# by jakthegr8
# http://www.rubeque.com/problems/each-with-object
def even_sum(arr)
arr.each_with_object([]){ |v,a| a << v.reverse if v && (v.size % 2 == 0)}
end
assert_equal even_sum(["cat", "dog", "bird", "fish"]), ["drib", "hsif"]
assert_equal even_sum(["why", "chunky", nil, "lucky", "stiff"]), ["yknuhc"]
assert_equal even_sum(["rewsna", "hitch hiker", "si", "guide", "galaxies ", "24"]), ["answer", "is", "42"]