Guest User

Untitled

a guest
Jan 23rd, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. // test arrays
  2. var x = [1, 2, 3];
  3. var y = [1, 3, 2];
  4. var z = [3, 2, 1];
  5.  
  6. // global swap counter
  7. var swaps = 0;
  8.  
  9. // custom sort function that counts swaps
  10. function swapcount(a, b){
  11. if (a < b) {
  12. return -1;
  13. } else if (a > b) {
  14. swaps++;
  15. return 1;
  16. }
  17.  
  18. return 0;
  19. }
  20.  
  21. // shallow compare two arrays
  22. function compareAr(a, b) {
  23. if (a.length !== b.length) return false;
  24.  
  25. for (var i = 0; i < a.length; i++) {
  26. if (a[i] !== b[i]) return false;
  27. }
  28.  
  29. return true;
  30. }
  31.  
  32. // test function
  33. function solution(a) {
  34. var sorted = a.slice().sort();
  35.  
  36. // true when already sorted
  37. if (compareAr(a, sorted)) return true;
  38.  
  39. // count swaps
  40. swaps = 0
  41. a.sort(swapcount);
  42.  
  43. // false when more than one swap is needed
  44. if (swaps > 1) {
  45. return false;
  46. }
  47.  
  48. // true when sorated with one swap
  49. return true;
  50. }
  51.  
  52. [x, y, z].forEach(ar => console.log(solution(ar)));
Add Comment
Please, Sign In to add comment