I have written a code for rotating a 1-D array by d elements but I just wondering if there is any shorter way to write this code? for instance:
arr = [1,2,3,4,5,6,7] , d = 3
newArr = [4,5,6,7,1,2,3]
const arrayRotation=(arr,d)=>{
var k = arr.slice(d)
var m = new Set(k)
var diff = ([...arr].filter(x=>!m.has(x)))
return k.concat(diff)
}
I had to use Set so I can filter the difference between 2 arrays. Is there any better way ( complexity wise) to solve this problem?
You can use slice twice and concatenate the subarrays:
const arr = [1,2,3,4,5,6,7], d = 3;
const newArr = [...arr.slice(d % arr.length), ...arr.slice(0, d % arr.length)];
console.log(newArr);
Assuming D is positive you can just use the index to map old idx => new idx.
const arr = [1,2,3,4,5,6,7]
const rot = 3;
const newArr = arr.map((el, idx) => arr[(idx+rot)%arr.length])
console.info(newArr);
>>> [4,5,6,7,1,2,3]