Last active
December 9, 2024 10:38
-
-
Save agasigp/0bcac9282b59cc26e659cb7577100fda to your computer and use it in GitHub Desktop.
Answer for technical test for jobs apply at Qiscus
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
| function calculateSeparatorSum(inputString, separators) { | |
| // Convert input string to an array of integers | |
| const numbers = inputString.split('').map(Number); | |
| // If separators is greater than or equal to the length of the input, return 0 | |
| if (separators >= numbers.length) { | |
| return 0; | |
| } | |
| // If separators is 1, return the sum of all numbers | |
| if (separators === 1) { | |
| return numbers.reduce((sum, num) => sum + num, 0); | |
| } | |
| // Calculate separator positions | |
| const separatorPositions = []; | |
| for (let i = 0; i < separators; i++) { | |
| separatorPositions.push( | |
| Math.round((i * (numbers.length - 1)) / (separators - 1)) | |
| ); | |
| } | |
| // separatorPositions | |
| if (numbers.length - 1 == separatorPositions.length || numbers.length - 2 == separatorPositions.length) { | |
| return numbers.reduce((sum, num) => sum + num, 0); | |
| } | |
| // Initialize sum | |
| let sum = 0; | |
| // Sum numbers between separators | |
| if (numbers.length % 2 === 0) { | |
| for (let i = 0; i < numbers.length; i++) { | |
| if (i !== 0 || i !== numbers.length - 1) { | |
| sum += numbers[i]; | |
| } | |
| } | |
| } else { | |
| for (let i = 1; i < separatorPositions.length; i++) { | |
| for (let j = separatorPositions[i - 1] + 1; j < separatorPositions[i];j++) { | |
| sum += numbers[j]; | |
| } | |
| } | |
| } | |
| return sum; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment