# Calculate average characters of string

Your task is to produce string that contains average characters of string. First character of result would be average character of first character (which is first character) and second character average of two first characters and so on.

# What is average character?

Strings are arrays of bytes. Average character of string can be found by calculating the average of the ASCII values of characters in string and taking corresponding ASCII character.

For example string "Hello!" can be written as byte sequence 72 101 108 108 111 33. Average of ascii values is 533/6 = 88.833... and when it's rounded to nearest integer we get 89 which is ascii code for captial letter Y.

# Rules

• You can assume that input contains only printable ASCII characters
• Input can be read from stdin or as command line arguments or as function arguments
• Output must be stdout. If your program is function, you can also return the string you would otherwise print.
• It must be whole program or function, not snippet
• Standard loopholes apply
• Integers are rounded by function floor(x+0.5) or similar function.

# How do I win?

This is , so shortest answer (in bytes) in wins.

# Examples

• Hello!HW^adY
• testtmop
• 4243
• StackExchangeSdccd_ccccddd
• Edited question. Now it should be clear: you have to round halves upwards. – Hannes Karppila Jul 24 '15 at 9:46
• "Input can be read from stdin or as command line arguments": or as function arguments (since you allow functions), right? – Luis Mendo Jul 24 '15 at 12:17
• Of course, edited again. – Hannes Karppila Jul 24 '15 at 13:36
• Sorry to bother you once again, but do functions actually have to print the output to STDOUT or can they return the desired string? – Dennis Jul 24 '15 at 14:20
• Sorry, forgot to edit that before. Now it should be ok. – Hannes Karppila Jul 24 '15 at 20:41

# J, 23 bytes

(0.5<.@++/%#)&.(a.&i.)\


Try it online!

### How it works

                      \  on prefixes
(   i.)   index of the first occurence
(  &  )   in
(a.   )   the character set
x&.y         apply y, then x, then the inverse of y,
(0.5        )              that is the element of a. with a given index
(       +/  )            sum
(          #)            number of elements
(         % )            division
(   <.@+    )            add, then floor


# Husk, 10 bytes

zȯci/Nt∫mc


Try it online!

                                                    | "tuna"
mc  -- map each character to ASCII value   | [116,117,110,97]
t∫    -- prefix sums & drop leading 0        | [116,233,343,440]
z(   )N      -- zip the list with [1..] using       |
/        --   divide                            | [116/1,233/2,343/3,440/4] == [116.0,116.5,114.̅3,110.0]
i         --   round                             | [116,117,114,110]
c          --   convert to character              | "turn"


# Jelly, 8 bytes

OÆmƤ+.ḞỌ


Try it online!

PHP, 176 byte

<?=(implode('',array_reduce(str_split($argv[1]),function($c,$k){array_push($c[1],chr(floor(((ord($k)+$c[0])/(count($c[1])+1))+0.5)));return[ord($k)+$c[0],$c[1]];},[0,[]])[1]));


Example:

>php cg.php Hello!
>php cg.php test
tmop
>php cg.php 42
43


The biggest solution so far, but based on php it can't get much shorter I think. 2 bytes could be saved by removing the newlines.

• Hmm, good point. I thought I might leave them in the post for better readability. But yeah, this is code golf. I'll remove them ;) – cb0 Sep 24 '17 at 14:16
• You can always include an additional version with padding for readability along side your short one. I often do this when my code is too long to be entirely visible on most monitors. – Sriotchilism O'Zaic Sep 24 '17 at 14:50

## Clojure, 69 bytes

#(for[c(map /(reductions +(map int %))(rest(range)))](char(+ c 0.5)))


Returns a sequence of characters, arguably a string-like construct. Would need an #(apply str(for[...]...)) to convert it into a string.

# Japt, 11 bytes

c@V±X /°T r


Try it

# SmileBASIC, 64 bytes

INPUT S$FOR I=1TO LEN(S$)A=A-A/I+ASC(S$[I-1])/I?CHR$(A+.5);
NEXT


# Japt, 13 bytes (non-competing)

£T±Xc)/°Y r d


Test it online!

### How it works

£   T± Xc)/° Y r d
mXY{T+=Xc)/++Y r d}
// Implicit: U = input string, T = 0
mXY{              }  // Replace each char X and index Y in the string by this function:
T+=Xc            //   Add X.charCodeAt() to T.
)/++Y       //   Take T / (Y + 1).
r d   //   Round, and convert to a character.
// Implicit: output result of last expression

• Ah, nuts; I thought the "non-competing" filter had been removed from the leaderboard, so I didn't see this before posting this. – Shaggy Sep 19 '17 at 13:01

# JavaScript (ES6), 75 bytes

let f =
s=>s.replace(/./g,x=>String.fromCharCode((t+=x.charCodeAt())/++i+.5),i=t=0)
<input oninput="O.value=f(this.value)" value="Hello!"><br>
<input id=O value="HW^adY" disabled>

I can't believe there's no JS answer with this technique yet...

# Jelly, 16 bytes (non-competing)

S÷L+.Ḟ
OµḣLR$Ç€Ọ  Try it online! Only if there were Average and Round built-ins... # 05AB1E, 15 bytes [Non-competing?] .pvyDSÇOsg/îç}J  Try it online! • -2 bytes by removing D and }, and replacing s with y. – Kevin Cruijssen Aug 10 '18 at 12:39 • @KevinCruijssen for how old this answer is there's a lot more than that :P. .p is a 1byter now too – Magic Octopus Urn Aug 10 '18 at 14:20 • Ah lol, forgot about η xD – Kevin Cruijssen Aug 10 '18 at 14:22 ## Python 3, 66 bytes If I use round() instead of int(.5+ etc., it saves one character, but is technically not in compliance with the challenge: Python's round() rounds halves to the nearest even integer, not upwards. However, it works correctly on all sample inputs. I also feel a bit dirty for not ending the output with a newline, but the challenge doesn't require that... n=t=0 for c in input():n+=1;t+=ord(c);print(end=chr(int(.5+t/n)))  • If you increment n before printing, you can avoid adjusting it by 1. – xnor Jul 24 '15 at 16:35 • @xnor: Face, palm. Palm, face. Thanks for pointing that out. – Tim Pederick Jul 24 '15 at 17:26 • do print(end=chr(int(...)) to save some bytes – FlipTack Dec 11 '16 at 20:12 • @Flp.Tkc: Thanks! Answer updated. – Tim Pederick Dec 20 '16 at 17:34 # Factor, 80 bytes [ cum-sum [ dup zero? 1 0 ? + / ] map-index [ .5 + floor >fixnum ] map >string ]  # ><>, 30 bytes i:0(?v v &l~< \+l2(? \&,12,+o;  • The first line reads from stdin and puts the characters on the stack • The second will remove the EOL char, take the size of the stack and put it in the & register • The third line will add numbers on the stack while there are two or more of them • The fourth line will divide the resulting number by the register's value, then add 1/2, output the value as a character and stop. When faced with a float value when displaying a char, ><> will floor it, which is why we added 1/2 You can try it on the online interpreter but then you need to use the following version, because the online interpreter pads the code box to a rectangle and applies ? to spaces. i:0(?v v &l~< \+l2( ? \&,12,+o;  # Mathcad, 60 "bytes" Mathcad is mathematical application based on 2D worksheets comprised of "regions" each of which can be text, a mathematical expression, program, plot or scripted component. A mathematical or programming instruction is picked from a palette toolbar or entered using a keyboard shortcut. For golfing purposes, an operation ("byte") is taken to be the number of keyboard operations necessary to create a name or expression (for example, to set the variable a to 3, we would write a:=3. The definition operator := is a single keypress ":", as are a and 3 giving a total of 3 "bytes". The programming for operator requires typing ctl-shft-# (or a single click on the programming toolbar) so again is equivalent to 1 byte. In Mathcad the user enters programming language commands using keyboard shortcuts (or picking them from the Programming Toolbar) rather than writing them in text. For example, typing ctl-] creates a while-loop operator that has two "placeholders" for entering the condition and a single line of the body, respectively. Typing = at the end of a Mathcad expressions causes Mathcad to evaluate the expression. (Count bytes) By looking at it from a user input perspective and equating one Mathcad input operation (keyboard usually, mouse-click on toolbar if no kbd shortcut) to a character and interpreting this as a byte. csort = 5 bytes as it's typed char-by-char as are other variable/function names. The for operator is a special construct that occupies 11 characters (including 3 blank "placeholders" and 3 spaces) but is entered by ctl-shft-#, hence = 1 byte (similar to tokens in some languages). Typing ' (quote) creates balanced parentheses (usually) so counts as 1 byte. Indexing v = 3 bytes (type v[k). ## TSQL, 118 bytes DECLARE @ varchar(400) = 'StackExchange' SELECT top(len(@))char(avg(ascii(stuff(@,1,number,''))+.5)over(order by number))FROM master..spt_values WHERE'P'=type  Returning characters vertical S d c c d _ c c c c d d d  # Perl 5, 41 bytes say map{$s+=ord;chr($s/++$c+.5)}pop=~/./g


run as

$perl -E 'say map{$s+=ord;chr($s/++$c+.5)}pop=~/./g' StackExchange
Sdccd_ccccddd


# R, 135 127 Bytes

This got long real quick and I really got it wrong the first time:) Need to read the questions properly.

cat(sapply(substring(a<-scan(,''),1,1:nchar(a)),function(x)rawToChar(as.raw(round(mean(as.integer(charToRaw(x)))+.5)))),sep='')


Test Run

cat(sapply(substring(a<-scan(,''),1,1:nchar(a)),function(x)rawToChar(as.raw(round(mean(as.integer(charToRaw(x)))+.5)))),sep='')
1: Hello!
2:

• somebody posted a dupe challenge in the sandbox so I found this...This was a looong time ago, but utf8ToInt will help! I have a 68 byte golf of this if you want to update to it. – Giuseppe Jan 18 '18 at 17:31
• @Giuseppe Go ahead and post it yourself if you would like. I suspect that it is significantly different to what I did here. – MickyT Jan 18 '18 at 18:41

# Perl: 31 30 characters

(29 characters code + 1 character command line option.)

s!.!chr.5+($s+=ord$&)/++$c!ge  Sample run: bash-4.3$ perl -pe 's!.!chr.5+($s+=ord$&)/++$c!ge' <<< 'StackExchange' Sdccd_ccccddd  # C, 62 bytes c;t;main(n){for(;(c=getchar())>0;n++)putchar(((t+=c)+n/2)/n);}  (ideone link) The results are slightly different from the OP's examples, but only because this code rounds 0.5 down instead of up. Not any more! # Q, 15 12 bytes 12 bytes as an expression "c"$avgs"i"$q)"c"$avgs"i"$"Hello!" "HW^adY" q)"c"$avgs"i"$"test" "tmop" q)"c"$avgs"i"$"42" "43" q)"c"$avgs"i"$"StackExchange" "Sdccd_ccccddd"  or 15 bytes as a function {"c"$avgs"i"$x} q){"c"$avgs"i"$x} "Hello!" "HW^adY" q){"c"$avgs"i"$x} "test" "tmop" q){"c"$avgs"i"$x} "42" "43" q){"c"$avgs"i"$x} "StackExchange" "Sdccd_ccccddd"  takes advantage of 1. the "i"$ cast to convert a string (list of characters) to a list of integers
2. the avgs function, which computes the running average of a list as a list of floats
3. the "c"$cast to convert a list of floats to a list of characters, and which automatically rounds each float to the nearest integer before doing so [i.e. ("c"$99.5) = ("c"$100) and ("c"$99.4) = ("c"$99) ] • Does Q require the function wrapper here or can you get away with just the tacit expression "c"$avgs"i"$ ? I don't think a solution could get much more straightforward than that. :) – JohnE Jul 24 '15 at 15:57 • you're correct -- no need for the function wrapper, as "c"$avgs"i"$"Hello!" works fine – scottstein37 Jul 24 '15 at 16:15 • I think you can save 2 bytes by changing "c" to c and "i" to i. – kirbyfan64sos Jul 24 '15 at 20:10 • unfortunately, i don't think that works. To use the symbol type representation for casting I'd have to use char and int as per code.kx.com/wiki/JB:QforMortals2/… I considered using 10h and 6h instead of "c" and "i" but that wouldn't save any bytes -- 10h is the same length as "c" and substituting 6h for "i" requires a trailing space, making them the same length also. – scottstein37 Jul 24 '15 at 20:25 # Ruby, 46 s=0.0$<.bytes{|b|s+=b;$><<'%c'%(0.5+s/$.+=1)}


With apologies to w0lf, my answer ended up different enough that it seemed worth posting.

