Skip to content

Instantly share code, notes, and snippets.

@lucas-janon
Created June 24, 2018 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucas-janon/c1cbcd3a0452f39a5118334fb537ffe2 to your computer and use it in GitHub Desktop.
Save lucas-janon/c1cbcd3a0452f39a5118334fb537ffe2 to your computer and use it in GitHub Desktop.
Gets highest combination possible from a positive integer array
const arr = [9, 90, 95, 99, 50, 5, 56, 504, 5006, 544, 1]
const highestCombination = (a) => {
const grouped = a.reduce(
(acc, c) => {
const cInitial = `${c}`.split('')[0]
acc[cInitial] ?
acc[cInitial].items.push(c)
:
acc[cInitial] = { items: [c], longest: 0 }
acc[cInitial].longest = acc[cInitial].longest > `${c}`.length ? acc[cInitial].longest : `${c}`.length
return acc
},
{}
)
const getAbsVal = (n, long) => {
const str = `${n}`
const splitted = str.split('')
const toRepeat = splitted[str.length - 1] > splitted[0] ? splitted[str.length - 1] : splitted[0]
return str + toRepeat.repeat(long - str.length)
}
return Object.keys(grouped)
.sort((a, b) => a < b)
.reduce(
(acc, key) => {
const items = grouped[key].items.sort((a, b) => {
const A = getAbsVal(a, grouped[key].longest)
const B = getAbsVal(b, grouped[key].longest)
return parseInt(A, 10) < parseInt(B, 10)
})
return [...acc, ...items]
},
[]
)
.join('')
}
console.log(highestCombination(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment