return the smallest possible join from array javas

2019-07-24 19:06发布

问题:

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