Advertisement
pacho_the_python

Untitled

Apr 20th, 2023
573
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function horse_racing(data) {
  2.     let horse_positions = data.shift().split('|')
  3.     data.pop()
  4.     for (const line of data) {
  5.         let command_data = line.split(' ')
  6.         let command = command_data[0]
  7.         if (command === 'Retake') {
  8.             let overtaking_horse = command_data[1]
  9.             let overtaken_horse = command_data[2]
  10.             let overtaking_index = horse_positions.indexOf(overtaking_horse)
  11.             let overtaken_index = horse_positions.indexOf(overtaken_horse);
  12.             [horse_positions[overtaking_index], horse_positions[overtaken_index]] = [horse_positions[overtaken_index], horse_positions[overtaking_index]]
  13.             console.log(`${overtaking_horse} retakes ${overtaken_horse}.`)
  14.         }
  15.         else if (command === 'Trouble') {
  16.             let trouble_horse = command_data[1]
  17.             let trouble_horse_index =  horse_positions.indexOf(trouble_horse)
  18.             let new_horse_idx = trouble_horse_index - 1
  19.             if (trouble_horse_index !== 0) {
  20.                 let deleted_horse = horse_positions.splice(trouble_horse_index, 1)
  21.                 horse_positions = horse_positions.splice(new_horse_idx, 0, deleted_horse)
  22.  
  23.                 console.log(`Trouble for ${trouble_horse} - drops one position.`)
  24.             }
  25.         }
  26.         else if (command === 'Rage') {
  27.             let rage_horse = command_data[1]
  28.             let horse_index = horse_positions.indexOf(rage_horse)
  29.             if (horse_index === horse_positions[horse_positions.length - 2]) {
  30.                 let current_horse = horse_positions.splice(horse_index, 1)
  31.                 horse_positions.push(current_horse);
  32.             } else if (horse_index < horse_positions[horse_positions.length - 2]) {
  33.                 let new_horse_idx = horse_index + 2
  34.                 let deleted_horse = horse_positions.splice(horse_index, 1)
  35.                 horse_positions = horse_positions.splice(new_horse_idx, 0, deleted_horse)
  36.             }
  37.             console.log(`${rage_horse} rages 2 positions ahead.`)
  38.         }
  39.         else if (command === 'Miracle') {
  40.             let last_horse = horse_positions.shift()
  41.             horse_positions.push(last_horse)
  42.             console.log(`What a miracle - ${last_horse} becomes first.`)
  43.         }
  44.     }
  45.     console.log(horse_positions.join('->'))
  46.     console.log(`The winner is: ${horse_positions[horse_positions.length - 1]}`)
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement