Решение на Първа задача от Николай Добромиров

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

Към профила на Николай Добромиров

Резултати

  • 5 точки от тестове
  • 0 бонус точки
  • 5 точки общо
  • 15 успешни тест(а)
  • 2 неуспешни тест(а)

Код

class Array
def to_hash()
result = {}
each do |sublist|
result[sublist[0]] = sublist[1] if sublist.length > 0
end
result
end
def index_by()
result = {}
each do |value|
result[ yield value ] = value
end
result
end
def subarray_count(subArray)
result = 0;
return result if length < subArray.length
for index in 0..(length - subArray.length)
result += 1 if slice(index, subArray.length) == subArray
end
result
end
def occurences_count()
result = {}
each do |value|
if result.has_key? value;
result[value] += 1
else
result[value] = 1
end
end
result
end
end

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

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

Failures:

  1) Array#occurences_count returns a hash that defaults to 0 when the key is not present
     Failure/Error: [].occurences_count[:something].should eq 0
       
       expected 0
            got nil
       
       (compared using ==)
     # /tmp/d20111025-2903-msjzz5/spec.rb:74: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)>'

  2) Array#occurences_count returns a hash, that does not change when indexed with a non-occuring element
     Failure/Error: hash['b'].should eq 0
       
       expected 0
            got nil
       
       (compared using ==)
     # /tmp/d20111025-2903-msjzz5/spec.rb:84: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.01392 seconds
17 examples, 2 failures

Failed examples:

rspec /tmp/d20111025-2903-msjzz5/spec.rb:73 # Array#occurences_count returns a hash that defaults to 0 when the key is not present
rspec /tmp/d20111025-2903-msjzz5/spec.rb:81 # Array#occurences_count returns a hash, that does not change when indexed with a non-occuring element

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

Николай обнови решението на 23.10.2011 22:08 (преди около 13 години)

+class Array
+ def to_hash()
+ result = {}
+ each do |sublist|
+ result[sublist[0]] = sublist[1] if sublist.length > 0
+ end
+ result
+ end
+
+ def index_by()
+ result = {}
+ each do |value|
+ result[ yield value ] = value
+ end
+ result
+ end
+
+ def subarray_count(subArray)
+ result = 0;
+ return result if length < subArray.length
+ for index in 0..(length - subArray.length)
+ result += 1 if slice(index, subArray.length) == subArray
+ end
+ result
+ end
+
+ def occurences_count()
+ result = {}
+ each do |value|
+ if result.has_key? value;
+ result[value] += 1
+ else
+ result[value] = 1
+ end
+ end
+ result
+ end
+end