Advertisement
Guest User

BeautifulArrays

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