/*
for example:
[1, 15, 17, 10, 25]
group like:
1: {
less: [15, 17], (1 < 5, 1 < 7)
eq: [1],
more: [10] (1 > 0)
}
2: {
less: [25]
}
and group again every less and more group untill group size > 1: ...less, ...eq, ...more
*/
function group(arr, index = 0) {
if (arr.length < 2) {
return arr[0] || "";
}
let res = "";
const groups = Array.from({length: 10}, _ => ({
more: [],
less: [],
eq: [],
active: false
}));
for (let i=0; i<arr.length; i++) {
const char = parseInt(arr[i][index], 10);
groups[char].active = true;
if (arr[i].length - 1 === index) {
groups[char].eq.push(arr[i]);
} else {
if (char < arr[i][index+1]) {
groups[char].less.push(arr[i]);
} else {
groups[char].more.push(arr[i]);
}
}
}
for (let i=9; i>=0; i--) {
const g = groups[i];
if (g.active) {
res += group(g.less, index + 1) + g.eq.join("") + group(g.more, index + 1);
}
}
return res;
}
console.log(group([ "123", "124", "56", "90"]));
console.log(group(["12", "14", "15", "19", "2", "25", "21", "67"]));
console.log(group(["123", "124", "56", "90", "95", "87", "8", "88", "89"]));
Last active
June 1, 2018 14:58
-
-
Save KolosovAO/f43cce8b74a8c40799e3d9e53b5bbfb7 to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment