Ивайло обнови решението на 23.10.2011 23:02 (преди около 13 години)
+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