Skip to content

Instantly share code, notes, and snippets.

@valentineus
Last active April 4, 2019 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valentineus/e8c867f9e91dd3d03f51a4ac7193709f to your computer and use it in GitHub Desktop.
Save valentineus/e8c867f9e91dd3d03f51a4ac7193709f to your computer and use it in GitHub Desktop.
"use strict";
function create(total) {
var result = [];
for (var i = 0; i < total; i++) {
result.push(i + 1);
}
return result;
}
function move(arr, old_index, new_index) {
while (old_index < 0) {
old_index += arr.length;
}
while (new_index < 0) {
new_index += arr.length;
}
if (new_index >= arr.length) {
var k = new_index - arr.length;
while (k-- + 1) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
return arr;
}
function pass(arr) {
return arr.reduce(function(previousValue, currentValue, index, array) {
if ((index + 1) & 1) {
previousValue.push(currentValue);
}
return previousValue;
}, []);
}
function cycle(number) {
var result = create(number);
var round = 1;
while (result.length > 1) {
var length = result.length;
result = pass(result);
round += 1;
if (length & 1) {
result = move(result, result.length - 1, 0);
}
}
return result;
}
// code run
var result = cycle(42);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment