25
\$\begingroup\$

Your task

Take a list of strings as the input, and output the maximum average ord.

Example

Given the list ['hello', 'world', 'bye']:

  • The average ord of 'hello' is:
    • (ord(h) + ord(e) + ord(l) + ord(l) + ord(o)) / len('hello')
    • = 106.4
  • The average ord of 'world' = 110.4
  • The average ord of 'bye' = 106.7

The maximum average ord is 110.4. This is your output.

Test cases

Note: For the last two test cases, I have given the roundings for 1, 2, and 3 decimal places. As mentioned in the rules below, you can round to any number of decimal places.

Input                                        Output
['hello', 'world', 'bye']                    110.4
['code', 'golf', 'stack', 'exchange']        106.8
['!@#', '$%^', '&*(']                        55.7 / 55.67 / 55.667 / etc.
['qwertyuiop[', 'asdfghjkl;', 'zxcvbnm,']    110.9 / 110.91 / 110.909 / etc.

Rules/clarifications

  • The output must be only the average ord. You may not output anything else.
  • It may be rounded (up or down) to any number (\$\ge\$ 1) of decimal places. If your language does not support floating points, you may output the average multiplied by 10.
  • Floating point innacuracies are ok.
  • You may assume that the input list will always have a length of 2 or more
  • You may assume that the strings will never be empty
  • You may assume that the strings will not contain whitespace or non-ASCII characters
  • This is , so shortest code in bytes wins!
\$\endgroup\$
10
  • \$\begingroup\$ Sandbox \$\endgroup\$
    – The Thonnu
    Nov 5, 2022 at 13:52
  • 1
    \$\begingroup\$ @Arnauld - oops, I forgot that wasn't an ASCII character. I've changed the test case. \$\endgroup\$
    – The Thonnu
    Nov 5, 2022 at 14:00
  • \$\begingroup\$ If you allow ≥0 decimal places, then languages that work only with integers would be able to compete, too. Or, as an alternative, could one output the average times ten? \$\endgroup\$ Nov 5, 2022 at 14:03
  • 2
    \$\begingroup\$ @DominicvanEssen - for languages that don't have floating points, I'll allow outputting the average times 10. I'll edit that in now. \$\endgroup\$
    – The Thonnu
    Nov 5, 2022 at 14:04
  • 1
    \$\begingroup\$ What is ord or why does ord(h) + ord(e) + ord(l) + ord(l) + ord(o)) / len('hello') give 106.4? \$\endgroup\$
    – QBrute
    Nov 7, 2022 at 21:37

49 Answers 49

9
\$\begingroup\$

Pyth, 7 bytes

eSm.OCM

Test suite

Explanation:
eSm.OCM   | Full program
eSm.OCMdQ | with implicit variables
----------+-------------------------------
  m     Q | For each word in the input,
     CMd  |  Get the ord of each character
   .O     |  Get the average
eS        | Get the max
\$\endgroup\$
2
  • \$\begingroup\$ For the record, eS.OCMM also works for 7 bytes, though I'm not entirely sure why. \$\endgroup\$
    – hakr14
    Nov 5, 2022 at 20:21
  • 2
    \$\begingroup\$ eS.OCMM works because .O is implicitly vectorized: If it is called on a list of lists, it is mapped over the inner lists. Most functions in Pyth that would otherwise throw errors are implicitly vectorized. This is implemented in the unknown_types function in macros.py: github.com/isaacg1/pyth/blob/… \$\endgroup\$
    – isaacg
    Nov 7, 2022 at 19:00
7
\$\begingroup\$

Python, 46 bytes

lambda l:max(sum(map(ord,s))/len(s)for s in l)

Attempt This Online!

Unfortunately, the only built-in mean function Python has is in the statistics module, and that's too expensive to import.

\$\endgroup\$
7
\$\begingroup\$

K (ngn/k), 18 11 bytes