$<.bytes iterates over each byte in stdin, so we print the rolling average in each loop. '%c' converts a float to a character by rounding down and taking the ASCII, so all we have to do is add 0.5 to make it round properly. $. is a magic variable that starts off initialized to 0--it's supposed to store the line count, but since here we want byte count we just increment it manually.

# JavaScript ES6, 111 bytes

w=>w.replace(/./g,(_,i)=>String.fromCharCode([for(f of w.slice(0,++i))f.charCodeAt()].reduce((a,b)=>a+b)/i+.5))


This is annoyingly long thanks in part to JavaScript's long String.fromCharCode and charCodeAt functions. The stack snippet contains ungolfed, commented, testable code.

f=function(w){
return w.replace(/./g,function(e,i){
return String.fromCharCode(w.slice(0,++i).split('').map(function(f){
return f.charCodeAt()
}).reduce(function(a,b){
// Adds all numbers in the array
return a+b
// String.fromCharCode automatically floors numbers, so we add .5 to round up
})/i+.5)
})
}

run=function(){document.getElementById('output').innerHTML=f(document.getElementById('input').value)};document.getElementById('run').onclick=run;run()
<input type="text" id="input" value="Hello!" /><button id="run">Run</button><br />
<pre id="output"></pre>

# Julia, 85 81 bytes

s->(i=[int(c)for c=s];print(join([char(iround(mean(i[1:j])))for j=1:length(i)])))


This creates an unnamed function that accepts a string and creates a vector of its ASCII code points. Means are taken for each sequential group, rounded to integers, converted to characters, joined into a string, and printed to STDOUT.

# Java, 100

Much like many other answers here, I'm summing and averaging in a loop. Just here to represent Java :)

void f(char[]z){float s=0;for(int i=0;i<z.length;System.out.print((char)Math.round(s/++i)))s+=z[i];}


My original code is a 97, but it only returns the modified char[] rather than printing it:

char[]g(char[]z){float s=0;for(int i=0;i<z.length;z[i]=(char)Math.round(s/++i))s+=z[i];return z;}


Now, it's just long enough for scrollbars to appear for me, so here's a version with some line breaks, just because:

void f(char[]z){
float s=0;
for(int i=0;
i<z.length;
System.out.print((char)Math.round(s/++i)))
s+=z[i];
}

• Interesting. Can you show us a call sample too? My Java is very rusty. – manatwork Jul 24 '15 at 13:49
• As in how to call it? Assuming test is a char array, just use f(test);. If it's a String object, then you'd use f(test.toCharArray());. String literals are fine like that, too: f("Hello!".toCharArray()); – Geobits Jul 24 '15 at 13:53
• Oh. Sure. toCharArray() Me stupid, I tried to violate it with some casting. Thank you. – manatwork Jul 24 '15 at 13:58
• It'd be way too easy to just cast it. The Java gods would be furious :P – Geobits Jul 24 '15 at 13:59

# Mathematica, 75 bytes

FromCharacterCode@Floor[.5+Accumulate@#/Range@Length@#]&@ToCharacterCode@#&


## Matlab, 43

Using an anonymous function:

f=@(s)char(round(cumsum(+s)./(1:numel(s))))


Examples:

>> f=@(s)char(round(cumsum(+s)./(1:numel(s))))
f =
@(s)char(round(cumsum(+s)./(1:numel(s))))

>> f('Hello!')
ans =

>> f('test')
ans =
tmop

>> f('42')
ans =
43

>> f('StackExchange')
ans =
Sdccd_ccccddd


# C# 189 135 134 106 Bytes

var x=s.Select((t,i)=>Math.Round(s.Select(a=>(int)a).Take(i+1).Average())).Aggregate("",(m,c)=>m+(char)c);


Can be seen here

First time golfer

### Ruby 59 61

->w{s=c=0.0;w.chars.map{|l|s+=l.ord;(s/c+=1).round.chr}*''}

• c+=1;(s/c)(s/c+=1) ideone.com/H2tB9W – manatwork Jul 24 '15 at 9:38
• @manatwork Well spotted! Thanks! I applied the change. – Cristian Lupascu Jul 24 '15 at 10:13

## Brainfuck 106 bytes

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


This is my first participation in a code-golf, please be gentle! It does work but brainfuck can't handle floats (not that i know of) so the rounded value is always the bottom one (might fix my algorithm later).

Also, the algorithm averages the values 2 by 2, meaning it could be innacurate in some spots. And I need to fix a bug that is printing a number at the end of the output too.