Таким образом, чтобы подать заявку на роль разработчика программного обеспечения, соискатели должны были написать приложение для решения таких уравнений, как:
- 7x — 2 = 21
- 2(4x + 3) + 6 = 24 — 4x с подробным описанием всех шагов, связанных с оценкой «x».
В моем решении эти уравнения будут упрощены следующим образом:
Для 7x — 2 = 21 решение будет равно:
{
Задача: '7x-2=21',
'Объединение одинаковых членов': '7x=23',
'Найти X': 'x=23/7'
}
а для 2(4x + 3) + 6 = 24–4x решение будет равно:
{
Задача: '2(4x+3)-6=24–4x',
'распределить уравнение': '8x+6–6=24–4x',
'решить уравнение целые числа слева от экватора': '8x=24–4x',
'Объединение одинаковых членов': '8x+4x=24',
'Найти X': 'x=24 /12'
}
Сначала задайте глобальную переменную для хранения конечного объекта result:
let result = {};
Внезапно, глядя на эту проблему, я буду решать ее, используя правило BODMAS, и это будет означать разделение уравнения и решение по частям:
Мы лишаем уравнение всех пробелов,
// remove space character fom string const parts = equation.replace(/\s/g, ""); // Update the result object with the initial problem statement result["Problem"] = parts;
Затем мы определяем логическое значение, чтобы проверить, содержит ли задача набор скобок.
const hasParenthesis = /\(|\)/.test(parts);
Теперь, если hasParenthesis равно true для задачи, которая имеет место для «2(4x+3)-6=24–4x», мы извлекаем скобочную часть уравнения используя простую рекурсивную функцию:
let endPart = ''; let subResult = ''; function getCoeffPart(equation) { let subEquation = ""; // checking to find a closing bracket ")" if (equation[0] === ")") { // if a closing bracket if found, we split the equation and exit subEquation = subEquation + equation[0]; endPart = equation.substring(1); return subEquation; } subEquation = equation[0] + getCoeffPart(equation.substring(1)); return subEquation } // getCoeffPart("2(4x+3)-6=24–4x") will return "2(4x+3)" and set endPart to "-6=24–4x"
Теперь, чтобы упростить скобку («2(4x + 3)») до «8x+6», определив функцию solveBracket:
function solveBracket(equation) { let result; // remove space character fom string const parts = equation.replace(/\s/g, ""); let parenthesis; // recursive function to get the coefficient of the equation function getCoeff(str) { let coeff = ""; if (str[0] === "(") { parenthesis = str.slice(1, -1); return coeff; } coeff = str[0] + getCoeff(str.substring(1)); return coeff; } const coefficient = Number(!getCoeff(parts) ? "1" : getCoeff(parts)); const [term1, variable, operator, term2] = parenthesis.split(""); result = `${coefficient * Number(term1)}${variable}${operator}${ coefficient * Number(term2) }`; return result; } module.exports = solveBracket;
Функция solveBracket подробно описана здесь, чтобы упростить эту статью.
Далее выполняем следующие действия над проблемой:
- решение целых чисел «+6–6», которые вернут ноль и еще больше упростят уравнение до «8x = 24–4x»,
- объединение аналогичного термина приведет к «8x+4x=24»,
- Решение для «x» вернет «12x + 24x», затем «x = 24/12».
if (hasParenthesis) { subResult = solveCoeff(getCoeffPart(parts)) + endPart; result["distribute equation"] = subResult; // get the equation that is at left of the equator operator and right also const leftSide = subResult.substring(0, subResult.indexOf("=")); const leftSideCoeff = subResult.substring(0, subResult.indexOf("x") + 1); const rightSide = subResult.substring(subResult.indexOf("=")); // function to solve for int function getInt(str) { let result = ""; if (str[0] === "x") { result = str.slice(1); return result; } result = getInt(str.slice(1)); return result; } const integerResult = eval(getInt(leftSide)); if (integerResult === 0) { result["solve the integers on the left side of the equator"] = leftSideCoeff + rightSide; // combining like terms result["Combining like terms"] = combineTerms(leftSideCoeff + rightSide); result["Solve for X"] = solveForX( combineTerms(leftSideCoeff + rightSide) ); } else { result["solve the integers on the left side of the equator"] = leftSideCoeff + integerResult + rightSide; // combining like terms result["Combining like terms"] = combineTerms( leftSideCoeff + eval(getInt(leftSide)) + rightSide ); result["Solve for X"] = solveForX( combineTerms(leftSideCoeff + eval(getInt(leftSide)) + rightSide) ); }
CombineTerms иsolveForX — это метод дальнейшего упрощения уравнения следующим образом:
// function to seperate like term in an equation function combineTerms(equation) { let combinedTerms = ""; const seperateEqu = equation.split("="); let left = seperateEqu[0].split(/[+\-]/g); let right = seperateEqu[1].split(/[+\-]/g); // taking the operator on the left side of the equation and converting it let newRightOperator = seperateEqu[0].includes("+") ? "-" : "+"; // taking the operator on the right side of the equation and converting it let newLeftOperator = seperateEqu[1].includes("+") ? "-" : "+"; let leftSide = ""; let rightSide = 0; left.map((variable) => { if (!Number(variable)) { leftSide += variable; } else { rightSide += Number(newRightOperator + variable); } }); right.map((variable) => { if (!Number(variable)) { leftSide += newLeftOperator + variable; } else { rightSide += Number(variable); } }); combinedTerms += `${leftSide}=${rightSide}`; return combinedTerms; } module.exports = combineTerms; // function the would finally solve for x function solveForX(equ) { const equationToSolve = equ.split("=")[0]; const rightSide = equ.split("=")[1]; const operator = equationToSolve.includes("+") ? "+" : "-"; const [num1, num2] = equationToSolve.split(operator); const result = num2 ? Number(num1.slice(0, -1)) + Number(operator + num2.slice(0, -1)) : num1.slice(0, -1); return `x=${rightSide}/${result}`; } module.exports = solveForX;
В противном случае для такой задачи, как задача 1, без круглых скобок, потребуется просто объединить одинаковые термины и решить для «x», например: «7x = 23», чтобы получить «x = 23/7».
// combining like terms result["Combining like terms"] = combineTerms(parts); result["Solve for X"] = solveForX(combineTerms(parts));
Обратите внимание, что вспомогательные функции можно записать в отдельный файл JavaScript и экспортировать для использования в основном файле JavaScript. Это необязательно, но важно для написания более чистого и читаемого кода.
Наконец, наша основная функция или файл будет выглядеть так:
// THIS SCRIPT IS WRITTEN TO SOLVE EQUATIONS THAT RESEMBLES THE PROVIDED USE CASES AND CAN BE IMPROVED IN SO MANY WAYS const solveCoeff = require('./coeff'); const combineTerms = require('./combineTerms'); const solveForX = require('./solveForX') let result = {}; // function to format the initial equation function format(equation) { // remove space character fom string const parts = equation.replace(/\s/g, ""); // Update the result object with the initial problem statement result["Problem"] = parts; let endPart = ""; let subResult = ""; function getCoeffPart(str) { let subEquation = ""; if (str[0] === ")") { subEquation = subEquation + str[0]; endPart = str.substring(1); return subEquation; } subEquation = str[0] + getCoeffPart(str.substring(1)); return subEquation; } const hasParenthesis = /\(|\)/.test(parts); if (hasParenthesis) { subResult = solveCoeff(getCoeffPart(parts)) + endPart; result["distribute equation"] = subResult; // get the equation that is at left of the equator operator and right also const leftSide = subResult.substring(0, subResult.indexOf("=")); const leftSideCoeff = subResult.substring(0, subResult.indexOf("x") + 1); const rightSide = subResult.substring(subResult.indexOf("=")); // function to solve for int function getInt(str) { let result = ""; if (str[0] === "x") { result = str.slice(1); return result; } result = getInt(str.slice(1)); return result; } const integerResult = eval(getInt(leftSide)); if (integerResult === 0) { result["solve the integers on the left side of the equator"] = leftSideCoeff + rightSide; // combining like terms result["Combining like terms"] = combineTerms(leftSideCoeff + rightSide); result["Solve for X"] = solveForX( combineTerms(leftSideCoeff + rightSide) ); } else { result["solve the integers on the left side of the equator"] = leftSideCoeff + integerResult + rightSide; // combining like terms result["Combining like terms"] = combineTerms( leftSideCoeff + eval(getInt(leftSide)) + rightSide ); result["Solve for X"] = solveForX( combineTerms(leftSideCoeff + eval(getInt(leftSide)) + rightSide) ); } } else { // combining like terms result["Combining like terms"] = combineTerms(parts); result["Solve for X"] = solveForX(combineTerms(parts)); } return result; }
Этот репозиторий проектов можно найти здесь. Этот репозиторий полностью с открытым исходным кодом, что означает, что вы можете клонировать, улучшать, вносить свой вклад и использовать кодовую базу по своему усмотрению.
Если вам интересно узнать больше о том, как я создал этот проект, или вы хотите внести свой вклад в его разработку, не стесняйтесь проверить репозиторий и принять участие. Я рад видеть, какие улучшения и идеи вы предлагаете, и я благодарен за любые отзывы, которые вы можете предложить.
Подпишитесь на меня в Твиттере: @allesia_ni
Свяжитесь со мной в LinkedIn: Nonye Ibeanu