The3vilM0nk3y

ContractSolver

Apr 17th, 2022 (edited)
1,426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async function HammingEncode(ns, value) {
  2.     await ns.sleep(1000);
  3.   // encoding following Hammings rule
  4.     function HammingSumOfParity(_lengthOfDBits) {
  5.         // will calculate the needed amount of parityBits 'without' the "overall"-Parity (that math took me 4 Days to get it working)
  6.         return _lengthOfDBits < 3 || _lengthOfDBits == 0 // oh and of course using ternary operators, it's a pretty neat function
  7.         ? _lengthOfDBits == 0
  8.             ? 0
  9.             : _lengthOfDBits + 1
  10.         : // the following math will only work, if the length is greater equal 3, otherwise it's "kind of" broken :D
  11.         Math.ceil(Math.log2(_lengthOfDBits * 2)) <=
  12.             Math.ceil(Math.log2(1 + _lengthOfDBits + Math.ceil(Math.log2(_lengthOfDBits))))
  13.         ? Math.ceil(Math.log2(_lengthOfDBits) + 1)
  14.         : Math.ceil(Math.log2(_lengthOfDBits));
  15.     }
  16.     const _data = value.toString(2).split(""); // first, change into binary string, then create array with 1 bit per index
  17.     const _sumParity = HammingSumOfParity(_data.length); // get the sum of needed parity bits (for later use in encoding)
  18.     const count = (arr, val) =>
  19.         arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
  20.     // function count for specific entries in the array, for later use
  21.  
  22.     const _build = ["x", "x", ..._data.splice(0, 1)]; // init the "pre-build"
  23.     for (let i = 2; i < _sumParity; i++) {
  24.         // add new paritybits and the corresponding data bits (pre-building array)
  25.         _build.push("x", ..._data.splice(0, Math.pow(2, i) - 1));
  26.     }
  27.     // now the "calculation"... get the paritybits ('x') working
  28.     for (const index of _build.reduce(function (a, e, i) {
  29.         if (e == "x") a.push(i);
  30.         return a;
  31.     }, [])) {
  32.         // that reduce will result in an array of index numbers where the "x" is placed
  33.         const _tempcount = index + 1; // set the "stepsize" for the parityBit
  34.         const _temparray = []; // temporary array to store the extracted bits
  35.         const _tempdata = [..._build]; // only work with a copy of the _build
  36.         while (_tempdata[index] !== undefined) {
  37.         // as long as there are bits on the starting index, do "cut"
  38.         const _temp = _tempdata.splice(index, _tempcount * 2); // cut stepsize*2 bits, then...
  39.         _temparray.push(..._temp.splice(0, _tempcount)); // ... cut the result again and keep the first half
  40.         }
  41.         _temparray.splice(0, 1); // remove first bit, which is the parity one
  42.         _build[index] = (count(_temparray, "1") % 2).toString(); // count with remainder of 2 and"toString" to store the parityBit
  43.     } // parity done, now the "overall"-parity is set
  44.     _build.unshift((count(_build, "1") % 2).toString()); // has to be done as last element
  45.     return _build.join(""); // return the _build as string
  46. }
  47. async function HammingDecode(ns, _data) {
  48.     await ns.sleep(1000);
  49.     //check for altered bit and decode
  50.     const _build = _data.split(""); // ye, an array for working, again
  51.     const _testArray = []; //for the "truthtable". if any is false, the data has an altered bit, will check for and fix it
  52.     const _sumParity = Math.ceil(Math.log2(_data.length)); // sum of parity for later use
  53.     const count = (arr, val) =>
  54.         arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
  55.     // the count.... again ;)
  56.  
  57.     let _overallParity = _build.splice(0, 1).join(""); // store first index, for checking in next step and fix the _build properly later on
  58.     _testArray.push(_overallParity == (count(_build, "1") % 2).toString() ? true : false); // first check with the overall parity bit
  59.     for (let i = 0; i < _sumParity; i++) {
  60.         // for the rest of the remaining parity bits we also "check"
  61.         const _tempIndex = Math.pow(2, i) - 1; // get the parityBits Index
  62.         const _tempStep = _tempIndex + 1; // set the stepsize
  63.         const _tempData = [..._build]; // get a "copy" of the build-data for working
  64.         const _tempArray = []; // init empty array for "testing"
  65.         while (_tempData[_tempIndex] != undefined) {
  66.         // extract from the copied data until the "starting" index is undefined
  67.             const _temp = [..._tempData.splice(_tempIndex, _tempStep * 2)]; // extract 2*stepsize
  68.             _tempArray.push(..._temp.splice(0, _tempStep)); // and cut again for keeping first half
  69.         }
  70.         const _tempParity = _tempArray.shift(); // and again save the first index separated for checking with the rest of the data
  71.         _testArray.push(_tempParity == (count(_tempArray, "1") % 2).toString() ? true : false);
  72.         // is the _tempParity the calculated data? push answer into the 'truthtable'
  73.     }
  74.     let _fixIndex = 0; // init the "fixing" index and start with 0
  75.     for (let i = 1; i < _sumParity + 1; i++) {
  76.         // simple binary adding for every boolean in the _testArray, starting from 2nd index of it
  77.         _fixIndex += _testArray[i] ? 0 : Math.pow(2, i) / 2;
  78.     }
  79.     _build.unshift(_overallParity); // now we need the "overall" parity back in it's place
  80.     // try fix the actual encoded binary string if there is an error
  81.     if (_fixIndex > 0 && _testArray[0] == false) {
  82.         // if the overall is false and the sum of calculated values is greater equal 0, fix the corresponding hamming-bit
  83.         _build[_fixIndex] = _build[_fixIndex] == "0" ? "1" : "0";
  84.     } else if (_testArray[0] == false) {
  85.         // otherwise, if the the overall_parity is the only wrong, fix that one
  86.         _overallParity = _overallParity == "0" ? "1" : "0";
  87.     } else if (_testArray[0] == true && _testArray.some((truth) => truth == false)) {
  88.         return 0; // uhm, there's some strange going on... 2 bits are altered? How? This should not happen 👀
  89.     }
  90.     // oof.. halfway through... we fixed an possible altered bit, now "extract" the parity-bits from the _build
  91.     for (let i = _sumParity; i >= 0; i--) {
  92.         // start from the last parity down the 2nd index one
  93.         _build.splice(Math.pow(2, i), 1);
  94.     }
  95.     _build.splice(0, 1); // remove the overall parity bit and we have our binary value
  96.     return parseInt(_build.join(""), 2); // parse the integer with redux 2 and we're done!
  97. }
  98. //n[][]
  99. /** @param {NS} ns */
  100.  
  101.  
  102. async function solverWaysToSumII(ns, arrayData) {
  103.     await ns.sleep(1000);
  104.     let n = arrayData[0];
  105.     let s = arrayData[1];
  106.     let ways = [1];
  107.     ways.length = n + 1;
  108.     ways.fill(0,1);
  109.     for (let i = 0; i < s.length; i++) {
  110.         for (let j = s[i]; j <= n; j++) {
  111.           ways[j] += ways[j - s[i]];
  112.         }
  113.     }
  114.     return ways[n];
  115. }
  116.  
  117. async function sanitizeParentheses(ns, input) {
  118.     await ns.sleep(1000);
  119.     var solutions = new Set();
  120.  
  121.     // Returns true and adds to solutions set if a string contains valid parentheses, false otherwise
  122.     var checkValidity = (str) => {
  123.         var nestLevel = 0;
  124.         for (var c of str) {
  125.             if (c == "(") nestLevel++;
  126.             else if (c == ")") nestLevel--;
  127.             if (nestLevel < 0) return false;
  128.         }
  129.  
  130.         if (nestLevel == 0) solutions.add(str);
  131.         return nestLevel == 0;
  132.     };
  133.  
  134.     // Does a breadth first search to check all nodes at the target depth
  135.     var getNodesAtDepth = (str, targetDepth, curDepth = 0) => {
  136.         if (curDepth == targetDepth)
  137.             checkValidity(str);
  138.         else
  139.             for (var i = 0; i < str.length; i++)
  140.                 if (str[i] == "(" || str[i] == ")")
  141.                     getNodesAtDepth(str.slice(0, i) + str.slice(i + 1), targetDepth, curDepth + 1);
  142.     }
  143.  
  144.     // Start from the top level and expand down until we find at least one solution
  145.     var targetDepth = 0;
  146.     while (solutions.size == 0 && targetDepth < input.length - 1) {
  147.         getNodesAtDepth(input, targetDepth++);
  148.     }
  149.  
  150.     // If no solutions were found, return [""]
  151.     if (solutions.size == 0) solutions.add("");
  152.     return `[${[...solutions].join(", ")}]`;
  153. }
  154. let matrix = [];
  155. let start;
  156. let end;
  157. async function solverShortestPath(ns, data){
  158.   await ns.sleep(1000);
  159.   matrix = [...data];
  160.  
  161.   start = [0, 0];
  162.   end = [matrix.length -1, matrix[0].length -1];
  163.    
  164.   let path = await findWay(start, end);
  165.   //await ns.sleep(1000);
  166.   let sPath = "";
  167.   if (path != undefined){
  168.     for (var i=1; i < path.length; i++) {
  169.         sPath += await getDirectionMoved(path[i-1], path[i]);
  170.     }
  171.   }
  172.   return sPath;
  173. }
  174. async function getDirectionMoved(current, newCoord){
  175.     let tCoord = [];
  176.     tCoord[0] = current[0] - newCoord[0];
  177.     tCoord[1] = current[1] - newCoord[1];
  178.     if (tCoord[0] == -1) return "D";
  179.     if (tCoord[0] == 1) return "U";
  180.     if (tCoord[1] == -1) return "R";
  181.     if (tCoord[1] == 1) return "L";
  182. }
  183. async function findWay(position, end){
  184.   var queue = [];
  185.  
  186.   matrix[position[0]][position[1]] = 1;
  187.   queue.push([position]); // store a path, not just a position
  188.  
  189.   while (queue.length > 0) {
  190.     var path = queue.shift(); // get the path out of the queue
  191.     var pos = path[path.length-1]; // ... and then the last position from it
  192.     var direction = [
  193.       [pos[0] + 1, pos[1]],
  194.       [pos[0], pos[1] + 1],
  195.       [pos[0] - 1, pos[1]],
  196.       [pos[0], pos[1] - 1]
  197.     ];
  198.  
  199.     for (var i = 0; i < direction.length; i++) {
  200.       // Perform this check first:
  201.       if (direction[i][0] == end[0] && direction[i][1] == end[1]) {
  202.         // return the path that led to the find
  203.         return path.concat([end]);
  204.       }
  205.      
  206.       if (direction[i][0] < 0 || direction[i][0] >= matrix.length
  207.           || direction[i][1] < 0 || direction[i][1] >= matrix[0].length
  208.           || matrix[direction[i][0]][direction[i][1]] != 0) {
  209.         continue;
  210.       }
  211.  
  212.       matrix[direction[i][0]][direction[i][1]] = 1;
  213.       // extend and push the path on the queue
  214.       queue.push(path.concat([direction[i]]));
  215.     }
  216.   }
  217. }
  218.  
  219.  
  220.  
  221. // autocontract.ns v20190515 by /u/hyperpandiculation
  222.  
  223. async function solverArrayJumpingGame(ns, arrayData) {
  224.     await ns.sleep(1000);
  225.     let arrayJump = [1];
  226.  
  227.     for (let n = 0; n < arrayData.length; n++) {
  228.         if (arrayJump[n]) {
  229.             for (let p = n; p <= Math.min(n + arrayData[n], arrayData.length-1); p++) { // fixed off-by-one error
  230.                 arrayJump[p] = 1;
  231.             }
  232.         }
  233.     }
  234.  
  235.     return 0 + Boolean(arrayJump[arrayData.length - 1]); // thanks /u/Kalumniatoris
  236. }
  237. async function solverArrayJumpingGameII(ns, arrayData){
  238.     await ns.sleep(1000);
  239.     let n = arrayData.length;
  240.     let reach = 0;
  241.     let jumps = 0;
  242.     let lastJump = -1;
  243.     while (reach < n - 1) {
  244.     let jumpedFrom = -1;
  245.     for (let i = reach; i > lastJump; i--) {
  246.         if (i + arrayData[i] > reach) {
  247.         reach = i + arrayData[i];
  248.         jumpedFrom = i;
  249.         }
  250.     }
  251.     if (jumpedFrom === -1) {
  252.         jumps = 0;
  253.         break;
  254.     }
  255.     lastJump = jumpedFrom;
  256.     jumps++;
  257.     }
  258.     return jumps
  259. }
  260. async function solverGenerateIPs(ns, arrayData) {
  261.     await ns.sleep(1000);
  262.     let i, j, k, l;
  263.  
  264.     let arrayDigits = [];
  265.     let arrayDelim = [];
  266.     for (i = 0; i < arrayData.length; i++) {
  267.         arrayDigits[i] = arrayData.substring(i, i + 1);
  268.         arrayDelim[i] = "";
  269.     }
  270.  
  271.     let validCandidates = [];
  272.  
  273.     for (i = 0; i < arrayData.length - 3; i++) {
  274.         for (j = i + 1; j < arrayData.length - 2; j++) {
  275.             for (k = j + 1; k < arrayData.length - 1; k++) {
  276.                 let arrayDelimScratch = JSON.parse(JSON.stringify(arrayDelim));
  277.                 arrayDelimScratch[i] = ".";
  278.                 arrayDelimScratch[j] = ".";
  279.                 arrayDelimScratch[k] = ".";
  280.  
  281.                 let candidateAddress = "";
  282.                 for (l = 0; l < arrayData.length; l++) {
  283.                     candidateAddress = candidateAddress + arrayDigits[l] + arrayDelimScratch[l];
  284.                 }
  285.  
  286.                 let isValid = 1;
  287.                 for (l = 0; l < 4; l++) {
  288.                     let tempOctet = candidateAddress.split(".")[l];
  289.                     if (tempOctet.slice(0, 1) === "0") { isValid = 0; }
  290.                     if (parseInt(tempOctet) > 255) { isValid = 0; }
  291.                 }
  292.                 if (isValid) {
  293.                     validCandidates[validCandidates.length] = candidateAddress;
  294.                 }
  295.             }
  296.         }
  297.     }
  298.  
  299.     let tempStr = JSON.stringify(validCandidates);
  300.     return tempStr.replace(/\"/g, '');
  301. }
  302.  
  303. async function solverLargestPrime(ns, arrayData) {
  304.     await ns.sleep(1000);
  305.     let primeFound = 0;
  306.  
  307.     while (!primeFound) {
  308.         primeFound = 1;
  309.         for (let i = 2; i < Math.sqrt(arrayData); i++) {
  310.             if (!Boolean((arrayData / i) - Math.floor(arrayData / i))) {
  311.                 arrayData = arrayData / i;
  312.                 primeFound = 0;
  313.             }
  314.         }
  315.     }
  316.  
  317.     return arrayData;
  318. }
  319.  
  320. async function solverLargestSubset(ns, arrayData) {
  321.     await ns.sleep(1000);
  322.     let highestSubset = arrayData[0];
  323.  
  324.     for (let i = 0; i < arrayData.length; i++) {
  325.  
  326.         for (let j = i; j < arrayData.length; j++) {
  327.             let tempSubset = 0;
  328.             for (let k = i; k <= j; k++) {
  329.                 tempSubset += arrayData[k];
  330.             }
  331.  
  332.             if (highestSubset < tempSubset) {
  333.                 highestSubset = tempSubset;
  334.             }
  335.         }
  336.     }
  337.  
  338.     return highestSubset;
  339. }
  340.  
  341. async function solverMergeRanges(ns, arrayData) {
  342.     await ns.sleep(1000);
  343.  
  344.     let i, j, k;
  345.     let rangeMax = 0;
  346.     let rangeMin = 999;
  347.     let outputRanges = [];
  348.  
  349.     for (i = 0; i < arrayData.length; i++) {
  350.         rangeMin = Math.min(rangeMin, arrayData[i][0]);
  351.         rangeMax = Math.max(rangeMax, arrayData[i][1]);
  352.     }
  353.  
  354.     let activeRange = 0;
  355.     let startRange, inRange;
  356.  
  357.     for (i = rangeMin; i <= rangeMax + 1; i++) {
  358.         inRange = 0;
  359.  
  360.         for (j = 0; j < arrayData.length; j++) {
  361.             if (i >= arrayData[j][0] && i < arrayData[j][1]) {
  362.                 inRange = 1;
  363.  
  364.                 if (activeRange === 0) {
  365.                     activeRange = 1;
  366.                     startRange = i;
  367.                 }
  368.             }
  369.         }
  370.  
  371.         if (activeRange === 1 && inRange === 0) {
  372.             activeRange = 0;
  373.             outputRanges[outputRanges.length] = [startRange, i];
  374.         }
  375.     }
  376.  
  377.     return JSON.stringify(outputRanges);
  378. }
  379.  
  380. async function solverSpiralizeMatrix(ns, arrayData) {
  381.     await ns.sleep(1000);
  382.     let i, j;
  383.  
  384.     let arrayY = arrayData.length;
  385.     let arrayX = arrayData[0].length;
  386.  
  387.     let loopCount = Math.ceil(arrayX / 2) + 1;
  388.     let marginData = [0, 1, 1, 0];
  389.  
  390.     let resultData = [];
  391.  
  392.     let lastWaypoint = [0, 0];
  393.  
  394.     resultData[0] = arrayData[0][0];
  395.  
  396.     for (i = 0; i < loopCount; i++) {
  397.         if (marginData[0] + marginData[2] <= arrayY && marginData[1] + marginData[3] <= arrayX) {
  398.             for (j = lastWaypoint[1] + 1; j <= arrayX - marginData[1]; j++) {
  399.                 resultData[resultData.length] = arrayData[lastWaypoint[0]][j];
  400.             }
  401.  
  402.             lastWaypoint = [0 + marginData[0], arrayX - marginData[1]];
  403.             marginData[0] += 1;
  404.         }
  405.         if (marginData[0] + marginData[2] <= arrayY && marginData[1] + marginData[3] <= arrayX) {
  406.             for (j = lastWaypoint[0] + 1; j <= arrayY - marginData[2]; j++) {
  407.                 resultData[resultData.length] = arrayData[j][lastWaypoint[1]];
  408.             }
  409.  
  410.             lastWaypoint = [arrayY - marginData[2], arrayX - marginData[1]];
  411.             marginData[1] += 1;
  412.         }
  413.         if (marginData[0] + marginData[2] <= arrayY && marginData[1] + marginData[3] <= arrayX) {
  414.             for (j = lastWaypoint[1] - 1; j >= 0 + marginData[3]; j--) {
  415.                 resultData[resultData.length] = arrayData[lastWaypoint[0]][j];
  416.             }
  417.  
  418.             lastWaypoint = [arrayY - marginData[2], 0 + marginData[3]];
  419.             marginData[2] += 1;
  420.         }
  421.         if (marginData[0] + marginData[2] <= arrayY && marginData[1] + marginData[3] <= arrayX) {
  422.             for (j = lastWaypoint[0] - 1; j >= 0 + marginData[0]; j--) {
  423.                 resultData[resultData.length] = arrayData[j][lastWaypoint[1]];
  424.             }
  425.  
  426.             lastWaypoint = [0 + marginData[0], 0 + marginData[3]];
  427.             marginData[3] += 1;
  428.         }
  429.     }
  430.  
  431.     return JSON.stringify(resultData);
  432.  
  433.  
  434. }
  435.  
  436. async function solverStockTrader(ns, arrayData) {
  437.     await ns.sleep(1000);
  438.    
  439.     let i, j, k;
  440.  
  441.     let tempStr = "[0";
  442.     for (i = 0; i < arrayData[1].length; i++) {
  443.         tempStr += ",0";
  444.     }
  445.     tempStr += "]";
  446.     let tempArr = "[" + tempStr;
  447.     for (i = 0; i < arrayData[0] - 1; i++) {
  448.         tempArr += "," + tempStr;
  449.     }
  450.     tempArr += "]";
  451.  
  452.     let highestProfit = JSON.parse(tempArr);
  453.  
  454.     for (i = 0; i < arrayData[0]; i++) {
  455.         for (j = 0; j < arrayData[1].length; j++) { // Buy / Start
  456.             for (k = j; k < arrayData[1].length; k++) { // Sell / End
  457.                 if (i > 0 && j > 0 && k > 0) {
  458.                     highestProfit[i][k] = Math.max(highestProfit[i][k], highestProfit[i - 1][k], highestProfit[i][k - 1], highestProfit[i - 1][j - 1] + arrayData[1][k] - arrayData[1][j]);
  459.                 } else if (i > 0 && j > 0) {
  460.                     highestProfit[i][k] = Math.max(highestProfit[i][k], highestProfit[i - 1][k], highestProfit[i - 1][j - 1] + arrayData[1][k] - arrayData[1][j]);
  461.                 } else if (i > 0 && k > 0) {
  462.                     highestProfit[i][k] = Math.max(highestProfit[i][k], highestProfit[i - 1][k], highestProfit[i][k - 1], arrayData[1][k] - arrayData[1][j]);
  463.                 } else if (j > 0 && k > 0) {
  464.                     highestProfit[i][k] = Math.max(highestProfit[i][k], highestProfit[i][k - 1], arrayData[1][k] - arrayData[1][j]);
  465.                 } else {
  466.                     highestProfit[i][k] = Math.max(highestProfit[i][k], arrayData[1][k] - arrayData[1][j]);
  467.                 }
  468.             }
  469.         }
  470.     }
  471.     return highestProfit[arrayData[0] - 1][arrayData[1].length - 1];
  472. }
  473.  
  474. async function solverTrianglePath(ns, arrayData) {
  475.     await ns.sleep(1000);
  476.     let i, j;
  477.  
  478.     for (i = 1; i < arrayData.length; i++) {
  479.         for (j = 0; j < arrayData[i].length; j++) {
  480.             arrayData[i][j] += Math.min(arrayData[i - 1][Math.max(0, j - 1)], arrayData[i - 1][Math.min(j, arrayData[i - 1].length - 1)]);
  481.         }
  482.     }
  483.  
  484.     let finalRow = arrayData[arrayData.length - 1];
  485.     let finalMinimum = 999;
  486.     for (i = 0; i < finalRow.length; i++) {
  487.         finalMinimum = Math.min(finalMinimum, finalRow[i]);
  488.     }
  489.  
  490.     return finalMinimum;
  491. }
  492.  
  493. async function solverUniquePaths(ns, arrayData) {
  494.     await ns.sleep(1000);
  495.     //let precalcFactorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000, 6402373705728000, 121645100408832000, 2432902008176640000];
  496.  
  497.     //if (arrayData === undefined || arrayData === null) {
  498.     //    return 1;
  499.     //}
  500.  
  501.     //let factN = precalcFactorial[arrayData[0] + arrayData[1] - 2];
  502.     //let factK = precalcFactorial[arrayData[0] - 1];
  503.     //let factNK = precalcFactorial[arrayData[1] - 1];
  504.     //
  505.  
  506.     let k = arrayData[0] - 1; // k
  507.     let ak = arrayData[1] - 1; // n-k
  508.     let n = k + ak; // n = k + (n-k);
  509.  
  510.     // n choose k = n!/[(k)!(n-k)!] = n! / k! / (n-k)!
  511.  
  512.     let i;
  513.     let factN = 1,
  514.         factAK = 1;
  515.  
  516.     for (i = n; i > k; i--) { // n!/k! = n * n-1 * n-2 ... k+1
  517.         factN = factN * i;
  518.     }
  519.     for (i = ak; i > 1; i--) {
  520.         factAK = factAK * i;
  521.     }
  522.  
  523.     return (factN / factAK);
  524. }
  525.  
  526. async function solverUniquePathsII(ns, arrayData) {
  527.     await ns.sleep(1000);
  528.     let i, j, k;
  529.     let pathsTo = [];
  530.     for (i = 0; i < arrayData.length; i++) {
  531.         pathsTo[i] = [];
  532.         for (j = 0; j < arrayData[0].length; j++) {
  533.             pathsTo[i][j] = 0;
  534.         }
  535.     }
  536.     pathsTo[0][0] = 1;
  537.  
  538.     for (i = 0; i < arrayData.length; i++) {
  539.         for (j = 0; j < arrayData[0].length; j++) {
  540.             if (i > 0 && j > 0 && !arrayData[i][j]) {
  541.                 pathsTo[i][j] = pathsTo[i][j - 1] + pathsTo[i - 1][j];
  542.             } else if (i > 0 && !arrayData[i][j]) {
  543.                 pathsTo[i][j] = pathsTo[i - 1][j];
  544.             } else if (j > 0 && !arrayData[i][j]) {
  545.                 pathsTo[i][j] = pathsTo[i][j - 1];
  546.             } else if (i === 0 && j === 0 && !arrayData[i][j]) {
  547.                 pathsTo[0][0] = 1;
  548.             } else {
  549.                 pathsTo[i][j] = 0;
  550.             }
  551.         }
  552.     }
  553.  
  554.     return pathsTo[pathsTo.length - 1][pathsTo[0].length - 1];
  555. }
  556.  
  557. async function solverWaysToExpress(ns, arrayData) {
  558.     await ns.sleep(1000);
  559.     let i, j, k;
  560.  
  561.     let operatorList = ["", "+", "-", "*"];
  562.     let validExpressions = [];
  563.  
  564.     let tempPermutations = Math.pow(4, (arrayData[0].length - 1));
  565.  
  566.     for (i = 0; i < tempPermutations; i++) {
  567.  
  568.         if (!Boolean(i % 100000)) {
  569.             ns.tprint(i + "/" + tempPermutations + ", " + validExpressions.length + " found.");
  570.             await ns.sleep(100);
  571.         }
  572.  
  573.         let arraySummands = [];
  574.         let candidateExpression = arrayData[0].substr(0, 1);
  575.         arraySummands[0] = parseInt(arrayData[0].substr(0, 1));
  576.  
  577.         for (j = 1; j < arrayData[0].length; j++) {
  578.             candidateExpression += operatorList[(i >> ((j - 1) * 2)) % 4] + arrayData[0].substr(j, 1);
  579.  
  580.             let rollingOperator = operatorList[(i >> ((j - 1) * 2)) % 4];
  581.             let rollingOperand = parseInt(arrayData[0].substr(j, 1));
  582.  
  583.             switch (rollingOperator) {
  584.                 case "":
  585.                     rollingOperand = rollingOperand * (arraySummands[arraySummands.length - 1] / Math.abs(arraySummands[arraySummands.length - 1]));
  586.                     arraySummands[arraySummands.length - 1] = arraySummands[arraySummands.length - 1] * 10 + rollingOperand;
  587.                     break;
  588.                 case "+":
  589.                     arraySummands[arraySummands.length] = rollingOperand;
  590.                     break;
  591.                 case "-":
  592.                     arraySummands[arraySummands.length] = 0 - rollingOperand;
  593.                     break;
  594.                 case "*":
  595.                     while (j < arrayData[0].length - 1 && ((i >> (j * 2)) % 4) === 0) {
  596.                         j += 1;
  597.                         candidateExpression += arrayData[0].substr(j, 1);
  598.                         rollingOperand = rollingOperand * 10 + parseInt(arrayData[0].substr(j, 1));
  599.                     }
  600.                     arraySummands[arraySummands.length - 1] = arraySummands[arraySummands.length - 1] * rollingOperand;
  601.                     break;
  602.             }
  603.         }
  604.  
  605.         let rollingTotal = arraySummands.reduce(function(a, b) { return a + b; });
  606.  
  607.         //if(arrayData[1] == eval(candidateExpression)){
  608.         if (arrayData[1] === rollingTotal) {
  609.             validExpressions[validExpressions.length] = candidateExpression;
  610.         }
  611.     }
  612.  
  613.     return JSON.stringify(validExpressions);
  614. }
  615.  
  616. async function solverWaysToSum(ns, arrayData) {
  617.     await ns.sleep(1000);
  618.     let precalcPartitions = [0, 0, 1, 2, 4, 6, 10, 14, 21, 29, 41, 55, 76, 100, 134, 175, 230, 296, 384, 489, 626, 791, 1001, 1254, 1574, 1957, 2435, 3009, 3717, 4564, 5603, 6841, 8348, 10142, 12309, 14882, 17976, 21636, 26014, 31184, 37337, 44582, 53173, 63260, 75174, 89133, 105557, 124753, 147272, 173524, 204225, 239942, 281588, 329930, 386154, 451275, 526822, 614153, 715219, 831819, 966466, 1121504, 1300155, 1505498, 1741629, 2012557, 2323519, 2679688, 3087734, 3554344, 4087967, 4697204, 5392782, 6185688, 7089499, 8118263, 9289090, 10619862, 12132163, 13848649, 15796475, 18004326, 20506254, 23338468, 26543659, 30167356, 34262961, 38887672, 44108108, 49995924, 56634172, 64112358, 72533806, 82010176, 92669719, 104651418, 118114303, 133230929, 150198135, 169229874, 190569291, 214481125, 241265378, 271248949, 304801364, 342325708, 384276335, 431149388, 483502843, 541946239, 607163745, 679903202, 761002155, 851376627, 952050664, 1064144450, 1188908247, 1327710075, 1482074142, 1653668664, 1844349559, 2056148050, 2291320911, 2552338240, 2841940499, 3163127351, 3519222691, 3913864294, 4351078599, 4835271869, 5371315399, 5964539503, 6620830888, 7346629511, 8149040694, 9035836075, 10015581679, 11097645015, 12292341830, 13610949894, 15065878134, 16670689207, 18440293319, 20390982756, 22540654444, 24908858008, 27517052598, 30388671977, 33549419496, 37027355199];
  619.  
  620.     return precalcPartitions[arrayData];
  621. }
  622. async function solve(inputData, outputData, listFile, listServer, inputType, ns){
  623.     let outputResult = ns.codingcontract.attempt(outputData, listFile, listServer, { returnReward: true});
  624.     ns.tprint([listServer,
  625.             listFile,
  626.             inputType,
  627.             outputData,
  628.             outputResult
  629.         ]);
  630.     if (outputResult == "") {
  631.         ns.tprint("Failed Solving!!!  Data for debug: " + JSON.stringify(inputData), outputData);
  632.     }
  633.        
  634. }
  635. /** @param {NS} ns */
  636. export async function main(ns) {
  637.     let listServers = ["home"];
  638.     let listIndex = 0;
  639.  
  640.     while (listIndex < listServers.length) {
  641.         let listScan = ns.scan(listServers[listIndex], true);
  642.         for (let i = 0; i < listScan.length; i++) {
  643.             if (listServers.indexOf(listScan[i]) === -1) {
  644.                 listServers[listServers.length] = listScan[i];
  645.             }
  646.         }
  647.  
  648.         listIndex += 1;
  649.     }
  650.     ns.tprint("Completed server probe; now solving contracts");
  651.  
  652.     while (true) {
  653.         await ns.sleep(1000);
  654.  
  655.         listIndex = (listIndex + 1) % listServers.length;
  656.  
  657.         let listFiles = ns.ls(listServers[listIndex], ".cct");
  658.  
  659.         for (let z = 0; z < listFiles.length; z++) {
  660.             let inputData = ns.codingcontract.getData(listFiles[z], listServers[listIndex]);
  661.             let inputType = ns.codingcontract.getContractType(listFiles[z], listServers[listIndex]);
  662.             let outputData;
  663.             let outputResult = null;
  664.             switch (inputType) {
  665.                 case "Algorithmic Stock Trader I":
  666.                     if(inputData.length > 1){
  667.                         outputData = await solverStockTrader(ns, [1, inputData]);    
  668.                     } else {
  669.                         outputData = 0;
  670.                     }
  671.                    
  672.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  673.                     break;
  674.                 case "Algorithmic Stock Trader II":
  675.                     if(inputData.length > 1){
  676.                         outputData = await solverStockTrader(ns, [Math.floor(inputData.length / 2), inputData]);
  677.                     } else {
  678.                         outputData = 0;
  679.                     }
  680.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  681.                     break;
  682.                 case "Algorithmic Stock Trader III":
  683.                     if(inputData.length > 1){
  684.                         outputData = await solverStockTrader(ns, [2, inputData]);
  685.                     } else {
  686.                         outputData = 0;
  687.                     }
  688.                    
  689.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  690.                     break;
  691.                 case "Algorithmic Stock Trader IV":
  692.                     outputData = await solverStockTrader(ns, inputData);
  693.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  694.                     break;
  695.                 case "Array Jumping Game":
  696.                     outputData = await solverArrayJumpingGame(ns, inputData);
  697.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  698.                     break;
  699.                 case "Array Jumping Game II":
  700.                     outputData = await solverArrayJumpingGameII(ns, inputData);
  701.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  702.                     break;
  703.                 case "Find All Valid Math Expressions":
  704.                     outputData = await solverWaysToExpress(ns, inputData);
  705.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  706.                     break;
  707.                 case "Find Largest Prime Factor":
  708.                     outputData = await solverLargestPrime(ns, inputData);
  709.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  710.                     break;
  711.                 case "Generate IP Addresses":
  712.                     outputData = await solverGenerateIPs(ns, inputData);
  713.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  714.                     break;
  715.                 case "Merge Overlapping Intervals":
  716.                     outputData = await solverMergeRanges(ns, inputData);
  717.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  718.                     break;
  719.                 case "Minimum Path Sum in a Triangle":
  720.                     outputData = await solverTrianglePath(ns, inputData);
  721.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  722.                     break;
  723.                 case "Spiralize Matrix":
  724.                     outputData = await solverSpiralizeMatrix(ns, inputData);
  725.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  726.                     break;
  727.                 case "Subarray with Maximum Sum":
  728.                     outputData = await solverLargestSubset(ns, inputData);
  729.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  730.                     break;
  731.                 case "Total Ways to Sum":
  732.                     outputData = await solverWaysToSum(ns, inputData);
  733.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  734.                     break;
  735.                 case "Total Ways to Sum II":
  736.                     outputData = await solverWaysToSumII(ns, inputData);
  737.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  738.                     break;
  739.                 case "Unique Paths in a Grid I":
  740.                     outputData = await solverUniquePaths(ns, inputData);
  741.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  742.                     break;
  743.                 case "Unique Paths in a Grid II":
  744.                     outputData = await solverUniquePathsII(ns, inputData);
  745.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  746.                     break;
  747.                 case "Sanitize Parentheses in Expression":
  748.                     outputData = await sanitizeParentheses(ns, inputData);
  749.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  750.                     break;
  751.                 case "HammingCodes: Integer to encoded Binary":
  752.                     outputData = await HammingEncode(ns, inputData);
  753.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  754.                     break;
  755.                 case "HammingCodes: Encoded Binary to Integer":
  756.                     outputData = await HammingDecode(ns, inputData);
  757.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  758.                     break;
  759.                 case "Shortest Path in a Grid":
  760.                     outputData = await solverShortestPath(ns, inputData);
  761.                     await solve(inputData, outputData, listFiles[z], listServers[listIndex], inputType, ns);
  762.                     break;
  763.                 default:
  764.                     ns.tprint([listServers[listIndex],
  765.                         listFiles[z],
  766.                         inputType,
  767.                         "NO SOLVER YET"
  768.                     ]);
  769.                     break;
  770.             }
  771.         }
  772.     }
  773. }
  774. ///Shortest Path in a Grid solverShortestPath
Advertisement
Add Comment
Please, Sign In to add comment