mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-09-20 07:43:04 +08:00
Merge 2876c14c0e
into ca3d16dcce
This commit is contained in:
commit
a5c4879250
27
src/data-structures/array-rotation/ArrayRotation.js
Normal file
27
src/data-structures/array-rotation/ArrayRotation.js
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
import Comparator from '../../../utils/comparator/Comparator';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Give an array of integers numbers, the task is rotate the array elements to the left
|
||||||
|
* according to the number of positions provided
|
||||||
|
*
|
||||||
|
* @param {*[]} array
|
||||||
|
* @param {*} seekElement
|
||||||
|
* @param {function(a, b)} [comparatorCallback]
|
||||||
|
* @return {number[]}
|
||||||
|
*/
|
||||||
|
export default function arrayRotation(arr,d,comparatorCallback){
|
||||||
|
const comparator = new Comparator(comparatorCallback);
|
||||||
|
if(d>arr.length-1) return false;
|
||||||
|
let p = 1;
|
||||||
|
|
||||||
|
while(p<=d){
|
||||||
|
let first = arr[0];
|
||||||
|
|
||||||
|
for(let i=0;i<=arr.length-1;i++){
|
||||||
|
if(comparator.equal(i,arr.length-1)) arr[i] = first
|
||||||
|
else arr[i] = arr[i+1];
|
||||||
|
}
|
||||||
|
p = p+1;
|
||||||
|
}
|
||||||
|
return arr;
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
import arrayRotation from '../ArrayRotation';
|
||||||
|
|
||||||
|
describe('arrayRotation', () => {
|
||||||
|
it('should move to left all numbers according to the number of positions provided', () => {
|
||||||
|
const array =[1,2,3,4,5,6,7,8];
|
||||||
|
|
||||||
|
expect(arrayRotation(array,4)).toEqual([5,6,7,8,1,2,3,4]);
|
||||||
|
expect(arrayRotation(array,2)).toEqual([3,4,5,6,7,8,1,2]);
|
||||||
|
expect(arrayRotation(array,3)).toEqual([,4,5,6,7,8,1,2,3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return false if the number of positions to move greater than the size of the array', () => {
|
||||||
|
const array =[1,2,3,4,5,6,7,8];
|
||||||
|
expect(arrayRotation(array,10)).toEqual(false);
|
||||||
|
});
|
||||||
|
});
|
Loading…
Reference in New Issue
Block a user