Advertisement
pacho_the_python

Untitled

Apr 20th, 2023
664
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_positions[trouble_horse_index]
  21.                 horse_positions[deleted] = horse_positions[new_horse_idx];
  22.                 horse_positions[new_horse_idx] = deleted
  23.  
  24.                 console.log(`Trouble for ${trouble_horse} - drops one position.`)
  25.             }
  26.         }
  27.         else if (command === 'Rage') {
  28.             let rage_horse = command_data[1]
  29.             let horse_index = horse_positions.indexOf(rage_horse)
  30.             if (horse_index === horse_positions[horse_positions.length - 2]) {
  31.                 let current_horse = horse_positions.splice(horse_index, 1)
  32.                 horse_positions.push(current_horse)
  33.                 console.log(`${rage_horse} rages 2 positions ahead.`)
  34.             } else if (horse_index < horse_positions[horse_positions.length - 2]) {
  35.                 let new_horse_idx = horse_index + 2
  36.                 let deleted_horse = horse_positions.splice(horse_index, 1)
  37.                 horse_positions = horse_positions.splice(new_horse_idx, 0, deleted_horse)
  38.                 console.log(`${rage_horse} rages 2 positions ahead.`)
  39.             }
  40.  
  41.         }
  42.         else if (command === 'Miracle') {
  43.             let last_horse = horse_positions.shift()
  44.             horse_positions.push(last_horse)
  45.             console.log(`What a miracle - ${last_horse} becomes first.`)
  46.         }
  47.     }
  48.     console.log(horse_positions.join('->'))
  49.     console.log(`The winner is: ${horse_positions[horse_positions.length - 1]}`)
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement