DEV Community

Discussion on: Daily Challenge #268 - Swapping Characters in Strings

Collapse
dry profile image
Hayden Mankin • Edited on

Javascript 1 liners

Recursive

const obtain=(s,t,count=0)=>s?~(idx=t.indexOf(s[0]))?obtain(s.slice(1),t.slice(0,idx)+t.slice(idx+1),idx+count):-1:count;

console.log(obtain('abcdef', 'abdfec'));  // 4
console.log(obtain('abcd', 'accd'));      // -1
console.log(obtain('ab', 'ab'));          // 0
console.log(obtain('ab', 'ba'));          // 1
console.log(obtain('aaa', 'aaa'));        // 0

Iterative

const obtain = (s,t)=>s.split("").reduce((a,v)=>~a&&~(i=t.indexOf(v))?~~(t=t.slice(0,i)+t.slice(i+1))||a+i:-1,0)

console.log(obtain('abcdef', 'abdfec'));  // 4
console.log(obtain('abcd', 'accd'));      // -1
console.log(obtain('ab', 'ab'));          // 0
console.log(obtain('ab', 'ba'));          // 1
console.log(obtain('aaa', 'aaa'));        // 0