Codewars Kata - Compare within margin.java
Create a function close_compare that accepts 3 parameters: a, b, and an optional margin. The function should return whether a is lower than, close to, or higher than b.
Please note the following:
- When a is close to b, return 0.
- For this challenge, a is considered "close to" b if margin is greater than or equal to the absolute distance between a and b.
Otherwise...
- When a is less than b, return -1.
- When a is greater than b, return 1.
If margin is not given, treat it as if it were zero.
Assume: margin >= 0
Tip: Some languages have a way to make parameters optional.
Example 1
If a = 3, b = 5, and margin = 3, then close_compare(a, b, margin) should return 0.
This is because a and b are no more than 3 numbers apart.
Example 2
If a = 3, b = 5, and margin = 0, then close_compare(a, b, margin) should return -1.
This is because the distance between a and b is greater than 0, and a is less than b.
public class Solution
{
public static int closeCompare
( double a, double b )
{
return closeCompare( a, b, 0 );
}
public static int closeCompare
( double a, double b, double margin )
{
double d = a - b;
if ( Math.abs( d ) <= margin )
{
return 0;
}
else
{
if ( d > 0 )
{
return 1;
}
else
{
return -1;
}
}
}
}
Leave Codewars Kata - Compare within margin.java to:
Read more #coding posts
Best Posts From Lochard
We have not curated any of lochard's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From Lochard
- King's Cross - 45th month of persecution by CCP, LT &UK
- 43rd month, belongings stolen
- Another round of strong damage
- 41st month of humiliation, torture and other crimes
- This is not a prank
- How sick one has to be to take pleasure in drugging and indirectly molesting others?
- Has AI already surpassed humans in morality and emotion?
- Just a reminder that your fellow biped had been treated as non-human for 39 months
- Psychopathy (Chat with AI)
- [Solved] Oracle Linux 10 WiFi adpator not found