Skip to content

Instantly share code, notes, and snippets.

@bmdoherty
Created August 11, 2016 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmdoherty/9c04676d4c325ff8307948fbc0bbb2e5 to your computer and use it in GitHub Desktop.
Save bmdoherty/9c04676d4c325ff8307948fbc0bbb2e5 to your computer and use it in GitHub Desktop.
<cfscript>
tests = [
// sorted
[true,[1,2,3,4,5]]
,[true,[2,4,6,8,10]]
// 1 swap
,[true,[1,2,3,5,4]]
,[true,[5,2,3,4,1]]
,[true,[1,2,3,5,3]]
// +1 swap
,[false,[5,2,3,1,4]]
,[false,[2,3,1,5,4]]
,[false,[5,1,2,3,4]]
,[false,[2,3,1,5,4]]
,[false,[2,3,1,4,5]]
,[false,[1,2,3,5,2]]
];
function diff(a1, a2) {
var diff = []
for (i = 1; i <= ArrayLen(a1); i++) {
if(a1[i] != a2[i]){
diff.append(a1[i])
}
}
return diff;
}
function isAlmostSorted(a){
var sorted = duplicate(a).sort("numeric");
var difference = []
if (a.equals(sorted)){
return true;
}
else{
difference = diff(a, sorted);
if( len(difference) lte 2 ){
return true
}
}
return false;
}
for (test in tests) {
result = isAlmostSorted(test[2]);
writeoutput("test " & serializeJSON(test[2]) & " : " & (result == test[1] || (!test[1] && result < 0) ? "pass " & (!!result) : "fail - got "&result) & "<br />");
}
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment