Resolviendo el reto/Solving Challenge

in HiveDevs2 months ago (edited)

versión español

This is a series of posts focused on solving the daily challenges of the user @ydavgonzalez step by step and teaching the programming approach.

challenge link

Today we are going to solve a classic math problem using programming. Get ready to put your knowledge into practice!

Problem: Maria has a basket with apples and pears. In total there are 72 fruits in the basket. If the number of pears is double that of apples, how many apples and how many pears are in the basket?

Solution:

  1. Definition of variables:
  • apples = number of apples.
  • pears = number of pears.
  1. Statement of equations:
  • apples + pears = 72 (The sum of apples and pears is 72)
    pears = 2 apples (The number of pears is double that of apples)
  1. Resolution of the system of equations:
    We substitute the second equation into the first one: apples + 2 apples = 72
    We simplify: 3 apples = 72
  • We solve for apples: apples = 72 / 3 = 24
    We substitute the value of apples in the second equation: pears = 2 24 = 48

Conclusion: Maria has 24 apples and 48 pears in her basket.

#JavaScript

// We define the variables
var apples = 0;
var pears = 0;

// Equations of the system
//equation1 = apples + pears = 72;
//equation2 = pears = 2 * apples;

// We solve by substitution
// We clear 'pears' from equation 2
//pears = 2 * apples;

// We substitute 'pears' in equation 1
//apples + (2 * apples) = 72;

// We solve for 'apples'
apples = 72 / 3;

// We substitute 'apples' in equation 2 to get 'pears'
pears = 2 * apples;

// We show the result
console.log("There are", apples, "apples and", pears, "pears in the basket.");