Skip to content

Instantly share code, notes, and snippets.

@akhoury
Last active December 20, 2015 18:59
Show Gist options
  • Save akhoury/6179684 to your computer and use it in GitHub Desktop.
Save akhoury/6179684 to your computer and use it in GitHub Desktop.
"Foldable Array" puzzle live: http://jsbin.com/ibewis/6/edit
/*
example:
// [1,2,3,4,5,6,7,8] (must be a power of 2 length)
var arr = new Foldable([1, 2, 3, 4, 5, 6, 7, 8]);
arr.fold( [ "l", "r", "l" ] ); // left, right, left
// left
[4, 3, 2, 1]
[5, 6, 7, 8]
//right
[8, 7]
[1, 2]
[4, 3]
[5, 6]
//left and final result
[5]
[4]
[1]
[8]
[7]
[2]
[3]
[6]
*/
(function () {
'use strict';
var pow2exp = function (n) {
return Math.log(n) / Math.log(2);
};
var Foldable = function (arr) {
if ( !arr || !arr.length || ( ( pow2exp( arr.length ) % 1 ) !== 0 ) ) {
throw new Error("Initial array must be of a power of 2 length");
}
this._arr = arr;
this._2d = [arr];
};
Foldable.prototype = {
fold: function (steps) {
var len = this._foldLength();
if (!steps || !steps.length) return;
for (var i = 0; i < len; i++) {
if (steps[i] === 'r')
this._foldRight();
else if (steps[i] === 'l')
this._foldLeft();
}
},
get2DResult: function () {
return this._2d;
},
getFlatArray: function () {
var _arr = [];
this._2d.forEach(function (a) {
_arr.push(a);
});
return _arr;
},
toString: function () {
var str = "[\n";
this._2d.forEach(function (arr) {
str += "\t[" + arr + "]\n";
});
str += "]\n";
return str;
},
_foldLeft: function () {
var _new_2d = [];
for (var i = 0; i < this._2d.length; i++) {
var left = this._2d[i].slice(0, this._2d[i].length / 2);
var right = this._2d[i].slice(this._2d[i].length / 2, this._2d[i].length);
left.reverse();
_new_2d.unshift(left);
_new_2d.push(right);
}
this._2d = _new_2d;
},
_foldRight: function () {
var _new_2d = [];
for (var i = 0; i < this._2d.length; i++) {
var left = this._2d[i].slice(0, this._2d[i].length / 2);
var right = this._2d[i].slice(this._2d[i].length / 2, this._2d[i].length);
right.reverse();
_new_2d.unshift(right);
_new_2d.push(left);
}
this._2d = _new_2d;
},
_foldLength: function () {
return pow2exp(this._arr.length);
}
};
// test
var farr = window.a = new Foldable([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(farr.toString());
farr.fold(["l", "r", "l"]);
console.log(farr.toString());
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment