从数组javascript返回最小可能的联接 [英] return the smallest possible join from array javascript
问题描述
我有适合以下数组的代码:['45','30','50','1'].
I have this code which works good for this array: ['45', '30', '50', '1'].
function penalty(a_list) {
return a_list.sort((a, b) => a - b).join('');
}
例如:假设a_list为['45','30','50','1'],则最小的字符串为'1304550',这是正确的,但是如果a_list为['32',给定当前代码,"3"]我将得到不正确的"332",因为"323"是可能的最小字符串.希望能有所帮助.
for example: given that a_list is ['45', '30', '50', '1'] the smallest possible string will be '1304550' which is right, but what if a_list is ['32', '3'] given this current code I will get '332' which is not correct because '323' is the smallest possible string. Hope that helps.
推荐答案
您可以采用a
和b
的隐式值以及b
和a
的值,并取其差值进行排序,它以较小的值反映了两个字符串的排序顺序,以供以后连接.
You could take the concatinated values of a
and b
and the value of b
and a
and take the delta of it for sorting, which reflects the sort order of the two string for a smaller value for later joining.
如果提供了整数,则需要在sort回调中将值转换为字符串.
If integers are supplied, then the values need to be converted to string in the sort callback.
function sort(a, b) {
return (a + b) - (b + a);
}
console.log([['45', '30', '50', '1'], ['32', '3']].map(a => a.sort(sort).join('')));
对于稳定的排序,可以将较小的值移到顶部(这不会影响后面的连接字符串).这将'3'
排在'33'
之前.
For a stable sort, you could move smaller values to top (which does not affect the later joined string). This sorts '3'
before '33'
.
function sort(a, b) {
return (a + b) - (b + a) || a - b;
}
console.log([['45', '30', '50', '1'], ['32', '3']].map(a => a.sort(sort).join('')));
这篇关于从数组javascript返回最小可能的联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!