Skip to content

Instantly share code, notes, and snippets.

@Tankenstein
Last active August 29, 2015 14:25
Show Gist options
  • Save Tankenstein/fb49e58b548dc6c3feeb to your computer and use it in GitHub Desktop.
Save Tankenstein/fb49e58b548dc6c3feeb to your computer and use it in GitHub Desktop.
/**
* This is a copy of https://www.youtube.com/watch?v=a9xAKttWgP4 (Conway's game of life in APL) in
* javascript.
*
* This is a completely functional implementation of game of life,
* with data being completely immutable.
*
* Author: Uku Tammet
* Date : 24.07.2015
*/
function mod(n, m) {
return ((n % m) + m) % m;
}
function localBinding(v, func) {
return func(v);
}
function rowRotation(matrix, rotations) {
return rotations.map(function(rotation) {
return matrix.map(function(row) {
return row.map(function(_, index, self) {
return self[mod(index+rotation, self.length)];
});
});
});
}
function columnRotation(matrix, rotations) {
return rotations.map(function(rotation) {
return matrix.map(function(row, index, self) {
return self[mod(index + rotation, self.length)]
});
});
}
function matrixSum(prev, crnt) {
return prev.map(function(row, x) {
return row.map(function(column, y) {
return column + crnt[x][y];
});
});
}
/**
* Life takes in the previous generation and returns the next generation.
*/
function life (previousGeneration) {
return localBinding([1, 0, -1], function(rotations) {
return rowRotation(previousGeneration, rotations).map(function(matrix) {
return columnRotation(matrix, rotations).reduce(matrixSum);
}).reduce(matrixSum);
}).map(function(row, x) {
return row.map(function(column, y) {
return column === 3 || (column === 4 && previousGeneration[x][y] === 1) ? 1 : 0;
});
});
}
// End of implementation, test the function here.
function printMatrix(matrix) {
matrix.forEach(function(row) {
console.log(row.reduce(function(prev, crnt) {
return prev + ' ' + crnt;
}));
});
}
var original = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 1, 1, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
printMatrix(original);
printMatrix(life(original));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment