Largest int from concatenated ints: Difference between revisions

→‎C: Add implementation
(→‎C: Add implementation)
Line 14:
* [http://www.quora.com/Algorithms/What-is-the-most-efficient-way-to-arrange-the-given-numbers-to-form-the-biggest-number Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?].
* [http://stackoverflow.com/questions/14532105/constructing-the-largest-number-possible-by-rearranging-a-list/14539943#14539943 Constructing the largest number possible by rearranging a list]
 
=={{header|C}}==
<lang C>#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
 
int diglen(int n)
{
int len = 1;
while (n /= 10) ++len;
return len;
}
 
int icsort(const void *px, const void *py)
{
int x = *(int *) px, y = *(int *) py;
int lx = diglen(x), ly = diglen(y);
int mx = 10, my = 10; /* magnitudes */
 
while (--lx) mx *= 10;
while (--ly) my *= 10;
return (y * mx + x) - (x * my + y);
}
 
long maxcat(int sz, ...)
{
int i, len = 0, off = 0;
int n, *ns = malloc(sz * sizeof(int));
char *buf;
long max;
 
va_list va;
va_start(va, sz);
for (i = 0; i < sz; ++i) {
n = va_arg(va, int);
ns[i] = n;
len += diglen(n);
}
va_end(va);
 
buf = malloc(++len);
qsort(ns, sz, sizeof(int), icsort);
 
for (i = 0; i < sz; ++i)
off += sprintf(buf + off, "%d", ns[i]);
max = atol(buf);
 
free(ns);
free(buf);
return max;
}
 
int main(void)
{
printf("%ld\n", maxcat(8, 1, 34, 3, 98, 9, 76, 45, 4));
printf("%ld\n", maxcat(4, 54, 546, 548, 60));
return 0;
}</lang>
 
{{out}}
 
<pre>998764543431
6054854654</pre>
 
=={{header|Perl 6}}==