Skip to content

Instantly share code, notes, and snippets.

@yayudev
Last active September 1, 2016 07:11
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 yayudev/17658b9b4b71cf8cde3d to your computer and use it in GitHub Desktop.
Save yayudev/17658b9b4b71cf8cde3d to your computer and use it in GitHub Desktop.
Paiza p5, given n rectangle coords within a matrix, calculate the sum of every number inside the area composed by all of the n rectangles (removing duplicate/collisions between rectangles)
var line = "4 5 3\n948 608 920 216\n3 413 306 7\n312 173 0 1000\n365 726 280 358\n26 539 197 753\n2 1 3 3\n3 3 4 4\n1 4 4 5 "
var input = line.split(/\n/);
// Remove first line (info) and get it's info.
matrix_data = input.shift().split(" ");
matrix_sizex = matrix_data[0];
matrix_sizey = matrix_data[1];
matrix_sizeSelection = matrix_data[2];
// Remove \n's
input = input.filter(function (element) {
return !element.match(/\n/);
});
// Separate the input into a array.
var inputCleanArray = [];
for (var i = 0; i < input.length; i++) {
inputCleanArray[i] = input[i]
.split(/\s/)
.filter(function (element) {
return !element.match(/\s/);
})
}
// Values matrix.
var valuesMatrix = inputCleanArray.slice(0, matrix_sizey)
// Selection .
var selections = inputCleanArray.slice(matrix_sizey, input.length)
// Divide matrix into top-bootom x,y pairs
var selectionArray = []
for (var i = 0; i < selections.length; i++) {
selectionArray.push({
top: {
x: +selections[i][0],
y: +selections[i][1]
},
bottom: {
x: +selections[i][2],
y: +selections[i][3]
}
});
}
// Find every coord touched by selections
var coordsCollection = [];
selectionArray.forEach(function(selection){
console.log(selection)
for(var x = selection.top.x; x <= selection.bottom.x; x++){
for(var y = selection.top.y; y <= selection.bottom.y; y++){
coordsCollection.push([x,y])
}
}
});
// Remove duplicates
coordsCollection = uniq(coordsCollection)
// Sum all values in the area.
var total = 0;
coordsCollection.forEach(function(coord){
total += +valuesMatrix[coord[1]-1][coord[0]-1]
})
console.log(total)
function uniq(arr) {
var seen = {};
var result = [];
var len = arr.length;
for (var i = 0; i < len; i++) {
var el = arr[i];
if (!seen[el]) {
seen[el] = true;
result.push(el);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment