Решение на Първа задача от Ивайло Петров

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

Към профила на Ивайло Петров

Резултати

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

Код

class Array
def to_hash()
res = {}
each { |pair| res[pair[0]] = pair[1] }
res
end
def index_by()
(map { |x| [(yield x), x] }).to_hash
end
def subarray_count(sub_array)
if size >= sub_array.size
# We take from the start the length of sub_array number of elements
# we want somehow if they are equal to our sub_array to return 1,
# otherwise to return 0. Maybe we do this in a bad way, still it is
# short and understandable.
# Other way to do this is by 1 - (array1 <=> array2).abs, however
# I don't think that the second way is more intuitive
([take(sub_array.size)].count(sub_array) + self[1..-1].subarray_count(sub_array))
else
0
end
end
def occurences_count()
counts = uniq.map { |a| [a, count(a)] }
Hash.new(0).merge(counts.to_hash)
end
end

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

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

Finished in 0.01492 seconds
17 examples, 0 failures

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

Ивайло обнови решението на 23.10.2011 23:02 (преди над 12 години)

+class Array
+ def to_hash()
+ res = {}
+ each { |pair| res[pair[0]] = pair[1] }
+ res
+ end
+
+ def index_by()
+ (map { |x| [(yield x), x] }).to_hash
+ end
+
+ def subarray_count(sub_array)
+ if size >= sub_array.size
+ # We take from the start the length of sub_array number of elements
+ # we want somehow if they are equal to our sub_array to return 1,
+ # otherwise to return 0. Maybe we do this in a bad way, still it is
+ # short and understandable.
+ # Other way to do this is by 1 - (array1 <=> array2).abs, however
+ # I don't think that the second way is more intuitive
+ ([take(sub_array.size)].count(sub_array) + self[1..-1].subarray_count(sub_array))
+ else
+ 0
+ end
+ end
+
+ def occurences_count()
+ counts = uniq.map { |a| [a, count(a)] }
+ Hash.new(0).merge(counts.to_hash)
+ end
+end