Решение на Първа задача от Виктор Хаджипопов

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

Към профила на Виктор Хаджипопов

Резултати

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

Код

class Array
def to_hash
inject({}) { |hash, list| hash[list[0]] = list[1]; hash }
end
def index_by
inject({}) { |hash, element| hash[yield(element)] = element; hash }
end
def subarray_count(subarray)
result = 0
for i in 0...size
fail = 0
for j in 0...subarray.size
unless self[i+j] == subarray[j]
fail = 1
end
end
unless fail == 1
result += 1
end
end
result
end
def occurences_count
inject(Hash.new(0)) { |hash, element| hash[element] += 1; hash}
end
end
[[:one, 1], [:two, 2]].to_hash # {one: 1, two: 2}
[[1, 2], [3, 4]].to_hash # {1 => 2, 3 => 4}
[[1, 2], [1, 3]].to_hash # {1 => 3}
[].to_hash # {}

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

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

Finished in 0.01566 seconds
17 examples, 0 failures

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

Виктор обнови решението на 24.10.2011 12:56 (преди над 12 години)

+class Array
+
+ def to_hash
+ inject({}) { |hash, list| hash[list[0]] = list[1]; hash }
+ end
+
+ def index_by
+ inject({}) { |hash, element| hash[yield(element)] = element; hash }
+ end
+
+ def subarray_count(subarray)
+ result = 0
+ for i in 0...size
+ fail = 0
+ for j in 0...subarray.size
+ unless self[i+j] == subarray[j]
+ fail = 1
+ end
+ end
+ unless fail == 1
+ result += 1
+ end
+ end
+ result
+ end
+
+ def occurences_count
+ inject(Hash.new(0)) { |hash, element| hash[element] += 1; hash}
+ end
+
+end
+
+[[:one, 1], [:two, 2]].to_hash # {one: 1, two: 2}
+[[1, 2], [3, 4]].to_hash # {1 => 2, 3 => 4}
+[[1, 2], [1, 3]].to_hash # {1 => 3}
+[].to_hash # {}