Advertisement
Lulunga

04. Star Enigma regex

Jul 26th, 2019
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arr) {
  2.     let n = arr.shift();//n – the number of messages
  3.     arr = arr.slice(0, n);
  4.     let attackedPlanets = [];
  5.     let destroyedPlanets = [];
  6.  
  7.     arr.forEach(line => {
  8.  
  9.         let decryptionKey = line.match(/[s, t, a, r]/gi).length;
  10.         line = line.split('').map(e => String.fromCharCode((e.charCodeAt(0) - decryptionKey))).join('');
  11.         let pattern = /[^@!:>-]*@(?<planet>[A-Za-z]+)[^@!:>-]*:(?<population>[0-9]+)[^@!:>-]*!(?<attackType>[AD])![^@!:>-]*->(?<soldierCount>[0-9]+)/gm;
  12.         let result = pattern.exec(line);
  13.         if (result) {
  14.             let attackType = result.groups.attackType;
  15.             if (attackType === 'A') {
  16.                 attackedPlanets.push(result.groups.planet);
  17.             } else if (attackType === 'D') {
  18.                 destroyedPlanets.push(result.groups.planet);
  19.             }
  20.         }
  21.  
  22.     });
  23.  
  24.     attackedPlanets.sort((a, b) => a.localeCompare(b));
  25.     destroyedPlanets.sort((a, b) => a.localeCompare(b));
  26.  
  27.     console.log(`Attacked planets: ${attackedPlanets.length}`);
  28.     if (attackedPlanets.length !== 0) {
  29.         for (let planet of attackedPlanets) {
  30.             console.log(`-> ${planet}`);
  31.         }
  32.     }
  33.     console.log(`Destroyed planets: ${destroyedPlanets.length}`);
  34.     if (destroyedPlanets.length !== 0) {
  35.         for (let planet of destroyedPlanets) {
  36.             console.log(`-> ${planet}`);
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement