drkskwlkr icon

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

drkskwlkr | PRO | 12/03/22 04:48:29 PM UTC | 0 ⭐ | 1003 👁️ | Never ⏰ | []
JavaScript |

1.99 KB

|

Source Code

|

0 👍

/

0 👎

function plant (input) {
 
  // Part 1: Fill plant collection
  let plantCount = Number(input.shift()) ;
  let collection = [] ;
  
  for (let c = 0 ; c < plantCount ; c++) {
 
    let output = input.shift().split('<->') ;
 
    let plant    = {} ;
    plant.name   = output[0] ;
    plant.rarity = Number(output[1]) ;
    plant.rating = 0 ;
    plant.votes  = 0 ;
 
    let plantDetails = collection.find(x => x.name === output[0]) ;
    let plantIndex   = collection.indexOf(plantDetails) ;
 
    if ( plantIndex === -1 ) {
      collection.push(plant) ;
    } else {
      collection[plantIndex].rarity = plant.rarity ;
    }
 
  }
 
  // Part 2: Rate/Update/Reset
  let instruction = input.shift() ;
  while (instruction !== 'Exhibition') {
    
    let output = instruction.split(' - ') ;
    let regex = /^(?<command>[A-Z][a-z]+)(: )(?<plant>[A-Z][a-z]+)/ ;
 
    let cmd   = output[0].match(regex).groups['command'] ;
    let plant = output[0].match(regex).groups['plant'] ;
    
    let value = 0 ;
 
    if (cmd !== 'Reset') {
      value = Number(output[1]) ;
    }
 
    let plantDetails = collection.find(x => x.name === plant) ;
    let plantIndex   = collection.indexOf(plantDetails) ;
 
    switch (cmd) {
 
      case 'Rate' : {
        collection[plantIndex].rating += value ;
        collection[plantIndex].votes++ ;
        break ;
      }
 
      case 'Update' : {
        collection[plantIndex].rarity = value ;
        break ;
      }
 
      case 'Reset' : {
        collection[plantIndex].rating = 0 ;
        collection[plantIndex].votes  = 0 ;
        break ;
      }
 
    }
    
    instruction = input.shift() ;
  }
  
  // Part 3: Exhibit Collection
  console.log('Plants for the exhibition:')
 
  for (let plant of collection) {
    let avgRating = plant.rating ;
    
    if (plant.votes > 0) {
      avgRating /= plant.votes ;
    }
 
    console.log(`- ${plant.name}; Rarity: ${plant.rarity}; Rating: ${avgRating.toFixed(2)}`) ;
  }
 
}

Comments