Guest User

findServer.js

a guest
Jul 27th, 2022
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /** @param {NS} ns */
  2. export async function main(ns) {
  3.     ns.tprint(connectCommandToServer(findPathToServer(ns, "home", ns.args[0])));
  4. }
  5.  
  6. /**
  7.  * returns an array containing all servers between currentServer and the target
  8.  */
  9. export function findPathToServer(ns, currentServer, target, previousServer) {
  10.  
  11.     //if we were asked to find the server we're currently on, we're done.
  12.     //Return an array with just that.
  13.     if (currentServer == target) {
  14.         return [currentServer];
  15.     }
  16.  
  17.     //otherwise, see if the target is connected to one of our neighbors
  18.     let neighbors = ns.scan(currentServer);
  19.     for (var i = 0; i < neighbors.length; i++) {
  20.         var neighbor = neighbors[i];
  21.  
  22.         //ignore any server we just visited, we don't want to go backwards
  23.         //I don't think scan returns currentServer, but in case it does, treat it the same as the previous server
  24.         if (neighbor == previousServer || neighbor == currentServer) {
  25.             continue;
  26.         }
  27.  
  28.         //recursively call findserver using neighbor as our new currentServer (and currentServer is our new previousServer)
  29.         //Basically, check if our target is down this path
  30.         let findResult = findPathToServer(ns, neighbor, target, currentServer);
  31.  
  32.         //if we got an actual answer back, create an array starting at currentServer followed by the findResult(s)
  33.         //This will collapse the recursion into an array of all connections from home to target
  34.         if (findResult != null) {
  35.             var newResult = [currentServer].concat(findResult)
  36.             return newResult;
  37.         }
  38.  
  39.     }
  40.  
  41.     //If we get here, we didn't find our target connected to any of these neighbors.
  42.     //The target must've been down a different branch
  43.     return null;
  44. }
  45.  
  46. /**
  47.  * Given an array of servers, make a copy-pasteable command that will chain terminal "connect" commands from first to last.
  48.  * Useful for making things like commands that can take you from home to CSEC (and other faction-related servers).
  49.  */
  50. export function connectCommandToServer(pathArray) {
  51.     var connectCommand = "";
  52.     for (var i = 0; i < pathArray.length; i++) {
  53.         if (pathArray[i] != "home") {
  54.             connectCommand += "connect "
  55.         }
  56.         connectCommand += pathArray[i] + ";"
  57.     }
  58.     return connectCommand;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment