Last active
July 29, 2024 06:12
-
-
Save iigmir/6e8a4e0415b90e9e1be8ae47b7cde05a to your computer and use it in GitHub Desktop.
Math
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const get_all_opreations = (operators = ["+", "-", "*", "/"], length = 3) => | |
| { | |
| const generate_combinations = (current, depth) => | |
| { | |
| if (depth === 0) | |
| { | |
| return [current]; | |
| } | |
| return operators.flatMap(op => generate_combinations([...current, op], depth - 1)); | |
| }; | |
| return generate_combinations([], length); | |
| } | |
| const evaluate_expression = (numbers = [1,1,1,1], operators = ["+", "-", "*", "/"]) => | |
| { | |
| let result = numbers[0]; | |
| for (let i = 0; i < operators.length; i++) | |
| { | |
| const operator = operators[i]; | |
| const number = numbers[i + 1]; | |
| if (operator === "+") result += number; | |
| else if (operator === "-") result -= number; | |
| else if (operator === "*") result *= number; | |
| else if (operator === "/") result /= number; | |
| } | |
| return result; | |
| } | |
| const main = (input = [], target_result = 0) => | |
| { | |
| const opreators = ["+", "-", "*", "/"]; | |
| const all_opreators = get_all_opreations(opreators); | |
| for (let i = 0; i < all_opreators.length; i++) | |
| { | |
| const current_operators = all_opreators[i]; | |
| const result = evaluate_expression(input, current_operators); | |
| if (result === target_result) | |
| { | |
| console.log(i, current_operators); | |
| return current_operators; | |
| } | |
| } | |
| console.log(-1, null); | |
| return null; | |
| }; | |
| const input = [6,6,6,6]; | |
| const result = 0; | |
| main(input, result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment