Last active
January 13, 2018 06:43
-
-
Save JohannesFischer/2c5a2046e2442ff18f9f56753ca92a0e to your computer and use it in GitHub Desktop.
determine if an array is sortable with one swap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// test arrays | |
var x = [1, 2, 3]; | |
var y = [1, 3, 2]; | |
var z = [3, 2, 1]; | |
// global swap counter | |
var swaps = 0; | |
// custom sort function that counts swaps | |
function swapcount(a, b){ | |
if (a < b) { | |
return -1; | |
} else if (a > b) { | |
swaps++; | |
return 1; | |
} | |
return 0; | |
} | |
// shallow compare two arrays | |
function compareAr(a, b) { | |
if (a.length !== b.length) return false; | |
for (var i = 0; i < a.length; i++) { | |
if (a[i] !== b[i]) return false; | |
} | |
return true; | |
} | |
// test function | |
function solution(a) { | |
var sorted = a.slice().sort(); | |
// true when already sorted | |
if (compareAr(a, sorted)) return true; | |
// count swaps | |
swaps = 0 | |
a.sort(swapcount); | |
// false when more than one swap is needed | |
if (swaps > 1) { | |
return false; | |
} | |
// true when sorated with one swap | |
return true; | |
} | |
[x, y, z].forEach(ar => console.log(solution(ar))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment