Решение на Първа задача от Здравко Стойчев

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

Към профила на Здравко Стойчев

Резултати

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

Код

class Array
def to_hash
result = {}
self.each { |key, value| result[key] = value}
result
end
def index_by
result = {}
self.each { |element| result[yield(element)] = element }
result
end
def subarray_count(subarray)
result = 0
possible_starts = 0..(self.length - subarray.length)
possible_starts.each { |i| result += 1 if self[i...(i + subarray.length)] == subarray }
result
end
def occurences_count
result = Hash.new { 0 }
self.each { |element| result[element] += 1 }
result
end
end

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

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

Finished in 0.01363 seconds
17 examples, 0 failures

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

Здравко обнови решението на 20.10.2011 21:21 (преди над 12 години)

+class Array
+ def to_hash
+ result = {}
+
+ self.each { |key, value| result[key] = value}
+
+ result
+ end
+
+ def index_by
+ result = {}
+
+ self.each { |element| result[yield(element)] = element }
+
+ result
+ end
+
+ def subarray_count(subarray)
+ result = 0
+
+ possible_starts = 0..(self.length - subarray.length)
+ possible_starts.each { |i| result += 1 if self[i...(i + subarray.length)] == subarray }
+
+ result
+ end
+
+ def occurences_count
+ result = Hash.new { 0 }
+
+ self.each { |element| result[element] += 1 }
+
+ result
+ end
+end
  • Харесва ми, че си се опитал да измислиш добро име и си стигнал до possible_starts.
  • Hash.new { 0 } става, но Hash.new(0) е по-добре.
  • В subarray_count, вместо да имаш temp и да правиш each, можеш да минеш просто с possible_starts.count { |start| self[i..(i + subarray.length)] == subarray }. Виж документацията на #count.
  • self. на всички места е излишен.

Иначе, приятно решение, харесва ми.