krasizorbov

Star Enigma

Aug 3rd, 2020
1,566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.   let pattern = /[star]/gim;
  3.   let messages = Number(input.shift());
  4.   let decryptedMessages = [];
  5.   for (let i = 0; i < messages; i++) {
  6.     let message = input.shift();
  7.     let match = message.match(pattern);
  8.     if (match) {
  9.       let countSymbols = match.length;
  10.       let decryptedMessage = [];
  11.  
  12.       for (let i = 0; i < message.length; i++) {
  13.         let symbolIndex = message[i].charCodeAt(0);
  14.         let newSymbolIndex = symbolIndex - countSymbols;
  15.         let newSymbol = String.fromCharCode(newSymbolIndex);
  16.  
  17.         decryptedMessage.push(newSymbol);
  18.       }
  19.       decryptedMessages.push(decryptedMessage.join(""));
  20.     } else {
  21.       let countSymbols = 0;
  22.       let decryptedMessage = [];
  23.  
  24.       for (let i = 0; i < message.length; i++) {
  25.         let symbolIndex = message[i].charCodeAt(0);
  26.         let newSymbolIndex = symbolIndex - countSymbols;
  27.         let newSymbol = String.fromCharCode(newSymbolIndex);
  28.  
  29.         decryptedMessage.push(newSymbol);
  30.       }
  31.       decryptedMessages.push(decryptedMessage.join(""));
  32.     }
  33.   }
  34.  
  35.   let atackedPlanets = [];
  36.   let destroyedPlanets = [];
  37.  
  38.   for (let item of decryptedMessages) {
  39.     let patternTwo = /@(?<name>[A-Za-z]+)[^@\-!:>]*:(?<population>[0-9]+)[^@\-!:>]*![^@\-!:>]*(?<attackType>[A|D])![^@\-!:>]*\->(?<soldierCount>[0-9]+)/;
  40.     let match = patternTwo.exec(item);
  41.     if (match && match.groups.attackType === "A") {
  42.       atackedPlanets.push(match.groups.name);
  43.     } else if (match && match.groups.attackType === "D") {
  44.       destroyedPlanets.push(match.groups.name);
  45.     }
  46.   }
  47.  
  48.   let sortedAttackedPlanets = atackedPlanets.sort((a, b) => a.localeCompare(b));
  49.   let sortedDestroyedPlanets = destroyedPlanets.sort((a, b) =>
  50.     a.localeCompare(b)
  51.   );
  52.  
  53.   if (sortedAttackedPlanets.length > 0) {
  54.     console.log(`Attacked planets: ${sortedAttackedPlanets.length}`);
  55.     for (let planet of sortedAttackedPlanets) {
  56.       console.log(`-> ${planet}`);
  57.     }
  58.   } else {
  59.     console.log(`Attacked planets: 0`);
  60.   }
  61.  
  62.   if (sortedDestroyedPlanets.length > 0) {
  63.     console.log(`Destroyed planets: ${sortedDestroyedPlanets.length}`);
  64.     for (let planet of sortedDestroyedPlanets) {
  65.       console.log(`-> ${planet}`);
  66.     }
  67.   } else {
  68.     console.log(`Destroyed planets: 0`);
  69.   }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment