Advertisement
Guest User

BeautifulArrays

a guest
Oct 16th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arr) {
  2.     let sorted = arr.slice().sort((a, b) => a - b);
  3.     let swapsAsc = findSwaps(arr, sorted);
  4.     let swapsDesc = findSwaps(arr, sorted.slice().reverse());
  5.     return Math.min(swapsAsc, swapsDesc);
  6. }
  7.  
  8. function findSwaps(arr, sorted) {
  9.     // map value to index
  10.     let value2index = arr.reduce((acc, curr, index) => {acc[curr] = index; return acc}, {});
  11.     let answer = 0;
  12.     for (let i = 0; i < arr.length; i++) {
  13.         // At index i there must be value sorted[i]
  14.         if (arr[i] != sorted[i]) {
  15.             // Find the position of value sorted[i] in the input array
  16.             let position = value2index[sorted[i]];
  17.             // Swap sorted[i] with a[i]
  18.             let temp = arr[i];
  19.             arr[i] = arr[position];
  20.             arr[position] = temp;
  21.             // Update the position of a[position] in the value2index map
  22.             value2index[arr[position]] = position;
  23.             // Increment swap count
  24.             answer++;
  25.         }
  26.     }
  27.     return answer;
  28. }
  29.  
  30. console.log(solve([2, 5, 3, 1])); // should return 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement