Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const problem5 = () => {
- // The possible symbols that can be inserted between digits
- const JOIN = 0; // insert nothing
- const ADD = 1; // insert +
- const SUB = 2; // insert -
- // One way of inserting the symbols is represented as a number
- // whose base three digits represent each symbol.
- // The first symbol to be inserted is the least significant
- // base-3 digit, etc.
- // eg. s=00120121 base 3 is 1+2-3+45-6+789
- // Computes the value of the expression where the given
- // symbols are inserted between the digits 1-9.
- const evaluate = (s) => {
- // ex:
- // s = ??021210 base 3
- // sign___ ___symbol
- // \ /
- // 12 + 3 - 4 + 5 - 67 ? 8 ? 9
- // \____________/ \| \__digit
- // sum \__num
- let sum = 0;
- let sign = +1;
- let num = 1;
- for (let digit = 2; digit <= 9; digit++) {
- const symbol = s % 3;
- s = (s / 3)|0;
- if (symbol === JOIN) {
- num = 10*num + digit;
- } else {
- sum += sign*num;
- sign = (symbol === ADD ? +1 : -1);
- num = digit;
- }
- }
- sum += sign*num;
- return sum;
- }
- // Print the digits 1-9, with the given symbols inserted,
- // to a string.
- const show = (s) => {
- let res = "1";
- for (let digit = 2; digit <= 9; digit++) {
- const symbol = s % 3;
- s = (s / 3)|0;
- if (symbol === ADD)
- res += " + ";
- else if (symbol === SUB)
- res += " - ";
- res += digit;
- }
- return res;
- }
- for (let s = 0; s !== Math.pow(3,8); s++)
- if (evaluate(s) === 100)
- console.log(show(s) + " = 100");
- }
Advertisement
Add Comment
Please, Sign In to add comment