getSkyline = (buildingsList) => {
let animationSteps = [];
const skyLine = (buildings) => {
if(buildings.length){
let dCopy = JSON.parse(JSON.stringify(buildings));
let step = {type: "divide", data:dCopy};
animationSteps.push(step);
}
if(!buildings.length){
return [];
}
if(buildings.length == 1){
let pt1 = {id: `${buildings[0].x}${buildings[0].height}`, x: buildings[0].x, y: buildings[0].height,status: "divided"}
let pt2 = {id: `${buildings[0].x2}${0}`, x: buildings[0].x2, y: 0, status: "divided"};
return [pt1,pt2];
}
let midPoint = Math.floor(buildings.length/2);
let left = buildings.slice(0,midPoint);
let right = buildings.slice(midPoint,buildings.length);
left = skyLine(left);
right = skyLine(right);
let solution = [];
let h1 = 0,
h2 = 0,
x = 0,
height = 0;
//merge
while(left.length && right.length){
//each point pair being compared
let l = left[0];
l.status = "compare";
let r = right[0];
r.status = "compare";
let mg = [l,r];
let cCopy = JSON.parse(JSON.stringify(mg));
let step2 = {type: "conquer", data:cCopy};
animationSteps.push(step2);
if(left[0].x < right[0].x){
x = left[0].x;
h1 = left[0].y;
left.shift();
}else{
if(left[0].x > right[0].x){
x = right[0].x;
h2 = right[0].y;
right.shift();
}else{
x = left[0].x;
h1 = left[0].y;
h2 = right[0].y;
left.shift();
right.shift();
}
}
//show left x + height, right x +height,
//take min x, or if equal, take max height of the two
//take min x + height, or if x same for both buildings, add it w/ max height to solution
height = d3.max([h1,h2]);
let solPt = {id: `${x}${height}`, x: x, y: height}
let ptCopy,step3;
if(!solution.length || height != solution[solution.length-1].y){
solPt.status = "solution";
ptCopy = JSON.parse(JSON.stringify([solPt]));
step3 = {type: "conquer", data:ptCopy};
animationSteps.push(step3);
solution.push(solPt);
}else{
solPt.status = "discard";
ptCopy = JSON.parse(JSON.stringify([solPt]));
step3 = {type: "conquer", data:ptCopy};
animationSteps.push(step3);
}
}
while(left.length){
let solPtL = left.shift();
solPtL.status = "solution";
let slCopy = JSON.parse(JSON.stringify([solPtL]));
let step4 = {type: "conquer", data:slCopy};
animationSteps.push(step4);
solution.push(solPtL);
}
while(right.length){
let solPtR = right.shift()
solPtR.status = "solution";
let srCopy = JSON.parse(JSON.stringify([solPtR]));
let step5 = {type: "conquer", data:srCopy};
animationSteps.push(step5);
solution.push(solPtR);
}
//for visualization
if(solution.length){
let sCopy = JSON.parse(JSON.stringify(solution));
animationSteps.push({type: "conquer", action: "solution", data: sCopy});
}
return solution;
}
let sortedSkyline = skyLine(buildingsList);
let outline = getLines(sortedSkyline);
return [sortedSkyline,outline,animationSteps];
}