Question
Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love.
Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren’t.
My thought process
-
I want the solution to be very simple, probably one line, that seems to be possible since I can already imagine using modulo or some technique that organises even and odd numbers
-
A step further is to think of how even and odd numbers bouce off each other, a list of the behaviours include;
-
The sum of two even numbers is an even number.
-
The sum of two odd numbers is an even number.
-
The sum of even and an odd number is an odd number.
-
Even number is divisible by 2, and leaves the remainder 0.
The last two are the most important to our solution.https://bigmachine.io/theory/mod-and-remainder-are-not-the-same
- Our soltution should also handle negative numbers, its important to be careful how to use
mod
andremainder
Test suite
describe "Basic Tests" do
it "should pass basic tests" do
Test.assert_equals(lovefunc(1,-4), true)
Test.assert_equals(lovefunc(2,-2), false)
Test.assert_equals(lovefunc(0,1), true)
Test.assert_equals(lovefunc(0,0), false)
Test.assert_equals(lovefunc(5,5), false)
end
end
Solution
def lovefunc( flower1, flower2 )
(flower1 + flower2) % 2 != 0
end
Other solutions I like:
def lovefunc(*all_flowers)
all_flowers.sum.odd?
end
We are using the parameter behaviour of the language itself here.
.odd?
can replace the % 2 != 0
section of my code as so
def lovefunc( flower1, flower2)
(flower1 + flower2).odd?
end
This was my first solution but I did not want to use a language specific method