Skip to content

Instantly share code, notes, and snippets.

@salamtamp
Last active September 23, 2018 18:10
Show Gist options
  • Save salamtamp/ed46781954d659f24dff223090fe5203 to your computer and use it in GitHub Desktop.
Save salamtamp/ed46781954d659f24dff223090fe5203 to your computer and use it in GitHub Desktop.
isSwapOneTime
const isSwapOneTime = (input) => {
const diff = (a, b) => a.filter((i, idx) => i !== b[idx]);
const sort = (a) => [ ...a ].sort();
const sorted = sort(input);
return diff(input, sorted).length <= 2;
}
console.log(isSwapOneTime([1, 2, 4, 5, 3])); //false
console.log(isSwapOneTime([1, 3, 3, 4, 5])); //true
console.log(isSwapOneTime([1, 2, 3, 4, 5])); //true
console.log(isSwapOneTime([1, 3, 2, 5, 4])); //false
console.log(isSwapOneTime([2, 1, 1])); //true
@bact
Copy link

bact commented Sep 23, 2018

เออ อันนี้เด็ด ดู distance ของ diff เอา

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment