来自 CodeWars 的重量重量

Weight for weight from CodeWars

问题是:

"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?"

例子

"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: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 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.

这是我目前的代码:

function sumOfParts(num) {
  return num.split('').reduce((a, b) => parseInt(a) + parseInt(b), 0)
} 

function orderWeight(string) {
  return string.split(' ').sort().sort((a,b) => sumOfParts(a) - sumOfParts(b)).join(' ')
}

字符串上的代码字即使有两个具有相同值的连续数字但是当添加 3+ 个具有相同总和的数字时它开始中断.... 这里有一些破坏它的字符串:

Expected: '112 14 170 233100 63 29 65 138 156 67 77 79 324612 144435 143275 335392 477504 460549 96194 281479 347984', instead got: '112 14 170 63 233100 29 65 156 138 67 77 79 324612 144435 143275 335392 477504 460549 96194 281479 347984'

Expected: '200 113 41 114 25 52 109 155 83 76 161330 59 450231 274111 93131 440830 432353 274292 320986 371567 29858', instead got: '200 41 113 114 52 25 109 83 155 76 59 161330 450231 274111 93131 440830 432353 274292 320986 371567 29858'

被困在这个上面的时间比我承认大声笑

谢谢

对于相同的总和,您需要一次排序和一次字符串排序。

function sumOfParts(num) {
    return num.split('').reduce((a, b) => a + +b, 0)
} 

function orderWeight(string) {
    return string
        .split(' ')
        .sort((a, b) => sumOfParts(a) - sumOfParts(b) || a > b || -(a < b))
        .join(' ');
}

console.log('out', orderWeight('112 14 170 63 233100 29 65 156 138 67 77 79 324612 144435 143275 335392 477504 460549 96194 281479 347984'));
console.log('exp', '112 14 170 233100 63 29 65 138 156 67 77 79 324612 144435 143275 335392 477504 460549 96194 281479 347984');


console.log('out', orderWeight('200 41 113 114 52 25 109 83 155 76 59 161330 450231 274111 93131 440830 432353 274292 320986 371567 29858'));
console.log('exp', '200 113 41 114 25 52 109 155 83 76 161330 59 450231 274111 93131 440830 432353 274292 320986 371567 29858');