Advertisement
maymunskoa

04. Star Enigma (RegEx)

Mar 19th, 2020
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.   let count = Number(input.shift());
  3.   let regexOne = /[star]/gi;
  4.   let reg = /@(?<name>[a-zA-z]+)[^@\-!:>]*:(?<population>[0-9]*)[^@\-!:>]*!(?<type>[AD])![^@\-!:>]*->(?<soldiers>[0-9]+)/g;
  5.   let attacked = [];
  6.   let destroyed = [];
  7.  
  8.   for (const line of input) {
  9.     let keyMatch = [];
  10.     while ((match = regexOne.exec(line)) !== null) {
  11.       keyMatch.push(match);
  12.     }
  13.     let key = keyMatch.length;
  14.     let decrypted = "";
  15.     for (const letter of line) {
  16.       let newCode = letter.charCodeAt() - key;
  17.       decrypted += String.fromCharCode(newCode);
  18.     }
  19.  
  20.     while ((newmatch = reg.exec(decrypted)) !== null) {
  21.      
  22.       if(newmatch.groups.type === "D"){
  23.         destroyed.push(newmatch.groups.name);
  24.       }else{
  25.         attacked.push(newmatch.groups.name);
  26.       }
  27.     }
  28.   }
  29.  
  30.   console.log(`Attacked planets: ${attacked.length}`);
  31.     if(attacked.length > 0 ){
  32.       attacked.sort((a,b)=>a.localeCompare(b)).forEach(planet=>{
  33.         console.log(`-> ${planet}`);
  34.       })
  35.     }
  36.     console.log(`Destroyed planets: ${destroyed.length}`);
  37.     if(destroyed.length > 0 ){
  38.       destroyed.sort((a,b)=>a.localeCompare(b)).forEach(planet=>{
  39.         console.log(`-> ${planet}`);
  40.       })
  41.     }
  42.  
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement