Skip to content

Commit fee46b9

Browse files
committed
update: new problem added
1 parent efa1e53 commit fee46b9

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/_Problems_/compose-largest-number/compose-largest.test.js

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/** Given an array of numbers, return the highest number that can be made out of it */
2+
3+
/**
4+
* Test cases
5+
* [3, 6, 0, 9] -> 9630
6+
* [60, 548] -> 60548
7+
* [1, 34, 3, 98, 9, 76, 45, 4] -> 998764543431
8+
*/
9+
10+
/** At first glance, the below solution may seem the answer */
11+
const hightestNumber = Number([60, 548].sort((a, b) => b - a).join(""));
12+
13+
/** The above will fail for test case 2 & 3 */
14+
15+
/** We need a custom compare funtion */
16+
function compare(a, b) {
17+
const x = Number(String(a) + String(b));
18+
const y = Number(String(b) + String(a));
19+
return x > y ? -1 : 1;
20+
}
21+
22+
/** final function */
23+
function composeHighest(arr) {
24+
if (!arr || !Array.isArray(arr)) {
25+
throw new Error("Invalid array/missing argument");
26+
}
27+
28+
return Number(arr.sort(compare).join(""));
29+
}
30+
31+
/** tests */
32+
33+
console.log(composeHighest([3, 6, 0, 9]) === 9630);
34+
console.log(composeHighest([60, 548]) === 60548);
35+
console.log(composeHighest([1, 34, 3, 98, 9, 76, 45, 4]) === 998764543431);

0 commit comments

Comments
 (0)