I see similar answers but I put in the work so I thought I'd post. Javascript:
var numSwapsToEquality = (str1, str2) => { const chars1 = str1.split(""); const chars2 = str2.split(""); return chars1.slice().sort().join("") !== chars2.slice().sort().join("") ? -1 : chars2.reduce((countTotal, char2) => { const count = -( chars1.reduce( (c, char1) => (c < 1 ? c : char1 !== char2 ? c + 1 : -c), 1 ) + 1 ); chars1.splice(count, 1); return countTotal + count; }, 0); }; console.log(numSwapsToEquality('abcdef', 'abdfec')); // 4 console.log(numSwapsToEquality('abcd', 'accd')); // -1 console.log(numSwapsToEquality('ab', 'ab')); // 0 console.log(numSwapsToEquality('ab', 'ba')); // 1 console.log(numSwapsToEquality('aaa', 'aaa')); // 0
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I see similar answers but I put in the work so I thought I'd post.
Javascript:
var numSwapsToEquality = (str1, str2) => { const chars1 = str1.split(""); const chars2 = str2.split(""); return chars1.slice().sort().join("") !== chars2.slice().sort().join("") ? -1 : chars2.reduce((countTotal, char2) => { const count = -( chars1.reduce( (c, char1) => (c < 1 ? c : char1 !== char2 ? c + 1 : -c), 1 ) + 1 ); chars1.splice(count, 1); return countTotal + count; }, 0); }; console.log(numSwapsToEquality('abcdef', 'abdfec')); // 4 console.log(numSwapsToEquality('abcd', 'accd')); // -1 console.log(numSwapsToEquality('ab', 'ab')); // 0 console.log(numSwapsToEquality('ab', 'ba')); // 1 console.log(numSwapsToEquality('aaa', 'aaa')); // 0