5
\$\begingroup\$

You have been employed by a data analysis company, and have been appointed the task of finding the average character of a string of characters. However, this company has limited funding for code storage, so your code must be as small as possible.

Task

Write a program or function that takes one string of characters as input, and outputs the average character of that string.

Calculation of average

The average character of a string is the sum of the ASCII values of the individual characters divided by the total number of characters, then converted back to an ASCII character.
For example, the string cat consists of the sequence 99 97 116 of ASCII values. These values summed equals 312, which then divided by 3 gives an average of 104. 104 represents the ASCII character h. The average character of the string cat is therefore h.

Rules

  • You can assume the input string will only contain printable ASCII characters
  • If the average of the string's ASCII values is floating point, it should be rounded to the nearest integer and then converted to the equivalent ASCII character (eg. an average of 66.4 would output B, and an average of 66.5 would output C)
  • Input can be from STDIN (or language equivalent), or as a function parameter
  • Output must be to STDOUT (or language equivalent), or as a return result if your program is a function
  • Standard loopholes are not allowed
  • This is , so shortest code in bytes wins

Examples

Input → average → output
Hello, world!89.3076923076923Y
Code golf92.77777777777777]
811201550.571428571428573

\$\endgroup\$
0

16 Answers 16

8
\$\begingroup\$

Matlab, 23,21 16 bytes

I think this is quite obvious, if you know that matlab handles strings as arrays of characters, which can be treated like integers, aparently rounding occurs automatically when concatenated with a string.

@(s)[mean(s),'']
\$\endgroup\$
6
\$\begingroup\$

Julia, 41 bytes

With help from @AlexA.

a->Char(round(Int,mean([Int(i)for i=a])))

(Older version only worked in Julia 0.3.)

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

JavaScript ES6, 87 82 81 79 bytes

f=s=>String.fromCharCode([...s].reduce((r,c)=>r+c.charCodeAt(),0)/s.length+.5);

Thanks ETHproductions for the time to shorten by 5 bytes. Thanks rink.attendant for a byte less. Thanks Vihan for another 2 bytes.

\$\endgroup\$
5
  • \$\begingroup\$ You can save to byte by removing the function declaration f= at the beginning. You can also save two bytes by using two backticks `, instead of (''). You can save one byte by omitting the 0 in charCode At also \$\endgroup\$
    – Downgoat
    Nov 7, 2015 at 17:48
  • \$\begingroup\$ Nice work! To go along with Vɪʜᴀɴ, [...s] works in place of s.split(''). \$\endgroup\$ Nov 7, 2015 at 17:50
  • \$\begingroup\$ Oh hey, I like the +.5|0 in place of Math.round(). I wonder why I've never thought of that... +1 \$\endgroup\$ Nov 7, 2015 at 18:05
  • \$\begingroup\$ I believe you can omit the 0 argument from String.prototype.charCodeAt \$\endgroup\$ Nov 7, 2015 at 18:16
  • \$\begingroup\$ You also don't need the |0 in +.5|0, String.formCharCode will automatically do that \$\endgroup\$
    – Downgoat
    Nov 7, 2015 at 18:42
3
\$\begingroup\$

CJam, 11 bytes

q_1b\,d/moc

Test it here.

Explanation

q    e# Read input.
_1b  e# Duplicate and get the ASCII sum by treating the character codes as base-1 digits.
\,   e# Swap with other copy and get its length.
d/   e# Convert to float and divide.
mo   e# Round to nearest integer.
c    e# Convert to character.
\$\endgroup\$
3
\$\begingroup\$

Vitsy, 11 Bytes

This was what this was MADE for.

IVzV1-\+V/O
I           Get the length of the input stack.
 V          Save it as the final global variable, popping it.
  z         Push the input stack to the program stack.
   V1-\     Repeat the next item global variable size - 1.
       +    Add the top two items. This adds up everything.
        V/  Divide by the global variable.
          O Output as a character.
\$\endgroup\$
2
\$\begingroup\$

Pyth, 9 bytes

C.R.OCMz0

Try it online.

\$\endgroup\$
1
\$\begingroup\$

Mathematica, 47 bytes

FromCharacterCode@Round@Mean@ToCharacterCode@#&

or using composition:

FromCharacterCode@*Round@*Mean@*ToCharacterCode

String handling in Mathematica is such a joy...

\$\endgroup\$
1
\$\begingroup\$

K5, 16 bytes

{`c$.5+(+/x)%#x}

The phrase {(+/x)%#x} is a classic K idiom for calculating an arithmetic mean, and in K5 characters naturally coerce to numbers with no special work. `c$.5+ handles rounding and converting the result back into a character.

In action:

  {`c$.5+(+/x)%#x}'("Hello, world!";"Code golf";"8112015")
"Y]3"
\$\endgroup\$
1
\$\begingroup\$

TeaScript, 14 bytes

ÇU(x¿lÅ)x¡/xn©

Probably can be golfed using a reduce

Ungolfed

C(U(xs``.m(#lc())x()/xn))

C(       // Char from code from...
  U(      // Round
    xs``   // Split input
    .m(#   // Map over input
        lc()  // get char code
    ).x()  // Sum up array
    /xn    // Divided by input length
  )
)
\$\endgroup\$
0
1
\$\begingroup\$

Python 3, 48 Bytes

Straightforward solution with an anonymous lambda function.

lambda k:chr(int(round(sum(map(ord,k))/len(k))))
\$\endgroup\$
1
\$\begingroup\$

Ruby, 46 45 characters

->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}

Sample run:

2.1.5 :001 > ->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}['Hello, world!']
 => "Y"

2.1.5 :002 > ->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}['Code golf']
 => "]"

2.1.5 :003 > ->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}['8112015']
 => "3"
\$\endgroup\$
0
\$\begingroup\$

Japt, 31 27 bytes

Ua r(X$,$Y =>Xc +Yc)/Ul)r d

Try it in the Stack Snippet interpreter! (Arrow functions require ES6-compliant browser, e.g. Firefox.)

How it works

            // Implicit: U = input string
Ua          // Split U into chars.
r(X$,$Y =>  // Reduce the result by:
Xc +Yc      //  summing the char codes.
/Ul)        // Divide the result by the original string's length.
r d         // Round the result and turn back into a character.
            // Implicit: output last expression

(Side note: c works as .charCodeAt on strings and Math.ceil on numbers. The first time reduce is run, it will be between two strings, so Xc is necessary, but has no effect on the rest of the reducing.)

This is still much longer than it should be. The summing is 17 bytes when it could be 5 or so. Here's a 14-byte version I'd like to get working in the interpreter:

Uamc)r+ /Ul)rd
Uamc)          // Split input into chars, then replace each with its char code.
     r+        // Reduce the result with operator +. Equivalent to summing the array.
        /Ul)   // Divide the sum by the original string's length.
            rd // Round and turn into a character.
\$\endgroup\$
0
\$\begingroup\$

CoffeeScript, 94 bytes

f=(x)->String.fromCharCode Math.round x.split('').reduce(((p,v)->p+v.charCodeAt 0),0)/x.length
\$\endgroup\$
0
\$\begingroup\$

Ruby, 48

->s{t=0.0;s.bytes{|i|t+=i};(t/s.size).round.chr}
\$\endgroup\$
0
0
\$\begingroup\$

PowerShell, 60 Bytes

param([char[]]$a)$a|%{$b+=[int]$_};[char][int]($b/$a.Length)

Nothing esoteric. Takes input string param(..) and casts it as a char[]. Iterates over that array $a|%{..}, and each iteration adds the int value of that character to our accumulator $b. Then takes the average, casts it as int (which does implicit rounding to the nearest integer), then casts as a char for output. Since that's left on the pipeline, output is implicit.

\$\endgroup\$
0
\$\begingroup\$

Haskell, 74 69 bytes

s x=toEnum$round$(fromIntegral.sum.map fromEnum$x)/(foldr(\_ y->y+1)0x)

Pretty straightforward. A good chunk of the length is due to the fact that we can't apply the floating-point division operator (/) to integral types and that besides we need to round so we can't take advantage of the integral division's truncating behaviour.

P.S. : Shaved off 5 bytes by using a fold to avoid the second fromIntegral. Interestingly, replacing the dividend by a fold gives a longer program, probably because you need the fromIntegral there.

\$\endgroup\$

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