https://www.codewars.com/kata/55c6126177c9441a570000cc
Codewars - Achieve mastery through coding practice and developer mentorship
A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!
www.codewars.com
DESCRIPTION:
My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest.
I am the one who establishes the list so I told him: "Don't worry any more, I will modify the order of the list". It was decided to attribute a "weight" to numbers. The weight of a number will be from now on the sum of its digits.
For example 99 will have "weight" 18, 100 will have "weight" 1 so in the list 100 will come before 99.
Given a string with the weights of FFC members in normal order can you give this string ordered by "weights" of these numbers?
Example:
"56 65 74 100 99 68 86 180 90" ordered by numbers weights becomes:
"100 180 90 56 65 74 68 86 99"
When two numbers have the same "weight", let us class them as if they were strings (alphabetical ordering) and not numbers:
180 is before 90 since, having the same "weight" (9), it comes before as a string.
All numbers in the list are positive numbers and the list can be empty.
Notes
- it may happen that the input string have leading, trailing whitespaces and more than a unique whitespace between two consecutive numbers
- For C: The result is freed.
코드
function orderWeight(strng) {
const arr = [];
if(!strng.length) return '';
strng = strng.split(' ').map(Number);
for(let i = 0; i < strng.length; i++){
arr.push([strng[i], strng[i].toString().split('').map(Number).reduce((a, b) => a + b, 0)]);
}
return arr.sort((a, b) => {
if(a[1] === b[1]){
return String(a[0]).localeCompare(String(b[0]));
} else{
return a[1] - b[1];
}
}).map(el => el[0]).join(' ');
}
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Two Sum (6 kyu) / JavaScript (0) | 2023.04.24 |
---|---|
[Codewars] Mexican Wave (6 kyu) / JavaScript (0) | 2023.04.24 |
[Codewars] Don't give me five! (7 kyu) / JavaScript (0) | 2023.04.22 |
[Codewars] Find the stray number (7 kyu) / JavaScript (0) | 2023.04.20 |
[Codewars] Twice as old (8 kyu) / JavaScript (0) | 2023.04.20 |
댓글