Advertisement
ricardovaltierra

Defuse the Bomb

Feb 15th, 2021
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * @param {number[]} code
  3.  * @param {number} k
  4.  * @return {number[]}
  5.  */
  6. const decrypt = (code, k) => {
  7.     let result = [];
  8.  
  9.     if (k == 0) {
  10.       result = code.fill(0);
  11.     }
  12.     else if (k < 0) {
  13.       let kAbs = Math.abs(k);
  14.       for (let i = 0; i < code.length; i += 1) {
  15.         let j = i,
  16.             kTemp = kAbs,
  17.             tempSum = 0;
  18.         while (kTemp > 0) {
  19.           j -= 1;
  20.           tempSum += j >= 0 ? code[j] : code[code.length + j];
  21.           kTemp -= 1;
  22.         }
  23.         result.push(tempSum);
  24.       }
  25.     }
  26.     else {
  27.       let kAbs = Math.abs(k);
  28.       for (let i = 0; i < code.length; i += 1) {
  29.         let j = i,
  30.             kTemp = kAbs,
  31.             tempSum = 0;
  32.         while (kTemp > 0) {
  33.           j += 1;
  34.           tempSum += j < code.length ? code[j] : code[j - code.length];
  35.           kTemp -= 1;
  36.         }
  37.         result.push(tempSum);
  38.       }
  39.     }
  40.   return result;
  41. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement