Reputation: 95
I am trying to rotate an array from the center position. Say for example:
For an array [1,2,3,4,5]
if I select 5
as the current element, the new array should be [3,4,5,1,2]
. If I select 4
, it should be [2,3,4,5,1]
I tried the below code and it works for some extent but it positions the selected at the beginning instead of center.
Any help with the approach will be really appreciated
var arr = [0,1,2,3,4];
function rot(arr, ind)
{
var narr = [];
var len = arr.length;
for(var i=0; i<arr.length; i++)
{
narr.push((i+ind<len?arr[i+ind]:arr[len-i-1]));
}
return narr;
}
console.log(rot(arr,0))
Upvotes: 3
Views: 368
Reputation: 92607
Try
let rot= (a,v,i=a.indexOf(v)) => a.map((x,j)=> a[(i+1+j+a.length/2)%a.length|0])
where n|0
cast float to integer. We use arrow function, indexOf and map
let arr=[1,2,3,4,5];
let rot=(a,v,i=a.indexOf(v))=>a.map((x,j)=>a[(i+1+j+a.length/2)%a.length|0]);
console.log( rot(arr,4) );
console.log( rot(arr,5) );
Upvotes: 4
Reputation: 332
this is basically the same as what @Mohammad posted, but instead of using ind as the index, you use arr.indexOf(ind) to get the relevant index.
I'd also add something to deal with the case you can't find the value...
let arrr = [1,2,3,4,5];
function rot(arr, ind) {
let narr = [...arr]; //copy and de-reference our array
let indexFound = narr.indexOf(ind); //find out where ind is
if(indexFound < 0 ) return narr; //ind was not found in your array
let len = Math.floor((narr.length/2) - indexFound); //find out how far your target is from the center
let doShift = (len < 0); //if len is negative, then we need elements from the beginning moved, otherwise move the elements off the end with pop()
len = Math.abs(len); //make sure len is always positive so our loop can run
for(var i=0; i<len; i++) {
if(doShift) narr.push(narr.shift());
else narr.unshift(narr.pop());
}
return narr;
}
console.log(rot(arrr,3));
console.log(rot(arrr,1));
console.log(rot(arrr,5));
Edit: modified to handle shifting from the end or beginning
Upvotes: 2
Reputation: 1127
First, find how much you are going rotate the array (delta
) then you splice as much items as its magnitude from the front if it is negative or the back if it is positive.
Put the spliced items on the opposite end.
function rot(arr, center) {
const index = arr.indexOf(center)
if (index === -1) {
throw new Error('')
}
if (arr.length % 2 === 0) {
throw new Error('')
}
const cIndex = Math.floor(arr.length/2)
const delta = cIndex - index
let narr = [...arr]
if (delta > 0) {
let temp = narr.splice(-delta)
narr = [...temp, ...narr]
}
else if (delta < 0) {
let temp = narr.splice(0, -delta)
narr = [...narr, ...temp]
}
return narr
}
let arr = [1,2,3,4,5]
console.log(rot(arr, 1))
console.log(rot(arr, 2))
console.log(rot(arr, 3))
console.log(rot(arr, 4))
console.log(rot(arr, 5))
Upvotes: 2