Prepare your favorite cup of coffee, because we are about to enter the fantastic world of Apple and Orange.
The problem
The solution
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) {}
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;
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;
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);
Final resolution
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);
}
Share the code, spread knowledge and build the future! 😉
Images generated by DALL·E 3