Решение на Първа задача от Мария Матева

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

Към профила на Мария Матева

Резултати

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

Код

class Array
def to_hash
Hash[*self.flatten]
end
def index_by
res = {}
if block_given?
self.each do |x|
res[yield(x)] = x
end
end
res
end
def subarray_count(subarray)
count = 0
len = self.length
for i in 0...len
if full_match?(subarray, i)
count += 1
end
end
count
end
def occurences_count
res = Hash.new(0)
self.map { |elem| res[elem] += 1 }
res
end
#as ugly as I could :/
private
def full_match? (arr2, pos)
m = self.length
n = arr2.length
if (n > m - pos)
false
else
for i in 0...n
if self[i + pos] != arr2[i]
return false
end
end
true
end
end
end

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

..F..............

Failures:

  1) Array#to_hash works when the keys and values are arrays
     Failure/Error: [[1, [2, 3]], [[4, 5], 6]].to_hash.should eq(1 => [2, 3], [4, 5] => 6)
       
       expected {1=>[2, 3], [4, 5]=>6}
            got {1=>2, 3=>4, 5=>6}
       
       (compared using ==)
       
       Diff:
       @@ -1,2 +1,2 @@
       -{1=>[2, 3], [4, 5]=>6}
       +{1=>2, 3=>4, 5=>6}
     # /tmp/d20111025-2903-130jker/spec.rb:11:in `block (2 levels) in <top (required)>'
     # ./lib/homework/run_with_timeout.rb:5:in `block (3 levels) in <top (required)>'
     # ./lib/homework/run_with_timeout.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.01502 seconds
17 examples, 1 failure

Failed examples:

rspec /tmp/d20111025-2903-130jker/spec.rb:10 # Array#to_hash works when the keys and values are arrays

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

Мария обнови решението на 24.10.2011 09:36 (преди над 12 години)

+class Array
+
+ def to_hash
+ Hash[*self.flatten]
+ end
+
+
+ def index_by
+ res = {}
+ if block_given?
+ self.each do |x|
+ res[yield(x)] = x
+ end
+ end
+ res
+ end
+
+
+ def subarray_count(subarray)
+ count = 0
+ len = self.length
+ for i in 0...len
+ if full_match?(subarray, i)
+ count += 1
+ end
+ end
+ count
+ end
+
+
+ def occurences_count
+ res = Hash.new(0)
+ self.map { |elem| res[elem] += 1 }
+ res
+ end
+
+ #as ugly as I could :/
+ private
+ def full_match? (arr2, pos)
+ m = self.length
+ n = arr2.length
+ if (n > m - pos)
+ false
+ else
+ for i in 0...n
+ if self[i + pos] != arr2[i]
+ return false
+ end
+ end
+ true
+ end
+ end
+
+end