Home > katas > Counting sheep... (8kyu) [Ruby]
Counting sheep... (8kyu) [Ruby]
Chek kata on Codewars
Description:
Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).
For example,
[true, true, true, false,
true, true, true, true ,
true, false, true, false,
true, false, false, true ,
true, true, true, true ,
false, false, true, true]
The correct answer would be 17.
Hint: Don't forget to check for bad values like null/undefined
Solution 1
Let's start with loop
solutions.
def countSheeps array
amount = 0
for sheep in array
if (sheep == true)
amount += 1
end
end
return amount
end
Solution 2
Let's solve it with count()
.
def countSheeps array
array.count(true)
end
count()
is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array.
Solution 3
Let's solve it with map()
.
def countSheeps array
array.map{ |sheep| sheep ? sheep : nil }.compact.length
end
map()
is a Array class method which returns a new array containing the values returned by the block.
compact()
is a Array class method which returns the array after removing all the ‘nil’ value elements (if any) from the array.
Solution 4
Let's solve it with select()
.
def countSheeps array
array.select{ |sheep| sheep == true }.length
end
select()
is a Array class method which returns a new array containing all elements of array for which the given block returns a true value.
Solution 5
Let's solve it with reduce()
.
def countSheeps array
array.reduce(0) {|acc, cur| cur.nil? || !cur ? acc : acc + 1}
end