Description
In this challenge, you need to write a function that takes in a list of strings and returns the smallest string based on their ASCII value. You should assume that the input list contains only lowercase alphabetical strings.
Test Cases
["a", "b", "c"] => "a"
["hello", "world", "code"] => "code"
["aaa", "aa", ""] => ""
["cat", "bat", "rat"] => "bat"
["zab", "xyz", "abcd"] => "zab"
Write the function in as few bytes as possible. The code itself can be a function, process or anything provided that it gives the desired output. Use of other ASCII characters like big or small letters, with space function must be supported.
29 Answers 29
Java (JDK), 57 bytes
l->l.stream().min((a,b)->a.chars().sum()-b.chars().sum())
Takes input as a List<String>
and returns an Optional<String>
.
BQN, (削除) 18 (削除ここまで) 16 bytes
-2 from Dominic van Essen for replacing '0'
with @
.
{x⊑ ̃⊑⍒(+ ́@⊸-) ̈x}
Explanation
{x⊑ ̃⊑⍒(+ ́@⊸-) ̈x}
{ ̈x} 1. For each string in the (monadic) input x
{ ( @⊸-) } 2a. convert the string to (negative) its unicode representation...
{ (+ ́ ) } 2b. and perform a sum reduction.
{ ⍒( ) } 3. return descending-sorted indices.
{ ⊑ } 4. take the first.
{x⊑ ̃ } 5. take this index into the input x where ̃ "flips" the next function.
-
1\$\begingroup\$ Save 2 bytes by changing
'0'
to@
... \$\endgroup\$Dominic van Essen– Dominic van Essen2023年03月18日 09:41:38 +00:00Commented Mar 18, 2023 at 9:41 -
\$\begingroup\$ Cheers, I didn't know about
@
:s \$\endgroup\$Jacobus Smit– Jacobus Smit2023年03月19日 16:47:32 +00:00Commented Mar 19, 2023 at 16:47
Vyxal, (削除) 5 (削除ここまで) 4 bytes
‡C∑P
-1 thanks to @mathcat
Explanation
‡C∑P # Implicit input
‡ P # Minimum by:
C # ASCII values
∑ # Sum
# Implicit output
Old:
C∑)ṡh # Implicit input
)ṡ # Sort by:
C # ASCII values
∑ # Sum
h # First item
# Implicit output
-
-
\$\begingroup\$ @mathcat thanks, updated \$\endgroup\$The Thonnu– The Thonnu2023年03月03日 17:32:32 +00:00Commented Mar 3, 2023 at 17:32
C (gcc), 92 bytes
f(s,t,u,i,c)char**s,*t,*u;{for(i=~0,u=0;t=*s;c<i+0U?u=*s,i=c:0,s++)for(c=0;*t;c+=*t++);s=u;}
Ungolfed:
f(s,t,u,i,c)char**s,*t,*u;{
for(i=~0, // initialize minimum string sum to largest possible
u=0; // initialize smallest string (in case of empty list)
t=*s; // scan list
c<i+0U?u=*s,i=c:0, // reset minimum string sum and pointer if smaller
s++)
for(c=0;*t;c+=*t++); // get string sum
s=u; // return smallest string
}
Raku, 17 bytes
*.min(*.ords.sum)
*.ords.sum
is an anonymous function that calculates the sum of the ordinal values of its string argument. That function is passed as the argument to *.min
, which returns the element of the input list with the smallest value computed by the first function.
-
\$\begingroup\$ Your explanation seems to break off at a \$\endgroup\$Dominic van Essen– Dominic van Essen2023年03月18日 14:50:55 +00:00Commented Mar 18, 2023 at 14:50
-
\$\begingroup\$ Huh! Fixed. Dunno how that happened. \$\endgroup\$Sean– Sean2023年03月18日 17:38:25 +00:00Commented Mar 18, 2023 at 17:38
Swift, (削除) 64 (削除ここまで) 69 bytes
Now with fewer compiler crashes!
{0ドル.map{(0ドル.reduce(0){0ドル+Int(1ドル.asciiValue!)},0ドル)}.min{0ドル.0<1ドル.0}!.1}
-
\$\begingroup\$ The original version only worked for short strings; after more than a couple characters, it would overflow the limit for
UInt8
. However, when you hardcode the input, constant-folding causes this overflow to happen at compile-time, an the compiler crashes. \$\endgroup\$Bbrk24– Bbrk242023年03月03日 16:49:56 +00:00Commented Mar 3, 2023 at 16:49
Python, 44 bytes
lambda l:min(l,key=lambda x:sum(map(ord,x)))
Commented
lambda l: # Anonymous function taking l, a list of strings
min(l, ) # Return the minimum of l...
key= # ...using the following function:
lambda x: # Function taking x, a string
sum( ) # Sum the following:
map(ord,x) # Convert all characters to ASCII values
JavaScript (Node.js), 59 bytes
a=>a.sort(g=(x,y)=>x>=x&&~~eval(Buffer(x).join`+`)-g(y))[0]
Commented
a => // a[] = input array
a.sort(g = // g is a recursive callback function
(x, y) => // for each pair (x, y) to be tested:
x >= x && // stop if x is undefined
~~eval( // otherwise, evaluate as JS code:
Buffer(x) // the ASCII codes of x
.join`+` // joined with '+'
) // end of eval()
- g(y) // subtract the result of a recursive call with x = y
) // end of sort()
[0] // keep the first entry
Excel, 78 bytes
=LET(x,A1#,y,ROW(A:A),@SORTBY(x,MMULT(TOROW(y^0),IFERROR(CODE(MID(x,y,1)),))))
where A1#
is a horizontal spilled range containing the strings.
-
\$\begingroup\$ In theory I thought
=@SORTBY(A1#,MAP(A1#,LAMBDA(x,SUM(IFERROR(CODE(MID(x,ROW(A:A),1)),)+1))))
for 73 bytes would work. Using the implicit intersection operator should return the top-left cell. However, it's either bugged or not working as I expected. \$\endgroup\$JvdV– JvdV2023年03月06日 14:37:15 +00:00Commented Mar 6, 2023 at 14:37
Zsh +old utils, 47 (削除) 55 (削除ここまで) (削除) 103 (削除ここまで) bytes
Using the filesystem and the old System V sum
* command:
for i;echo $i>$[++n];set `sum -s *|sort -n`;<3ドル
Try it online!
(削除) 55 bytes (削除ここまで)
* On MacOS, cksum -o2
is equivalent to GNU sum -s
. According to Wikipedia, the BSD checksum algorithm is "useless from a security perspective" 😛
103 bytes, using arrays and builtins only:
for x;{w=;for a (${(s::)${x:?}})((w+=#a));k+=($w)}
for i ({1..$#})((k[i]==$(printf ${(n)k})))&&<<<$@[i]
Try it online!
Explanation of code is in earlier revisions of this answer
Stax, (削除) 9 (削除ここまで) 5 bytes
And pure ASCII!
{|+}e
Run and debug it (with test cases)
Explanation
{ }e # minimum by
|+ # sum
janet, 51 bytes
(fn[l](((sort-by first(map(fn[x][(sum x)x])l))0)1))
in janet, you can save bytes by not using spaces between brackets, which i personally think is very ugly for a lisp-like language, so here's an de-uglified version and an example
(fn [l] (((sort-by first (map (fn [x] [(sum x) x]) l)) 0) 1))
$ janet
Janet 1.29.1-20230709 openbsd/x64/clang - '(doc)' for help
repl:1:> (def F (fn[l](((sort-by first(map(fn[x][(sum x)x])l))0)1)))
<function 0x028B13B5F580>
repl:2:> (F ["zab" "xyz" "abcd"])
"zab"
Pip, (削除) 12 (削除ここまで) 10 bytes
@Y$+A*_SKg
-2 thanks to @DLosc
Explanation
@Y$+A*_SKg ; Input on command line
g ; Input list
SK ; Sorted by:
$+ ; Sum of
A* ; ASCII values of
_ ; The string
@Y ; First item (minimum)
; Implicit output
-
\$\begingroup\$ Just noticing this answer a year later... you can save two bytes on the function by using a lambda expression
$+A*_
. \$\endgroup\$DLosc– DLosc2024年03月06日 07:29:42 +00:00Commented Mar 6, 2024 at 7:29
Perl 5 + -pl
, 49 bytes
($_)=sort{unpack($x="%32A*",$a)-unpack$x,$b}$_,<>
Explanation
sort
s a list of the current input ($_
) and the remaining lines of input (<>
) based on the value of unpack
ing the string using "exotic templates", having the first index of the result re-assigned to $_
to be implicitly -p
rinted.
R, (削除) 50 (削除ここまで) 47 bytes
- -3 bytes by pajonk
which.min(Map(\(x)sum(utf8ToInt(x)),scan(,"")))
This outputs a named vector with the smallest value string as the name and the value is the string's position in the input list. If this is against the rules, then the following code for 7 bytes more will provide the clean output: names(which.min(Map(\(x)sum(utf8ToInt(x)),scan(,""))))
-
1
Retina 0.8.2, 74 bytes
.
$&$&96$*~
0T1`l`L`\w\w
{`[J-Z]
9$&
}T`_L`dL
\d
$*~
+`(\w)~
~1ドル
O`
1G`
~
Try it online! Only accepts strings of lowercase letters. Explanation:
.
$&$&96$*~
Duplicate each letter and suffix 96 ~
s to each pair.
0T1`l`L`\w\w
Uppercase alternate letters.
{`[J-Z]
9$&
}T`_L`dL
Map uppercase letters into digits that sum to their index i.e. A=1
to Z=998
.
\d
$*~
Expand the digits into that many ~
s.
+`(\w)~
~1ドル
Move all of the ~
s to the beginning of the string.
O`
Sort the strings into order. Since ~
sorts after z
, this means that the string with the fewest ~
s will sort first.
1G`
Keep only the first string.
~
Delete the ~
s.
Charcoal, 15 bytes
UMθ⟦↨Eιc/oλ1ι⟧⊟⌊θ
Try it online! Link is to verbose version of code. Explanation:
UMθ⟦↨Eιc/oλ1ι⟧
Calculate the sum of ASCII values for each string.
⊟⌊θ
Output the string with the smallest sum.
-
\$\begingroup\$ Fairly certain the
b
isn't necessary: tio.run/##K6gsyfj/Xy@32Nk36f//aKWqxCQlHQWlisoqEJWYlJyiFAsA \$\endgroup\$hakr14– hakr142024年05月07日 14:16:39 +00:00Commented May 7, 2024 at 14:16
BQN, (削除) 15 (削除ここまで) 14 bytes
⊑∘⍋∘(+ ́ ̈-⟜@)⊑⊢
⊑∘⍋∘(+ ́ ̈-⟜@)⊑⊢
( ̈ ) # for each element of input
-⟜@ # subtract the null character from each letter
# (thereby getting codepoint values)
+ ́ # and sum by fold-addition
⊑∘ # now get the first element of
⍋∘ # the indices of sorted elements
⊑ # and use this to select from
⊢ # the elements of the input
["zab", "xyz", "abcd"] => "zab"
\$\endgroup\$