Advertisement
drkskwlkr

Plant Discovery (https://judge.softuni.org/Contests/Practice/Index/2518#2)

Dec 3rd, 2022
619
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.99 KB | Source Code | 0 0
  1. function plant (input) {
  2.  
  3.   // Part 1: Fill plant collection
  4.   let plantCount = Number(input.shift()) ;
  5.   let collection = [] ;
  6.  
  7.   for (let c = 0 ; c < plantCount ; c++) {
  8.  
  9.     let output = input.shift().split('<->') ;
  10.  
  11.     let plant    = {} ;
  12.     plant.name   = output[0] ;
  13.     plant.rarity = Number(output[1]) ;
  14.     plant.rating = 0 ;
  15.     plant.votes  = 0 ;
  16.  
  17.     let plantDetails = collection.find(x => x.name === output[0]) ;
  18.     let plantIndex   = collection.indexOf(plantDetails) ;
  19.  
  20.     if ( plantIndex === -1 ) {
  21.       collection.push(plant) ;
  22.     } else {
  23.       collection[plantIndex].rarity = plant.rarity ;
  24.     }
  25.  
  26.   }
  27.  
  28.   // Part 2: Rate/Update/Reset
  29.   let instruction = input.shift() ;
  30.   while (instruction !== 'Exhibition') {
  31.    
  32.     let output = instruction.split(' - ') ;
  33.     let regex = /^(?<command>[A-Z][a-z]+)(: )(?<plant>[A-Z][a-z]+)/ ;
  34.  
  35.     let cmd   = output[0].match(regex).groups['command'] ;
  36.     let plant = output[0].match(regex).groups['plant'] ;
  37.    
  38.     let value = 0 ;
  39.  
  40.     if (cmd !== 'Reset') {
  41.       value = Number(output[1]) ;
  42.     }
  43.  
  44.     let plantDetails = collection.find(x => x.name === plant) ;
  45.     let plantIndex   = collection.indexOf(plantDetails) ;
  46.  
  47.     switch (cmd) {
  48.  
  49.       case 'Rate' : {
  50.         collection[plantIndex].rating += value ;
  51.         collection[plantIndex].votes++ ;
  52.         break ;
  53.       }
  54.  
  55.       case 'Update' : {
  56.         collection[plantIndex].rarity = value ;
  57.         break ;
  58.       }
  59.  
  60.       case 'Reset' : {
  61.         collection[plantIndex].rating = 0 ;
  62.         collection[plantIndex].votes  = 0 ;
  63.         break ;
  64.       }
  65.  
  66.     }
  67.    
  68.     instruction = input.shift() ;
  69.   }
  70.  
  71.   // Part 3: Exhibit Collection
  72.   console.log('Plants for the exhibition:')
  73.  
  74.   for (let plant of collection) {
  75.     let avgRating = plant.rating ;
  76.    
  77.     if (plant.votes > 0) {
  78.       avgRating /= plant.votes ;
  79.     }
  80.  
  81.     console.log(`- ${plant.name}; Rarity: ${plant.rarity}; Rating: ${avgRating.toFixed(2)}`) ;
  82.   }
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement