Last active
April 14, 2020 02:44
-
-
Save javi-aire/4f408ad1a591b68d8706bed4f5fb61f4 to your computer and use it in GitHub Desktop.
Problem 12/30 of LeetCode 30-day challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let lastStoneWeight = function(stones) { | |
| // 2 pointers & index for tracking in array | |
| let pointer1 = 0; | |
| let pointer2 = pointer1 + 1; | |
| let index = pointer2 + 1; | |
| let weight1, weight2; | |
| // reset pointers and weights | |
| function resetValues() { | |
| // reset pointers and weights | |
| pointer1 = 0; | |
| pointer2 = pointer1 + 1; | |
| index = pointer2 + 1; | |
| weight1 = weight2 = 0; | |
| } | |
| while(stones.length > 1) { | |
| // find two largest nums in array | |
| findLargestWeights(pointer1, pointer2); | |
| if(index > stones.length){ | |
| // compare weights if index is at the end of array | |
| compareWeights(weight1, weight2); | |
| // reset pointers and weights | |
| resetValues(); | |
| } | |
| } | |
| // finds the largest weights left in array | |
| function findLargestWeights(pointer1, pointer2) { | |
| if(stones[pointer1] > stones[pointer2]) { | |
| // set weight2 | |
| weight2 = weight2 > stones[pointer2] ? weight2 : stones[pointer2]; | |
| weight1 = stones[pointer1]; | |
| // move the second pointer to current index then increase index | |
| pointer2 = index++; | |
| } else { | |
| // set weight1 | |
| weight1 = weight1 > stones[pointer1] ? weight1 : stones[pointer1]; | |
| weight2 = stones[pointer2]; | |
| // move the first pointer to current index then increase index | |
| pointer1 = index++; | |
| } | |
| if(index > stones.length){ | |
| return; | |
| } | |
| return findLargestWeights(pointer1, pointer2); | |
| } | |
| // compares the weights then adjusts | |
| // array based on caveats (see comments within conditional) | |
| function compareWeights(weight1, weight2) { | |
| if(weight1 === weight2) { | |
| // both stones are removed from array | |
| stones.splice(stones.indexOf(weight1), 1); | |
| stones.splice(stones.indexOf(weight2), 1); | |
| } else { | |
| // splice weight1 and weight2 & replace with weight2 = weight2 - weight1 | |
| let leftoverWeight = Math.abs(weight2 - weight1); | |
| stones.splice(stones.indexOf(weight2), 1); | |
| stones.splice(stones.indexOf(weight1), 1, leftoverWeight); | |
| } | |
| } | |
| return stones.length > 0 ? stones[0] : 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment