17
\$\begingroup\$

Introduction

Every letter in the English alphabet can be represented as an ASCII code. For example, a is 97, and S is 83. As we all know, the formula for averaging two numbers \$x\$ and \$y\$ is \$\frac{x+y}{2}\$. I'm pretty sure you can see where this is going. Your challenge is to average two letters.

Challenge

Your program must take two letters as input, and output the average of the ASCII values in it. If the average is a decimal, you should truncate it.

  • Input will always be two ASCII letters. You can assume they will always be valid, but the case may vary. Basically, both letters will be in the range 97-122 or 65-90. The second letter will always have a greater ASCII value than the first. If your language has no method of input, you may take input from command line arguments or from a variable.
  • You must output the ASCII character signified by the average of the two numbers. As stated above, it should always be truncated to 0 decimal places. If your language has no method of output, you may store it in a variable. Exit codes and return values are considered valid output methods.

Example I/O

  • Input: A, C
    Output: B
  • Input: a, z
    Output: m
  • Input: d, j
    Output: g
  • Input: B, e
    Output: S
  • Input: Z, a
    Output: ]

Rules

This is , so shortest answer in bytes wins!

\$\endgroup\$
5
  • 2
    \$\begingroup\$ Please specify whether, for example, B e is a valid input. \$\endgroup\$ Nov 10 '19 at 19:53
  • 4
    \$\begingroup\$ Why is the output of the last example U? The value of B is 66 and the value of e is 101, which averages to 83.5, truncated to 83, which corresponds to S \$\endgroup\$ Nov 10 '19 at 23:05
  • 1
    \$\begingroup\$ If that example is correct, it will invalidate all of the existing answers. \$\endgroup\$
    – user85052
    Nov 11 '19 at 10:05
  • 1
    \$\begingroup\$ Sorry. I read an ASCII table wrong and got 69 for B, not 66. \$\endgroup\$
    – sugarfi
    Nov 11 '19 at 14:00
  • \$\begingroup\$ Could I enter for a non-ASCII compliant system? \$\endgroup\$ Nov 25 '19 at 17:28

74 Answers 74

2
\$\begingroup\$

Ceylon (named function) 74 68 65 64 60

Contrary to e.g. Java, in Ceylon you can't directly add characters (The compiler complains with Left operand must be of summable type: Character is not a subtype of Summable). Instead, we first need to convert it to an integer, and afterwards back to character. This gives 74 bytes:

Character c(Character x,Character y)=>((x.integer+y.integer)/2).character;

We can write this shorter by using the .hash attribute instead of the .integer attribute, which for characters turns out to have the same implementation (returning the Unicode value of a character). This is 68 bytes:

Character d(Character x,Character y)=>((x.hash+y.hash)/2).character;

A more ceylonic way of doing this is to use the fact that Character is a Enumerable type, and implements the .neighbour and .offset methods. The average has an offset from the smaller which is half as large as the offset of the larger to the smaller. This even turns out slightly smaller, with 65 bytes.

Character a(Character x,Character y)=>x.neighbour(y.offset(x)/2);

Unfortunately most of this is the declaration of the types. We can reduce this slightly by having the method take a sequence (tuple/pair) of two characters instead of both individually – this removes one parameter, but adds [...] several times, coming to 64 bytes:

Character b(Character[2]c)=>c[0].neighbour(c[1].offset(c[0])/2);

An alternative way of making the type declaration shorter is an alias declaration. This only is worthwile from 3 usages of Character, which we have here, reaching 60 bytes:

alias C=>Character;C e(C x,C y)=>x.neighbour(y.offset(x)/2);

(The .hash version with alias comes to 63 bytes.)

Try all the examples online

\$\endgroup\$
2
\$\begingroup\$

Wren, 67 bytes

There should be a Wren answer for every Lua answer.

Fn.new{|a|String.fromCodePoint((a.bytes.reduce{|a,i|a+i}/2).floor)}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Whitespace, 45 bytes

[S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   S _Read_char_from_STDIN][T  T   T   _Retrieve][S N
S _Duplicate][S N
S _Duplicate][T N
T   S _Read_char_from_STDIN][T  T   T   _Retrieve][T    S S S _Add][S S S T S N
_Push_2][T  S T S _Integer_divide][T    N
S S _Print_as_character]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Explanation:

Character inputs in Whitespace are always stored as unicode integers, so we don't have to do an explicit conversion manually. The program has the following pseudo-code:

int a = STDIN as character
int b = STDIN as character
int c = (a+b) integer-divided by 2
Print c as character to STDOUT

I also use the first input as a heap-address for the second input, since it's guaranteed to be non-negative. This saves a byte by using SNS (duplicate) twice instead of SSSN + SNS (push 0 and duplicate).

\$\endgroup\$
2
\$\begingroup\$

brainfuck, 46 bytes

,>,[-<+>]++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>>.

Try it online!

,>,                             Takes input into cells 0 and 1
[-<+>]                          Sums the two values, storing the result in cell 0
++<                             Sets cell 1 to 2, and returns to cell 0
[->-[>+>>]>[+[-<+>]>+>>]<<<<<]  Divides cell 0 by cell 1
>>>.                            Moves to and outputs cell 3, where the quotient is stored
\$\endgroup\$
1
  • 1
    \$\begingroup\$ ,<,[>+<-]>[-[->+>]<[<<]>]>. is only 27 bytes, and it does the division by 2 by basically decrementing the sum, decrementing the sum again only if the result is still greater than 0, and incrementing another tape value, all until the sum is 0. \$\endgroup\$ Nov 12 '19 at 13:09
2
\$\begingroup\$

(e)Lisp, 50 bytes

(insert (/ (+ (aref (read) 0) (aref (read) 0)) 2))
\$\endgroup\$
2
\$\begingroup\$

CJam, 10 bytes

rcirci+2/c

Try it online!

\$\endgroup\$
2
\$\begingroup\$

T-SQL, 64 bytes

declare @ char='Z',@2 char='a'print char((ascii(@)+ascii(@2))/2)

assuming @ and @2 the input.

37 bytes if only put:

print char((ascii('B')+ascii('C'))/2)
\$\endgroup\$
2
\$\begingroup\$

T-SQL, 32 bytes

SELECT CHAR(AVG(ASCII(c)))FROM i

Input is taken via a pre-existing table \$i\$ with CHAR(1) column \$c\$, per our IO standards.

The two input characters are entered as separate rows. (Note that because SQL is set-based, this will calculate the average of an arbitrary number of inputs.)

\$\endgroup\$
2
\$\begingroup\$

C (gcc), 22 bytes

Saved 0 bytes, but got a giggle, thanks to @ceilingcat!

(*c)()=L"\xd137048d쏸";

Try it online!

\$\endgroup\$
4
  • \$\begingroup\$ Can you write \xd1 as a char? \$\endgroup\$
    – l4m2
    Apr 22 '20 at 8:46
  • \$\begingroup\$ @l4m2 Seg fault when I tried (*c)()=L"Ñ37048d쏸"; \$\endgroup\$
    – Noodle9
    Apr 22 '20 at 11:39
  • \$\begingroup\$ That's because tio use utf8 \$\endgroup\$
    – l4m2
    Apr 22 '20 at 12:53
  • \$\begingroup\$ (*c)()="??7???"; is 1 byte shorter than c(a,b){b=a+b>>1;} \$\endgroup\$
    – l4m2
    Apr 22 '20 at 13:02
2
\$\begingroup\$

shortC, 12 8 bytes

APG+G>>1

Try it online!

Please advise on golfing skeeels.

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

1+, 25 23 bytes

,,+11##1+"\"/^"+1+<1+#;

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Husk, 3 bytes

c½Σ

Try it online!

Input as a two character string.

\$\endgroup\$
2
\$\begingroup\$

Zsh, 27 bytes

Not as original as @manatwork's solution, but shorter. Try it online!

<<<${(#)$(((##$1+##$2)/2))}

Alternative for 30 bytes: printf \\$[[##8](##$1+##$2)/2]

\$\endgroup\$
2
\$\begingroup\$

Hexagony, 14 13 bytes

|*;:2@+/',{,|

Try it online!

Image

Linear control flow: ,{,'+{*2':;@

I decide to plug it in the Hexagony brute forcer program, and it can't find a 12-byte program. At least for that specific linear code.

Other possible linear control flows:

,{,'+'2=':;@
,{,'+'2{=:;@
,},"+{*2':;@
,},"+'2=':;@
,},"+'2{=:;@
,{,'+{+2':;@

(none of them results in a 12-byte solution (there are only some non-halting 12-byte solutions); nevertheless, the brute force program has room for improvement.)

\$\endgroup\$
1
  • \$\begingroup\$ That's one horrific control flow D: \$\endgroup\$
    – Bubbler
    Jan 27 at 3:25
1
\$\begingroup\$

05AB1E, 4 bytes

ÇÅAç

Try it online! or verify all test cases

Explanation

Ç    | Get ASCII values of both inputs
 ÅA  | Take the mean
   ç | Convert to ASCII char
\$\endgroup\$
1
\$\begingroup\$

C (gcc), 17 bytes

f(a,b){a=a+b>>1;}

Try it online!

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

Charcoal, 7 bytes

℅⊘ΣES℅ι

Try it online! Link is to verbose version of code. Takes input as a string of two letters. Explanation:

    S   Input string
   E    Map over characters
      ι Current character
     ℅  Take the ordinal
  Σ     Take the sum
 ⊘      Halved
℅       Convert to character
        Implicitly print
\$\endgroup\$
1
\$\begingroup\$

Python 3, 34 bytes

lambda a,b:chr((ord(a)+ord(b))//2)

Try it online!

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

Labyrinth, 8 bytes

,,+_2/.@

Try it online!

How?

, read a character from STDIN and push its ordinal 
, read a character from STDIN and push its ordinal
+ pop y, pop x, push x+y
_ push a zero
2 pop x, push 10*x+2
/ pop y, pop x, push x/y (integer division, rounded towards negative infinity)
. pop x, print byte at (x%256)
@ exit program
\$\endgroup\$
1
\$\begingroup\$

Haskell, 32 bytes

toEnum.(`div`2).sum.map fromEnum

Try it online!

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

Japt, 8 6 bytes

xc z d

Try it

\$\endgroup\$
2
  • \$\begingroup\$ Why not just xc z d? \$\endgroup\$
    – Gymhgy
    Nov 10 '19 at 5:08
  • 2
    \$\begingroup\$ @EmbodimentofIgnorance, because beer! Also, lack of practice. But mainly beer! \$\endgroup\$
    – Shaggy
    Nov 10 '19 at 11:19
1
\$\begingroup\$

Ruby, 27 bytes

->x,y{(x.ord+y.ord>>1).chr}

Try it online!

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

Gol><>, 6 bytes

ii+2,H

Try it online!

Explanation

ii     Push 2 input chars as int to stack
  +    Add them
   2,  Float divide by 2
     H Output as char and halt (Seems to truncate)
\$\endgroup\$
1
\$\begingroup\$

Javascript, 59 53 Bytes

i=>String.fromCharCode(Buffer.from(i).reduce((t,v)=>t+v)/2)

i=>String.fromCharCode((b=Buffer.from(i))[0]+b[1]>>1)

> f('ae')
'c'
> f('ab')
'a'
> f('ac')
'b'
> f('ad')
'b'
> f('ae')
'c'
> f('aZ')
']'
> f('Be')
'S'

Bonus (Sorry if off topic, I'm not sure if this is allowed and couldn't find anything with a quick check. Please advise if this is actually a viable answer or not), here is the first answer written as NodeJS REPL input (making use of tabs to complete partial names):

i=>St .f h (Bu .f (i).reduce((t,v)=>t+v)/2) (43 bytes)

Note tabs might be malformed by page formatting. Note pasting anything after the tab will suppress completion on some terminals.

\$\endgroup\$
1
  • \$\begingroup\$ Could this be shortened using toString(36) and parseInt? \$\endgroup\$ Dec 11 '20 at 6:00
1
\$\begingroup\$

JavaScript - 62 60 bytes

I'm certain there's a better way than this:

(a,b,c=x=>x.charCodeAt())=>String.fromCharCode(c(a)+c(b)>>1)

Would love some feedback!

Example:

f=(a,b,c=x=>x.charCodeAt())=>String.fromCharCode(c(a)+c(b)>>1)
f('a','c') // 'b'
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Another way to divide by 2 is to delete the last binary digit by doing a right-shift one place. This would be >>1. This is of course longer than /2, but the advantage is that it has lower precedence in terms of order-of-operations, so you can remove a pair of brackets. This results in a net gain of one character. So (...)/2 -> ...>>1 \$\endgroup\$
    – Max
    Nov 10 '19 at 15:45
  • 1
    \$\begingroup\$ I count 64 bytes. You don’t need the 0 argument. As far as I know only the function is needed, without the name; so you could use (a,b,c=x=>x.charCodeAt())=>String.fromCharCode((c(a)+c(b))/2), which would be 61 bytes. 60 with @Max’s suggestion. \$\endgroup\$ Nov 10 '19 at 15:45
  • \$\begingroup\$ Thanks you guys, very clever. I thought about the bitshift but didn't realize it is low in op precedence! \$\endgroup\$ Nov 10 '19 at 22:50
  • \$\begingroup\$ Write c as a helper and take two inputs as a=>b=> \$\endgroup\$
    – l4m2
    Apr 22 '20 at 8:47
  • 1
    \$\begingroup\$ You can reduce it to 58 bytes by currying the function, defining the c function inline and doing the division by 2 within it: a=>b=>String.fromCharCode((c=x=>x.charCodeAt()/2)(a)+c(b)) \$\endgroup\$ Aug 17 '20 at 4:44
1
\$\begingroup\$

Pyth, 6 5 bytes

C.OmC

Try it online!

As a bonus, works with more than two letters

Edit: -1 thanks to @randomdude999, wasnt aware that the lambda function implicitly adds the lambda variable

How it Works

C.OmC
   mC - Map (char to int) to the implicit input
 .O    - Take the average
C      - Int to char
\$\endgroup\$
3
  • \$\begingroup\$ Oh wow, I made a solution that was identical to this yesterday but didn't post it, nice one \$\endgroup\$
    – EdgyNerd
    Nov 10 '19 at 16:29
  • 1
    \$\begingroup\$ You don't need the trailing d. \$\endgroup\$ Nov 13 '19 at 12:18
  • \$\begingroup\$ @randomdude999 good catch \$\endgroup\$
    – frank
    Nov 13 '19 at 17:30
1
\$\begingroup\$

Stax, 4 bytes

:V@]

Run and debug it

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

Triangular, 10 9 bytes

t+~2.`>_@

Try it online!

Ungolfed:

   t
  + ~
 2 . `
> _ @

----------------------

t~`           - Read 2 characters from input; change direction to SE after
+2>_          - Add the two top values of the stack, then divide by 2
@             - Print as a character

Previous Version (10 bytes):

~.~..+@_2<
\$\endgroup\$
1
\$\begingroup\$

@, 6 bytes

Has some trailing garbage, but can't be avoided because all functions have return values.

ō/+čč2

Explanation

  +čč  Sum two inputs' charcodes
 /   2 Halve the number
ō      Output as a character
\$\endgroup\$
1
\$\begingroup\$

GolfScript, 10 bytes

{+}*2/]''+

Explanation

{+}*       # Fold the input string with sums
    2/     # Divide this number by 2
      ]''+ # Put stack into array & convert to string

# Implicit print

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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