Guest User

Untitled

a guest
May 8th, 2015
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const problem5 = () => {
  2.     // The possible symbols that can be inserted between digits
  3.     const JOIN = 0; // insert nothing
  4.     const ADD  = 1; // insert +
  5.     const SUB  = 2; // insert -
  6.    
  7.     // One way of inserting the symbols is represented as a number
  8.     // whose base three digits represent each symbol.
  9.     // The first symbol to be inserted is the least significant
  10.     // base-3 digit, etc.
  11.     // eg.  s=00120121 base 3  is  1+2-3+45-6+789
  12.    
  13.     // Computes the value of the expression where the given
  14.     // symbols are inserted between the digits 1-9.
  15.     const evaluate = (s) => {
  16.         // ex:
  17.         //   s = ??021210 base 3
  18.         //          sign___        ___symbol
  19.         //                 \      /
  20.         //   12 + 3 - 4 + 5 - 67 ? 8 ? 9
  21.         //   \____________/   \|    \__digit
  22.         //        sum          \__num
  23.         let sum = 0;
  24.         let sign = +1;
  25.         let num = 1;
  26.         for (let digit = 2; digit <= 9; digit++) {
  27.             const symbol = s % 3;
  28.             s = (s / 3)|0;
  29.             if (symbol === JOIN) {
  30.                 num = 10*num + digit;
  31.             } else {
  32.                 sum += sign*num;
  33.                 sign = (symbol === ADD ? +1 : -1);
  34.                 num = digit;
  35.             }
  36.         }
  37.         sum += sign*num;
  38.         return sum;
  39.     }
  40.     // Print the digits 1-9, with the given symbols inserted,
  41.     // to a string.
  42.     const show = (s) => {
  43.         let res = "1";
  44.         for (let digit = 2; digit <= 9; digit++) {
  45.             const symbol = s % 3;
  46.             s = (s / 3)|0;
  47.             if (symbol === ADD)
  48.                 res += " + ";
  49.             else if (symbol === SUB)
  50.                 res += " - ";
  51.             res += digit;
  52.         }
  53.         return res;
  54.     }
  55.    
  56.     for (let s = 0; s !== Math.pow(3,8); s++)
  57.         if (evaluate(s) === 100)
  58.             console.log(show(s) + " = 100");
  59. }
Advertisement
Add Comment
Please, Sign In to add comment