Skip to content

Instantly share code, notes, and snippets.

@agasigp
Last active December 9, 2024 10:38
Show Gist options
  • Select an option

  • Save agasigp/0bcac9282b59cc26e659cb7577100fda to your computer and use it in GitHub Desktop.

Select an option

Save agasigp/0bcac9282b59cc26e659cb7577100fda to your computer and use it in GitHub Desktop.
Answer for technical test for jobs apply at Qiscus
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