Advertisement
giovani-rubim

Linear array rotation

Aug 29th, 2020
1,522
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const rotate = (array, a, b, c) => {
  2.     for (;;) {
  3.         const n1 = b - a;
  4.         const n2 = c - b;
  5.         if (n1 === 0 || n2 === 0) break;
  6.         const len = c - a;
  7.         const min = n1 < n2? n1: n2;
  8.         const max = len - min;
  9.         if (n1 === max) {
  10.             const end = c - 1 - n1;
  11.             for (let i=c-1; i>end; --i) {
  12.                 const j = i - n2;
  13.                 const aux = array[i];
  14.                 array[i] = array[j];
  15.                 array[j] = aux;
  16.             }
  17.         } else {
  18.             const end = a + n2;
  19.             for (let i=a; i<end; ++i) {
  20.                 const j = i + n1;
  21.                 const aux = array[i];
  22.                 array[i] = array[j];
  23.                 array[j] = aux;
  24.             }
  25.         }
  26.         const rotations = max % min;
  27.         if (rotations === 0) break;
  28.         if (n1 === max) {
  29.             c = a + min;
  30.             b = a + rotations;
  31.         } else {
  32.             a += max;
  33.             b = c - rotations;
  34.         }
  35.     }
  36. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement