Skip to content

Instantly share code, notes, and snippets.

@iigmir
Last active July 29, 2024 06:12
Show Gist options
  • Select an option

  • Save iigmir/6e8a4e0415b90e9e1be8ae47b7cde05a to your computer and use it in GitHub Desktop.

Select an option

Save iigmir/6e8a4e0415b90e9e1be8ae47b7cde05a to your computer and use it in GitHub Desktop.
Math
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