New Year Chaos

  • + 0 comments

    Javascript

    It's essentially a reverse insertion sort. You just keep looping through the array doing a single swap until it's sorted. Count how many times you had to make a swap to get it sorted. Break if the value of any element is more than two higher than its original position.

    function minimumBribes(q: number[]): void {
      let totalBribes = 0;
      
      let sorted = false;
      
      while (sorted === false) {
        sorted = true;
        
        for (let i=0; i < q.length-1; i++) {
          if (q[i] > q[i+1]) {
            if (q[i] - (i+1) > 2) {
              console.log('Too chaotic');
              return;
            }
            const temp = q[i];
            q[i] = q[i+1];
            q[i+1] = temp;
            sorted = false;
            totalBribes++;
          }
        }
      }
      
      console.log(totalBribes);
    }