return the smallest possible join from array javascript

孤街醉人 提交于 2020-01-24 20:03:08

问题


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('');
}

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.


回答1:


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.

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('')));

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('')));


来源:https://stackoverflow.com/questions/47378471/return-the-smallest-possible-join-from-array-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!