DEV Community

Cover image for Apple and Orange
Klecianny Melo
Klecianny Melo

Posted on

Apple and Orange

Prepare your favorite cup of coffee, because we are about to enter the fantastic world of Apple and Orange.

The problem

Image description

The solution

Image description

To start developing the solution, the first step is to define the function that will manipulate the input data:

function countApplesAndOranges(s, t, a, b, apples, oranges) {}
Enter fullscreen mode Exit fullscreen mode

Next we will count how many apples fell in Sam's yard. To do this, we will use the filter function on the apples array and we will only consider apples that are at a distance greater than or equal to s (the starting point of Sam's house) and less than or equal to t (the end point of Sam's house). In the end, we will check the size of apples with the length method and store this value in the appleCount constant:

const appleCount = apples.filter(apple => (a + apple >= s && a + apple <= t)).length;
Enter fullscreen mode Exit fullscreen mode

To count the oranges we will follow the same logic, considering the oranges that are at a distance greater than or equal to s and less than or equal to t. After this operation, we will store this value in the constant orangeCount:

const orangeCount = oranges.filter(orange => (b + orange >= s && b + orange <= t)).length;
Enter fullscreen mode Exit fullscreen mode

Now that we have determined the number of apples and oranges that fell in Sam's yard (appleCount and orangeCount), let's display these values in the console:

console.log(appleCount);
console.log(orangeCount);
Enter fullscreen mode Exit fullscreen mode

Final resolution

Image description

After following the step by step we have our final resolution:

// Function that counts how many apples and oranges fell in Sam's yard
function countApplesAndOranges(s, t, a, b, apples, oranges) {
    // Checking how many apples fell in Sam's yard
    const appleCount = apples.filter(apple => (a + apple >= s && a + apple <= t)).length;
    // Checking how many oranges fell into Sam's yard
    const orangeCount = oranges.filter(orange => (b + orange >= s && b + orange <= t)).length;
    // Showing on the console the amount of apples and oranges that fell in Sam's yard
    console.log(appleCount);
    console.log(orangeCount);
}
Enter fullscreen mode Exit fullscreen mode

Share the code, spread knowledge and build the future! 😉

Images generated by DALL·E 3

Top comments (4)

Collapse
 
nik4latic profile image
Anuska Santos

High quality content, thanks for sharing!

Collapse
 
kecbm profile image
Klecianny Melo

Thank you! 😁

Collapse
 
rayanny_bezerra_563386fb7 profile image
Rayanny Bezerra

Sounds great! Thank you very much for sharing this solution 😁

Collapse
 
kecbm profile image
Klecianny Melo

Thank you for your feedback Lala ❤️