Right-cyclic array rotation

in code


The solution is ugly, but fuck it: the code works. Also, code Zen. ;) TL;DR: Create a new array by plucking the last element from the array and making it the first.

def rotate(array, count)
  return array unless (count >= 1 && array.present?)
  rotate(cycle(array), count - 1)
end

def cycle(array)
  [array[-1]] + array[0..-2]
end

And in JavaScript:

function rotate(array, count) {
    if (count < 1 || !array.length) {
        return array;
    } else {
        return rotate(cycle(array), count - 1);
    }
}

function cycle(array) {
    return [].concat(array.slice(-1), array.slice(0, -1));
}

To test:

let a = [0, 1, 1, 1, 1, 1];
rotate(a, 1); // [1, 0, 1, 1, 1, 1]
rotate(a, 2); // [1, 1, 0, 1, 1, 1]


Remap a JavaScript Object

in code

Blog Silence

in me

Run Clare 2019 Race Series

in running


Your email address will not be published. Required fields are marked *