Last active
February 11, 2025 12:28
-
-
Save MariaSzubski/d92a0dd6028fec76d1c6aea0ee91a344 to your computer and use it in GitHub Desktop.
Given N sticks, reduce the length of each by the length of the smallest stick. Print the number of sticks that are left before each cut operation.
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
| /* | |
| Solution for HackerRank > Algorithms > Implementation > Cut The Sticks | |
| https://www.hackerrank.com/challenges/cut-the-sticks | |
| */ | |
| function cutSticks() { | |
| var n = 8; // Number of sticks | |
| arr = [1,2,3,4,3,3,2,1]; // Stick length | |
| while (arr.length > 0){ | |
| // Print the current number of sticks | |
| console.log(arr.length); | |
| // Sort the stick array lowest to highest | |
| arr.sort( (a, b) => (a - b) ); | |
| // Subtract the lowest value from each stick | |
| var cut = arr[0]; | |
| for (var i = 0; i < arr.length; i++){ | |
| arr[i] -= cut; | |
| } | |
| // Remove the '0' sticks from the array | |
| var remove = arr.lastIndexOf(0) + 1; | |
| arr.splice(0, remove); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
arr.sort should be outside from while loop