gpt4 book ai didi

javascript - 数字根排序算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:35:43 25 4
gpt4 key购买 nike

我正在通过 codefight 的挑战,所有测试都通过了,除了 1 个“隐藏测试”,我无法看到插入的测试数据...我正在寻求帮助,指出我在做什么我的解决方案缺少或失败的测试用例。

问题:

Digit root of some positive integer is defined as the sum of all of its digits.

You are given an array of integers. Sort it in such a way that if a comes before b then the digit root of a is less than or equal to the digit root of b. If two numbers have the same digit root, the smaller one (in the regular sense) should come first. For example 4 and 13 have the same digit root, however 4 < 13 thus 4 comes before 13 in any digitRoot sorting where both are present.

Example

For a = [13, 20, 7, 4], the output should be [20, 4, 13, 7].

[time limit] 4000ms (js) [input] array.integer a

Array of positive integers.

[output] array.integer

我的解决方案:

function digitRootSort(a) {
"use strict";

function getDigitalRoot(n) {
let _dr = n
.toString()
.split('')
.reduce((acc, val, i) => {
return acc += parseInt(val)
}, 0)
.toString()

if (_dr.length > 1) {
return getDigitalRoot(_dr)
}

return parseInt(_dr)
}

const digitalRootSorted = a.sort((a,b) => {
const _a = getDigitalRoot(a)
const _b = getDigitalRoot(b)

return _a < _b
? -1
: _a > _b
? 1
: a < b
? -1
: a === b
? 0
: 1
})

return digitalRootSorted
}

最佳答案

您可以对数字求和并使用链式方法,例如

const sum = n => [...n.toString()].reduce((a, b) => +a + +b),
array = [13, 20, 7, 4];

array.sort((a, b) => sum(a) - sum(b) || a - b);

console.log(array);

关于javascript - 数字根排序算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com