Given a nonempty list of positive decimal integers, output the largest number from the set of numbers with the fewest digits.
The input list will not be in any particular order and may contain repeated values.
Examples:
[1] -> 1
[9] -> 9
[1729] -> 1729
[1, 1] -> 1
[34, 3] -> 3
[38, 39] -> 39
[409, 12, 13] -> 13
[11, 11, 11, 1] -> 1
[11, 11, 11, 11] -> 11
[78, 99, 620, 1] -> 1
[78, 99, 620, 10] -> 99
[78, 99, 620, 100] -> 99
[1, 5, 9, 12, 63, 102] -> 9
[3451, 29820, 2983, 1223, 1337] -> 3451
[738, 2383, 281, 938, 212, 1010] -> 938
The shortest code in bytes wins.
-
\$\begingroup\$ Can the input numbers be on separate lines? \$\endgroup\$seshoumara– seshoumara2016年09月16日 05:48:10 +00:00Commented Sep 16, 2016 at 5:48
-
\$\begingroup\$ @seshoumara That sounds reasonable, yes. \$\endgroup\$Calvin's Hobbies– Calvin's Hobbies2016年09月16日 05:48:31 +00:00Commented Sep 16, 2016 at 5:48
68 Answers 68
Perl, (削除) 38 (削除ここまで) 37 bytes
Includes +1 for -a
Give input on STDIN:
perl -M5.010 maxmin.pl <<< "3451 29820 2983 1223 1337"
maxmin.pl:
#!/usr/bin/perl -a
\$G[99-y///c][$_]for@F;say$#{$G[-1]}
Uses memory linear in the largest number, so don't try this on too large numbers. A solution without that flaw is 38 bytes:
#!/usr/bin/perl -p
$.++until$\=(sort/\b\S{$.}\b/g)[-1]}{
All of these are very awkward and don't feel optimal at all...
PowerShell v2+, 41 bytes
($args[0]|sort -des|sort{"$_".length})[0]
Takes input $args, sorts it by value in -descending order (so bigger numbers are first), then sorts that by the .length in ascending order (so shorter lengths are first). We then take the [0] element, which will be the biggest number with the fewest digits.
Examples
PS C:\Tools\Scripts\golfing> @(78,99,620,1),@(78,99,620,10),@(78,99,620,100),@(1,5,9,12,63,102),@(3451,29820,2983,1223,1337),@(738,2383,281,938,212,1010)|%{($_-join',')+" -> "+(.\output-largest-number-fewest-digits.ps1 $_)}
78,99,620,1 -> 1
78,99,620,10 -> 99
78,99,620,100 -> 99
1,5,9,12,63,102 -> 9
3451,29820,2983,1223,1337 -> 3451
738,2383,281,938,212,1010 -> 938
-
\$\begingroup\$ Quick improvement to 36 bytes \$\endgroup\$Veskah– Veskah2021年07月26日 13:55:48 +00:00Commented Jul 26, 2021 at 13:55
C# (85 bytes)
It's a full function:
int y(int[] t) {int m=t.Min(i=>(i+"").Length);return t.Max(n=>(n+"").Length==m?n:0);}
Unriddled:
int y(int[] t)
{
int m = t.Min(i => (i+"").Length);
return t.Max(n => (n+"").Length == m ? n : 0);
}
-
\$\begingroup\$ There's an useless whitespace after you function signature and in the parameter list. Lambda statement should also work. \$\endgroup\$Yytsi– Yytsi2016年09月17日 17:21:42 +00:00Commented Sep 17, 2016 at 17:21
R, (削除) 72 (削除ここまで) (削除) 41 (削除ここまで) 36 bytes
Rewrote the function with a new approach. Golfed 5 bytes thanks to a suggestion from @bouncyball.
n=nchar(i<-scan());max(i[n==min(n)])
Explained:
i<-scan() # Read input from stdin
n=nchar( ); # Count the number of characters in each number in i
max( ) # Return the maximum of the set where
i[n==min(n)] # the number of characters is the minimum number of characters.
(削除)
function(i){while(1){if(length(o<-i[nchar(i)==T]))return(max(o));T=T+1}}
Indented/explained:
function(i){ # Take an input i
while(1){ # Do the following continuously:
if(length(
o<-i[nchar(i)==T]) # Define o to be the subset of i with numbers of length T,
) # where T is 1 (a built-in!).
# We take the length of this subset (its size), and then pass
# it to if(). Thanks to weak typing, this numeric is converted
# to a logical value. When this occurs, zero evaluates to FALSE
# and any non-zero number evaluates to TRUE. Therefore, the if()
# is TRUE iff the subset is not empty.
return(max(o)); # If it's true, then we just return the largest element of the
# subset, breaking out of our loop.
T=T+1 # Otherwise, increment our counter and continue.
}
}
(削除ここまで)
-
1\$\begingroup\$ Save 4 bytes by not defining
function:i=scan();n=nchar(i);max(i[n==min(n)])\$\endgroup\$bouncyball– bouncyball2016年09月16日 14:13:49 +00:00Commented Sep 16, 2016 at 14:13 -
\$\begingroup\$ @bouncyball Thanks! And 1 further byte saved by
n=nchar(i<-scan()). \$\endgroup\$rturnbull– rturnbull2016年09月16日 19:32:23 +00:00Commented Sep 16, 2016 at 19:32
C# 85 bytes
int S(int[] i){var m=i.Min();return i.Where(v=>v<m*10&&$"{v}{m}".Length%2==0).Max();}
Usage:
Console.WriteLine(S(new[] { 738, 2383, 281, 938, 212, 1010 }));
Output: 938
Explanation
Get the minimum value from the array and assume that the minimum value is the value with the shortest length.
Filter the array to remove all values greater than 10 * the minimum. i.e if the value is 8, the first check removes all values greater than 80.
Also filter to remove all values where the length of the combined string is odd. "8" + "9" is length 2 which is even, "8" + "10" is length 3 which is odd and eliminated.
int S(int[] i)
{
var m = i.Min();
return i.Where(v => v < m * 10 && $"{v}{m}".Length % 2 == 0).Max();
}
-
\$\begingroup\$
int[]iwill work. \$\endgroup\$Yytsi– Yytsi2016年09月17日 17:22:55 +00:00Commented Sep 17, 2016 at 17:22
Python 2 - 41 bytes
lambda l:max((-len(`x`),x) for x in l)[1]
Racket 148 bytes
(λ(l)(define l2(map number->string l))(apply max(map string->number
(filter(lambda(x)(eq?(string-length x)(apply min(map string-length l2))))l2))))
Testing:
(f (list 1 5 9 12 63 102))
Output:
9
Detailed version:
(define (f sl)
(define sl2 (map number->string sl))
(apply max
(map string->number
(filter (lambda(x)
(equal? (string-length x)
(apply min (map string-length sl2))
)) sl2))))
SQLite, 49 bytes
SELECT n FROM a ORDER BY length(n),n DESC LIMIT 1
Of course only if the list is allowed to be in a table. The type of the field should be INTEGER.
C++11, 109 bytes
[](auto a){sort(a.begin(),a.end(),[](auto x,auto y){return (int)log10(x)<=(int)log10(y)&&x>y;});return a[0];}
a should be a container like vector or list. E.g. (lambda as f)
cout<<f(vector<int>{ 10, 13, 19, 100, 12200 });
Common Lisp, 136 bytes
Golfed:
(defun o(&rest r &aux(s(sort r '<)))(flet((f(x)(floor(log x 10))))(apply 'max(remove-if(lambda(x)(<(apply 'min(mapcar 'f s))(f x)))s))))
Ungolfed:
(defun o (&rest r
&aux (s (sort r '<)))
(flet ((f (x) (floor (log x 10))))
(apply 'max
(remove-if (lambda (x)
(< (apply 'min (mapcar 'f s))
(f x)))
s))))
Coconut, 56 bytes
This is just a Coconut-ification of the best (currently only) Python 3 answer (as well as some of the other answers), so most of the credit should go to them. Any valid Python 3 is Coconut which means it's at most the same length. Also, Coconut compiles to Python.
lambda a:sorted(sorted(a),key=lambda x:-len(str(x)))[-1]
can be changed into ->sorted(sorted(_),key=->-len(str(_)))[-1]. This compiles to lambda _=None: sorted(sorted(_), key=lambda _=None: -len(str(_)))[-1] (along with a ton of other stuff like additional Coconut builtins).
-
\$\begingroup\$
⌈/⊢×((⌊/=⊢)≢∘⍕¨)works I think \$\endgroup\$rak1507– rak15072020年12月20日 21:05:50 +00:00Commented Dec 20, 2020 at 21:05
Jelly, 6 bytes
DL$ÐṂṀ
How it works
DL$ÐṂṀ - Main link. Takes a list L on the left
$ÐṂ - Take the elements of L for which the following is minimal:
DL - Digit Length
Ṁ - Maximum of those elements
Japt -h, 4 bytes
Input as an array of integer strings, output as an integer string.
üÊÎñ
üÊÎñ :Implicit input of array
ü :Group and sort by
Ê : Length
Î :First element
ñ :Sort
:Implicit output of last element
Vyxal, 5 bytes
((LN∵
How?
((LN∵
( # Next element as a lambda:
( # Apply both of the next two elements and wrap the results in a list:
L # Length...
N # ...and negate
∵ # Get the minimum of the input by that function
JavaScript (Node.js), 53 bytes
a=>a.reduce((N,n)=>~(L=Math.log10)(N)!=~L(n)^N>n?N:n)
Explanation
For any two values N,n, we need to decide which to return, this table describes that:
length
| < = >
---+-------
value < | N n .
= | . ? .
> | . N n
Where . will never happen and ? means either N or n works.
This looks a lot like an exclusive or (XOR) table:
A
| 0 1
---|-----
B 0 | 0 1
1 | 1 0
Where we XOR length(N) != length(n) with N > n. The cheapest way (I think) to get the length of a number in JS is using Math.log10, then flooring the result with a bitwise operator (in this case ~).
I also [ab]use the fact that ^ has lower operator precedence than comparisons.
Pascal (FPC), (削除) 169 (削除ここまで) 167 bytes
A function which takes variable array as input:
function m(a:array of integer):integer;var i:integer;begin m:=a[0];for i in a do if(int(log10(i))<int(log10(m)))or((int(log10(i))=int(log10(m)))and(i>m))then m:=i;end;
(Yes I know, pascal sucks at this, in addition there is no sort function in it's library..)
Thunno 2 hG, 3 bytes
Ṡñl
Thunno 2, 5 bytes
ṠñlhG
Explanation
ṠñlhG # Implicit input
Ṡ # Sort the input, so the minimum item is at the start
ñ # Group this sorted list by the following:
l # Length (for integers this is number of digits)
h # Get the first group (the minimum digits)
G # And get the maximum item in this group
# Implicit output
Red, 98 bytes
func[b][first sort/compare b func[a b][(j: to 1 log-10 a)<(k: to 1 log-10 b)or(j = k and(a > b))]]
Uiua, 16 bytes
⊣↙⊢▽⊸≠0°⊚⊸≡◇⧻°⋕⍆
Outputs a boxed string.
Try this in the pad!
+1 byte for outputting numbers.
⋕⊣↙⊢▽⊸≠0°⊚⊸≡◇⧻°⋕⍆
-
-
1
-
\$\begingroup\$ I know I can't compete with real golfing languages but I like it compared to something like Racket or Common Lisp 🤷🏻♀️ \$\endgroup\$Sandra– Sandra2025年11月04日 09:10:35 +00:00Commented Nov 4 at 9:10
Python 2, 58 bytes
def F(x):l={len(`i`):i for i in sorted(x)};print l[min(l)]
Python 3, 56 bytes
lambda a:sorted(sorted(a),key=lambda x:-len(str(x)))[-1]
Uses a lambda in a lambda!
Python 2, 53 bytes
s=lambda a:sorted(sorted(a),key=lambda x:-len(`x`))[-1]
Same but with backticks
Clojure, 63 bytes
(reduce #(if(=(quot %1 10)(quot %2 10))(max %1 %2) %1)(sort x))
as in:
(reduce #(if(=(quot %1 10)(quot %2 10))(max %1 %2) %1)(sort[3 7 121 11 8 2 10 9]))
=> 9
Though I'm sure there's a way to make it smaller.
PHP , 86 Bytes
<?$l=strlen($r=min($a=$_GET[a]));foreach($a as$v)if($v>$r&strlen($v)==$l)$r=$v;echo$r;