Created
November 21, 2022 16:12
-
-
Save Northernside/e2084498579cbd566049b732a566d281 to your computer and use it in GitHub Desktop.
Automatically arrange array elements to make the most of them fit into a specific character limitation
This file contains 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
/* | |
@Northernside - Elias | |
Created on 20th November 2022, | |
Last edited on 21st November 2022 | |
*/ | |
function smartArrange(array, charLimit) { | |
/* | |
We're going to use Bubble Sort here, it might not be the quickest one, but I. Don't. Care. :) | |
Also, I'm using nested for-loops, but I. Don't. Care. | |
*/ | |
for (let i = array.length - 1; i >= 0; i--) | |
for (let j = 1; j <= i; j++) { | |
if (array[j - 1].length <= array[j].length) | |
continue; | |
let tmp = array[j - 1]; | |
array[j - 1] = array[j]; | |
array[j] = tmp; | |
} | |
let charCount = 0, fittingElements = [], i = 0; | |
for (let element in array) { | |
charCount += array[element].length; | |
fittingElements.push(array[i]); | |
if (charCount + array[element].length > charLimit) | |
break; | |
i++; | |
} | |
return fittingElements; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment