📝 Descrição

Sam’s house has an apple tree and an orange tree that yield an abundance of fruit. Using the information given below, determine the number of apples and oranges that land on Sam’s house.

In the diagram below:

The red region denotes the house, where ‘s’ is the start point, and t is the endpoint. The apple tree is to the left of the house, and the orange tree is to its right. Assume the trees are located on a single point, where the apple tree is at point a, and the orange tree is at point b. When a fruit falls from its tree, it lands d units of distance from its tree of origin along the x-axis. _A negative value of d means the fruit fell d units to the tree’s left, and a positive value of d means it falls units to the tree’s right. _

Given the value of d for m apples and n oranges, determine how many apples and oranges will fall on Sam’s house (i.e., in the inclusive range )?

📌 Exemplos

Examplo 1:

A casa de Sam está localizada entre os pontos s=7 e s=10. A macieira está localizada em a=4 e a laranjeira em b=12. Se tivermos m=3 maçãs e n=3 laranjas nas posições apples = [2,3,-4] e oranges = [3,-2,-4] quantas cairão perto da casa sam?

  1. Vetor de posição de maçãs: [4+2, 4+3, 4+(-4)]
  2. Vetor de posição de laranjas: [12+3, 12+(-2), 12+(-4)]
  3. Range: [7, 10]

✅ Casos de teste

Caso 1

Entrada

7 11 5 15 3 2 -2 2 1 5 -6

Saída

1 1

🚀 Como resolvi?

Só precisamos nos atentar que devemos atualizar o vetor de posição da fruta com a posição da árvore. Dessa forma teremos a atual posição de onde o fruto caiu.

Com esse valor em mão verificaremos se a posição atual do fruto está dentro da range fornecida. Caso esteja, contamos.

🛠️ Implementação

def count_fruit(tree_position, initial_range, final_range, fruits):
    return sum(initial_range <= x + tree_position <= final_range for x in fruits)

def count_apples_and_oranges(s, t, a, b, apples, oranges):
    count_apples = count_fruit(a, s, t, apples)
    count_oranges = count_fruit(b, s, t, oranges)

    print(f"{count_apples}\n{count_oranges}")

🧠 O que aprendemos?

Dividir o problema em problema menores sempre nos ajudará.