Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Created June 1, 2020 00:38
Show Gist options
  • Save Shaddyjr/e4f448c73d4b8af0b2cf0ff34efabdf7 to your computer and use it in GitHub Desktop.
Save Shaddyjr/e4f448c73d4b8af0b2cf0ff34efabdf7 to your computer and use it in GitHub Desktop.
// Source - https://www.hackerrank.com/challenges/equal-stacks/problem
// Solution by user "manjula dube" - See comment at https://www.youtube.com/watch?v=X9NdolHDm2c&lc=Ugx3ya8xOB2wAj1Oi154AaABAg
function equalStacks(h1, h2, h3) {
/*
* Write your code here.
*/
// get the sum of each stack
var height1 = h1.reduce(function(a, b){return a+b;});
var height2 = h2.reduce(function(a, b){return a+b;});
var height3 = h3.reduce(function(a, b){return a+b;});
while(!(height1 === height2 && height1 === height3)) {
var discarded_block = 0;
if((height1 > height2) && (height1 > height3)){
discarded_block = h1.shift();
height1 = height1 - discarded_block;
} else if((height2 > height1) && (height2 > height3)) {
discarded_block = h2.shift();
height2 = height2 - discarded_block;
} else if((height3 > height1) && (height3 > height2)) {
discarded_block = h3.shift();
height3 = height3 - discarded_block;
} else if((height1 > height3) && (height1 === height2)) {
// 1 and 2 are greater than 3
discarded_block = h1.shift();
height1 = height1 - discarded_block;
} else if((height2 > height1) && (height2 === height3)) {
// 2 and 3 are greater than 1
discarded_block = h2.shift();
height2 = height2 - discarded_block;
} else if((height1 > height2) && (height1 === height3)){
// 1 and 3 are greater than 2
discarded_block = h3.shift();
height3 = height3 - discarded_block;
}
}
return height1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment