Решение на Първа задача от Николай Константинов

Обратно към всички решения

Към профила на Николай Константинов

Резултати

  • 6 точки от тестове
  • 0 бонус точки
  • 6 точки общо
  • 17 успешни тест(а)
  • 0 неуспешни тест(а)

Код

class Array
def to_hash()
hash = {}
self.each do |array_element|
if hash.keys.include?(array_element[0])
hash[array_element[0]] = array_element[1]
else
hash[array_element[0]] = array_element[1]
end
end
hash
end
def index_by()
hash = {}
self.each { |array_element| hash[yield(array_element)] = array_element }
hash
end
def subarray_count(subarray)
if subarray == []
raise ArgumentError, "subarray cannot be []"
elsif self.size < subarray.size
return 0
elsif self == subarray
return 1
else
founded_subarrays = 0
self.size.times do |index|
sliced_array = self[index, subarray.size]
break if sliced_array.size < subarray.size
founded_subarrays += 1 if sliced_array == subarray
end
founded_subarrays
end
end
def occurences_count()
hash_with_occurences_count = Hash.new(0)
self.each do |key|
if hash_with_occurences_count.keys.include?(key)
hash_with_occurences_count[key] += 1
else
hash_with_occurences_count[key] = 1
end
end
hash_with_occurences_count
end
end

Лог от изпълнението

.................

Finished in 0.01497 seconds
17 examples, 0 failures

История (1 версия и 0 коментара)

Николай обнови решението на 23.10.2011 22:03 (преди над 12 години)

+class Array
+ def to_hash()
+ hash = {}
+ self.each do |array_element|
+ if hash.keys.include?(array_element[0])
+ hash[array_element[0]] = array_element[1]
+ else
+ hash[array_element[0]] = array_element[1]
+ end
+ end
+ hash
+ end
+
+ def index_by()
+ hash = {}
+ self.each { |array_element| hash[yield(array_element)] = array_element }
+ hash
+ end
+
+ def subarray_count(subarray)
+ if subarray == []
+ raise ArgumentError, "subarray cannot be []"
+ elsif self.size < subarray.size
+ return 0
+ elsif self == subarray
+ return 1
+ else
+ founded_subarrays = 0
+ self.size.times do |index|
+ sliced_array = self[index, subarray.size]
+ break if sliced_array.size < subarray.size
+ founded_subarrays += 1 if sliced_array == subarray
+ end
+ founded_subarrays
+ end
+ end
+
+ def occurences_count()
+ hash_with_occurences_count = Hash.new(0)
+ self.each do |key|
+ if hash_with_occurences_count.keys.include?(key)
+ hash_with_occurences_count[key] += 1
+ else
+ hash_with_occurences_count[key] = 1
+ end
+ end
+ hash_with_occurences_count
+ end
+end