|/{+/x%#x}'

Try it online!

Massive -7 bytes golf thanks to Steffan!

Damn everyone is answering quick. Anyways here's my solution. Takes input as a list of strings.

Explanation:

|/{+/x%#x}'  Main function. Takes implicit input
          '  For each string in the input...
  {      }   Execute a function that...
   +/x       Takes sum of every character in the string
      %      And divide it by
       #x    The length of the string
|/           Get the maximum value
\$\endgroup\$
2
  • \$\begingroup\$ Max is just |/, and from there you can go pointfree: |/{+/x%#x}' \$\endgroup\$
    – naffetS
    Nov 5, 2022 at 20:33
  • \$\begingroup\$ In k4, avg is a built in so we can get it down to 6 bytes: |/avg' \$\endgroup\$ Nov 25, 2022 at 4:29
6
\$\begingroup\$

Wren, 68 bytes

Fn.new{|x|x.reduce(0){|y,z|y.max(z.bytes.reduce{|a,b|a+b}/z.count)}}

Try it

\$\endgroup\$
6
\$\begingroup\$

APL(Dyalog Unicode), 14 13 bytes SBCS

-1 bytes thanks to Adám

⌈/+⌿∘⎕UCS¨÷≢¨

Try it on APLgolf!

A tacit function which finds the maximum ord. Originally wrote a dfn, but I tried random stuff to convert it to tacit and it somehow worked out.

⌈/+⌿∘⎕UCS¨÷≢¨
          ¨              ⍝  for each element in the input...
     ⎕UCS               ⍝  convert the characters to their ascii values...
  +⌿∘                   ⍝  and sum the resulting ascii values...
           ÷             ⍝  divided by...
            ≢¨           ⍝  the length of each element...
⌈/                       ⍝  and take the maximum of that
\$\endgroup\$
5
\$\begingroup\$

><>, 80 51 48 bytes

0>0001.
$i:"!"(?v+$1+
(@:{:,$&/
v?(0&~$?/.02
\n;

Animated Version

Requires a extra space at the end of the input. Also assumes no 2 spaces in a row. (no 0 length words). Anything with ORD of 32 or lower is considered white-space.

Explanation

enter image description here

Top row: Push 3 0s on to the stack. The first is the current best ORD, the second is the length of the current word, and the last is the sum of the ord values of the current word. 01. is a jump to the next row.

The second row sums a word. If a character is less than "!" (char value 33) go down. Otherwise sum the word and increment the length. `$1+

In the third row, we fist push the last value to the register & . We use this to later check if this was the end of the string. Then we divide by the length to get the new ORD value. Then we use the :{:@ trick to copy the stack if it has only 2 elements (which is always the case) from the stack and compare them. If the new one is better we swap the stack with $. In either case we delete the top item.

Lastly, we take the value of the register and check if it is negative, &0(?. If so, we print the maximum ord and exit. If not, we jump back to 00. To get the correct direction we use the 00!.| trick.

\$\endgroup\$
5
\$\begingroup\$

><>, 65 45 44 40 bytes

000i:"!"(?v+$1+$20.
$~$0(?n00.>@$,:{:@(?

Try it online!

Takes input as a space separated string.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Welcome back! \o/ First post in 3 years :) \$\endgroup\$
    – naffetS
    Nov 9, 2022 at 1:14
4
\$\begingroup\$

Factor, 24 bytes

[ 0 [ mean max ] foldl ]

Attempt This Online!

Just fold with the max of the mean.

\$\endgroup\$
4
\$\begingroup\$

R, 38 bytes

\(x)max(sapply(Map(utf8ToInt,x),mean))

Attempt This Online!

               Map(utf8ToInt,x)        # for every string in the input, store the vector of its codepoints in a list
        sapply(                ,mean)  # apply mean to each of the list elements and return a vector
\(x)max(                             ) # take max
\$\endgroup\$
0
4
\$\begingroup\$

Jelly, 4 bytes

OÆmṀ

Try it online!

\$\endgroup\$
4
\$\begingroup\$

05AB1E, 10 9 4 bytes

ÇÅAà

-5 thanks to Sʨɠɠan

Try it online!

Explained:

ÇÅAà  # Implicit input as a list
      # Implicit map over the input:
Ç     #   Get the ord of each character
 ÅA   #   Get the average of the ords
   à  # Get the maximum value
\$\endgroup\$
4
  • 4
    \$\begingroup\$ I think that answering one's own challenge three times within 25 minutes of posting it is probably a record, although possibly not one that I'd encourage anyone to attempt to break... \$\endgroup\$ Nov 5, 2022 at 14:19
  • \$\begingroup\$ @DominicvanEssen I'll probably delete this one if someone comes up with a better 05AB1E solution. \$\endgroup\$
    – The Thonnu
    Nov 5, 2022 at 14:22
  • 1
    \$\begingroup\$ Why not just ÇÅAà? Ç is the same as εÇн} and everything vectorizes so you don't need any maps \$\endgroup\$
    – naffetS
    Nov 5, 2022 at 20:26
  • \$\begingroup\$ @Sʨɠɠan wow, I didn't know that was possible! \$\endgroup\$
    – The Thonnu
    Nov 5, 2022 at 20:57
4
\$\begingroup\$

Pip, 12 bytes

M:$+A*_/#_Mg

Try It Online!

\$\endgroup\$
4
\$\begingroup\$

Knight (v2), 56 bytes

;=mF;W=pP;=s!=i~1;W>Lp=i+1i=s+*10A Gp iTs&<m=t/sLp=m tOm

Try it online!

Because Knight doesn't support floating point values, it outputs the maximum average ord multiplied by \$10\$, as allowed by the rules:

It may be rounded to any number (\$\ge1\$) of decimal places. If your language does not support floating points, you may output the average multiplied by 10.

\$\endgroup\$
4
\$\begingroup\$

Julia, 34 bytes

!a=max(sum.(Int,a)./length.(a)...)

Attempt This Online!

\$\endgroup\$
1
  • \$\begingroup\$ -1 byte with @. \$\endgroup\$
    – MarcMush
    Mar 29, 2023 at 14:21
4
\$\begingroup\$

Excel (ms365), 70 bytes

enter image description here

Formula in F1:

=MAX(MAP(A1:C1,LAMBDA(a,SUM(CODE(MID(a,SEQUENCE(LEN(a)),1)))/LEN(a))))
\$\endgroup\$
1
  • \$\begingroup\$ you can get this down to 68 bytes if you expect input in array format (eg. ={"hello","world","bye"}) and use # to denote an array input (map(A1#,...) \$\endgroup\$ Nov 26, 2022 at 20:31
4
\$\begingroup\$

MathGolf, 4 bytes

$m▓╙

Input as a list of lists of characters.

Try it online.

Explanation:

$     # Get the codepoint of each inner-most character of the (implicit) input-list
 m    # Map over each list of integers:
  ▓   #  Pop and push the average of the list
   ╙  # After the map: pop and push the maximum
      # (after which the entire stack is output implicitly as result)
\$\endgroup\$
4
\$\begingroup\$

J, 18 bytes

[:>./(1#.3&u:%#)&>

Accepts list of boxed strings

Attempt This Online!

[:>./(1#.3&u:%#)&>
[:                  NB. cap, [: f g y -> f (g y)
                &>  NB. for each input item, result will be unboxed
     (         )    NB. monadic fork
              #     NB. length
         3&u:       NB. convert input to list of char codes
             %      NB. vectorized division
      1#.           NB. sum the result to compute average
  >./               NB. max item
\$\endgroup\$
4
\$\begingroup\$

PHP 8.x, 75 73 bytes

Creates an anonymous function that returns the expect values, hopefully.

fn($x)=>max(array_map(fn($z)=>array_sum(unpack('C*',$z))/strlen($z),$x));

-2 bytes thanks to Sʨɠɠan.

How does it work?

This uses the unpack('C*', ...) function to convert all characters into an unsigned char (0-255).
This assumes all characters are part of the ASCII table.

Then it calculates the average using array_sum([...])/strlen([...]).
The function array_sum() takes an array and returns the sum of all elements, and strlen() returns the length of the string.

The function max() takes the array with the averages and returns the highest value from it.

Anonymous functions implicitly return values.

Example usage

You need to assign this to a variable, or call with call_user_func() or call_user_func_array():

<?php
$fn = fn($x)=>max(array_map(fn($z)=>array_sum(unpack('C*',$z))/strlen($z),$x));

// Should output: float(110.4)
var_dump($fn(['hello', 'world', 'bye']));

You can try this here (with test examples): https://onlinephp.io/c/2a424

\$\endgroup\$
2
  • 1
    \$\begingroup\$ fn($x)=>max(array_map(fn($z)=>array_sum(unpack('C*',$z))/strlen($z),$x)); saves two bytes. Also you don't need to count the semicolon \$\endgroup\$
    – naffetS
    Nov 5, 2022 at 20:41
  • 1
    \$\begingroup\$ ... How dumb of me to forget to use the string length ... Thank you! I count the semicolon, as it is a required part of the arrow function. \$\endgroup\$ Nov 5, 2022 at 22:10
4
\$\begingroup\$

MATLAB, 39 31 bytes

@(s)max(cellfun(@(x)mean(x),s))

Matlab unfortunately doesn't convert strings ("") directly to ASCII values using the double function, and if converted to char type then a string array will be padded with spaces to make a proper matrix. As a result, the input is a cellstr type, which needs to be looped over using the cellfun function with an anonymous function that takes the average of the unicode values of the strings (''). The output is then the maximum of those values.

Try it online!

edit: -8 bytes thanks to Guiseppe

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I think the (implicit) type conversion +x should work and be shorter than double(x), at least in Octave: try it online \$\endgroup\$
    – Giuseppe
    Nov 8, 2022 at 16:28
4
\$\begingroup\$

T-SQL, 125 bytes

WITH C as(SELECT len(x)m,0b,*FROM @
UNION ALL SELECT m-1,b+ascii(right(x,m)),x
FROM C WHERE
m>0)SELECT max(b*1./len(x))FROM c

Try it online

\$\endgroup\$
4
\$\begingroup\$

Raku, 27 bytes

*».&{.ords.sum/.chars}.max

Try it online!

Edit: as per advice from @Steffan

\$\endgroup\$
5
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$
    – naffetS
    Nov 14, 2022 at 19:45
  • \$\begingroup\$ This is actually 26 bytes (25 characters), since we count in bytes \$\endgroup\$
    – naffetS
    Nov 14, 2022 at 19:46
  • \$\begingroup\$ We don't allow hardcoding the input into the code - the best way to take input in Raku is via a function. This only costs one byte, you can just add a * at the beginning to make it a WhateverCode block. :) Try it online! \$\endgroup\$
    – naffetS
    Nov 14, 2022 at 19:47
  • \$\begingroup\$ @Steffan : Thanks and amended as per your advice. \$\endgroup\$
    – hkdtam
    Nov 15, 2022 at 13:49
  • \$\begingroup\$ .chars can be .comb or .ords for -1. I was trying to figure out a way of using a HyperWhatever, but I couldn't find something shorter \$\endgroup\$
    – Jo King
    Dec 19, 2022 at 13:01
3
\$\begingroup\$

Vyxal G, 3 bytes

Cvṁ

Try it Online!

\$\endgroup\$
3
\$\begingroup\$

Ruby, 48 bytes

->l{l.map{_1.chars.sum(&:ord)/_1.size.to_f}.max}

As the division of two integers in ruby gives an integer, and what was expected was a float, it's long :/
And .fdiv is one byte longer

Attempt This Online!

\$\endgroup\$
3
  • \$\begingroup\$ 40 bytes: ->l{l.map{1.0*_1.bytes.sum/_1.size}.max} \$\endgroup\$
    – naffetS
    Nov 5, 2022 at 20:45
  • \$\begingroup\$ @Dingus, I think string sum won't work, as it wraps around with modulo, so it may pass given test cases, but not some big string \$\endgroup\$
    – Kirill L.
    Nov 6, 2022 at 9:18
  • \$\begingroup\$ @KirillL. Thanks for pointing that out. You are right. I should've read the docs! \$\endgroup\$
    – Dingus
    Nov 6, 2022 at 10:15
3
\$\begingroup\$

Sequences, \$9 \log_{256}(96) \approx 7.41\$ bytes

[$v$aH]gM

Explanation

[$v$aH]gM  // Implicit list of string input
[     ]    // Loop through the input list:
 $v$       //   Get a list of ords of each character
    aH     //   Get the average and append to `g`
       g   // Push the list `g`
        M  // Get the maximum value
           // Implicit output

Screenshot

\$\endgroup\$
3
\$\begingroup\$

Mathematica, 29 bytes

Max[Mean/@ToCharacterCode@#]&

View it on Wolfram Cloud!

\$\endgroup\$
3
\$\begingroup\$

Fig, \$6\log_{256}(96)\approx\$ 4.939 bytes

]KemMC

Try it online!

]KemMC
     C - Charcodes
  emM  - Mean of each
 K     - Sort
]      - Last
\$\endgroup\$
5
  • \$\begingroup\$ When maximum is two bytes long \$\endgroup\$
    – naffetS
    Nov 5, 2022 at 20:50
  • \$\begingroup\$ what do you mean \$\endgroup\$
    – Seggan
    Nov 6, 2022 at 21:56
  • \$\begingroup\$ ]K should be one byte \$\endgroup\$
    – naffetS
    Nov 6, 2022 at 23:43
  • \$\begingroup\$ Ah yes. Pu that on my todo list \$\endgroup\$
    – Seggan
    Nov 7, 2022 at 2:42
  • 1
    \$\begingroup\$ Lol.. Didn't knew there were two of you: Sʨɠɠan and Sʨɠɠan. The conversation in the comments above is pretty confusing if it would be only a single person. xD \$\endgroup\$ Nov 10, 2022 at 13:34
3
\$\begingroup\$

Java 8, 81 79 56 bytes

a->a.mapToDouble(s->s.chars().average().orElse(0)).max()

Input as a Stream<String> and output as an OptionalDouble.

Try it online.

Explanation:

a->                  // Method with String-Stream parameter & OptionalDouble return-type
   a.map             //  Map over the input-Stream
        ToDouble(s-> //  and convert them to a Stream of Doubles
      s.chars()      //   Convert the String to an IntStream of its codepoint integers
       .average()    //   Then take the average of that IntStream (as OptionalDouble)
       .orElse(0))   //   And convert the OptionalDouble to double
                     //   (`.orElse(0)` is shorter than `.getAsDouble()`)
    .max()           //  After the map: leave the maximum (again as OptionalDouble)
\$\endgroup\$
3
\$\begingroup\$

BQN, 13 12 bytes

-1 byte inspired by Aiden Chow's APL answer

⌈´+´∘-⟜@¨÷≠¨

Anonymous tacit function; takes a list of strings and returns a float. Try it at BQN online!

Explanation

⌈´+´∘-⟜@¨÷≠¨
          ≠¨  Length of each string
         ÷    Divide the following by the above:
  +´∘           Sum of
     -⟜@       Subtract null character from (each character in)
        ¨       Each string
⌈             Get the maximum of the resulting list of averages
\$\endgroup\$
3
\$\begingroup\$

Go, 132 108 bytes

func f(S[]string)(m int){for a,s:=range S{a=0
for _,r:=range s{a+=int(r)}
if a=a*10/len(s);a>m{m=a}}
return}

Attempt This Online!

  • -24 bytes by @Sʨɠɠan: return as an int, multiplied by 10
\$\endgroup\$
2
  • \$\begingroup\$ 108 (returns multiplied by 10) \$\endgroup\$
    – naffetS
    Nov 8, 2022 at 17:44
  • \$\begingroup\$ I think that is only valid for languages that doesn't support floating point operations. \$\endgroup\$
    – jdt
    Nov 10, 2022 at 16:58
3
\$\begingroup\$

Japt -h, 9 bytes

Takes input as an array of character arrays.

®xc /ZlÃñ

Try it

®xc /ZlÃñ     :Implicit input of 2D array of characters
®             :Map each sub-array Z
 x            :  Reduce by addition of
  c           :    Codepoints
    /         :  Divide by
     Zl       :    Length of Z
       Ã      :End map
        ñ     :Sort
              :Implicit output of last element
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.