34
\$\begingroup\$

Task

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
\$\endgroup\$
8
  • \$\begingroup\$ Edited question. Now it should be clear: you have to round halves upwards. \$\endgroup\$ Jul 24, 2015 at 9:46
  • 1
    \$\begingroup\$ "Input can be read from stdin or as command line arguments": or as function arguments (since you allow functions), right? \$\endgroup\$
    – Luis Mendo
    Jul 24, 2015 at 12:17
  • \$\begingroup\$ Of course, edited again. \$\endgroup\$ Jul 24, 2015 at 13:36
  • 2
    \$\begingroup\$ Sorry to bother you once again, but do functions actually have to print the output to STDOUT or can they return the desired string? \$\endgroup\$
    – Dennis
    Jul 24, 2015 at 14:20
  • 1
    \$\begingroup\$ Sdcce`ccddeee and HW^bdY bugs are if you use ceil instead of round, while HV^adY bugs is if you use banker's rounding (round to even). The original asker has it right for traditional math rounding. \$\endgroup\$
    – Sandra
    Aug 20, 2022 at 8:08

58 Answers 58

14
\$\begingroup\$

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.

\$\endgroup\$
10
\$\begingroup\$

Pyth, 16 bytes

smCs+.5csaYCdlYz

Pretty straightforward. Using s+.5 instead of rounding, because for some reason round(0.5, 0) is 0 in Python.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Python 3 rounds half towards even, which introduces less bias. The question doesn't explicitly specify how halves should be rounded, so I've requested clarification from the OP. \$\endgroup\$
    – Dennis
    Jul 24, 2015 at 4:35
  • 1
    \$\begingroup\$ Edited question. 0.5 rounded should be 1. \$\endgroup\$ Jul 24, 2015 at 7:54
7
\$\begingroup\$

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) ]
\$\endgroup\$
4
  • \$\begingroup\$ 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. :) \$\endgroup\$
    – JohnE
    Jul 24, 2015 at 15:57
  • \$\begingroup\$ you're correct -- no need for the function wrapper, as "c"$avgs"i"$ "Hello!" works fine \$\endgroup\$ Jul 24, 2015 at 16:15
  • \$\begingroup\$ I think you can save 2 bytes by changing "c" to `c and "i" to `i. \$\endgroup\$ Jul 24, 2015 at 20:10
  • \$\begingroup\$ 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. \$\endgroup\$ Jul 24, 2015 at 20:25
4
\$\begingroup\$

CJam, 19 bytes

Uq{i+_U):Ud/moco}/;

Try it online in the CJam interpreter.

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

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
\$\endgroup\$
4
\$\begingroup\$

Python 3, 65 bytes

n=t=0
for c in input():n+=1;t+=ord(c);print(end=chr(int(.5+t/n)))

Try it online!

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.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ If you increment n before printing, you can avoid adjusting it by 1. \$\endgroup\$
    – xnor
    Jul 24, 2015 at 16:35
  • 1
    \$\begingroup\$ @xnor: Face, palm. Palm, face. Thanks for pointing that out. \$\endgroup\$ Jul 24, 2015 at 17:26
  • \$\begingroup\$ do print(end=chr(int(...)) to save some bytes \$\endgroup\$
    – FlipTack
    Dec 11, 2016 at 20:12
  • \$\begingroup\$ @Flp.Tkc: Thanks! Answer updated. \$\endgroup\$ Dec 20, 2016 at 17:34
3
\$\begingroup\$

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

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

Ruby, 46

s=0.0
$<.bytes{|b|s+=b;$><<'%c'%(0.5+s/$.+=1)}

ideone.

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.

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

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...

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

Python 2, 65 bytes

f=lambda s:s and f(s[:-1])+chr(int(sum(map(ord,s))*1./len(s)+.5))

Try it online!

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

Ruby, 27 bytes

putc gets.sum.quo(~/$/)+0.5

Solution produced through some collaborative golfing at work.

How this works

  • Kernel#putc prints a single character (e.g. putc "Hello" outputs H). Passing an object to it prints the character whose code is the least-significant byte of the object. So putc 72 outputs H.
  • Kernel#gets reads stdin and returns a string.
  • String#sum returns a checksum. The result is the sum of the binary value of each byte in the string modulo 2**16 - 1. Since ASCII bytes comfortably fit in this space, this just returns the byte total.
  • Because the byte total is an integer, we can’t do floating point calculations (in Ruby 10 / 3 is 3 whereas 10.to_f / 3 is 3.33…). Here’s where Numeric#quo comes in – 10.quo(3) returns the Rational (10/3).
  • Regexp#~ matches a regular expression against the contents of $_ (the last string read by gets). It returns index of the match.
  • The Regexp /$/ matches the end of the string, so ~/$/ means “print the index of the end of the string” – in other words, the string length. This gives us the final is a short-hand for the length of the string read by gets.
  • This gives us the Rational (byte total/string length). Now we need to round it into an integer. +0.5 casts the Rational to a float. putc floors the float into an integer.
\$\endgroup\$
2
\$\begingroup\$

K, 36 bytes

`0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic

Usage:

  `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"Hello!"
HW^adY
  `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"test"
tmop
  `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"42"
43
  `0:_ci_.5+{(+/x)%#x}'.0+1_|(-1_)\_ic"StackExchange"
Sdccd_ccccddd

_ci and _ic convert ascii to chars and vice versa, respectively. {(+/x)%#x} is a classic K idiom for calculating a mean. Pretty straightforward overall.

Edit: oh, misread the spec. `0: is needed to print the result to stdout. Waiting for clarification on input re. Dennis' question.

\$\endgroup\$
6
  • \$\begingroup\$ If you use K5, this can be shortened to 35 bytes: {[s]`0:`c${_.5+(+/u)%#u:x#s}'1+!#s}. \$\endgroup\$ Jul 24, 2015 at 14:22
  • \$\begingroup\$ Or 30: `0:`c$_.5+{(+/x)%#x}'1_|(-1_)\ \$\endgroup\$
    – JohnE
    Jul 24, 2015 at 14:51
  • \$\begingroup\$ `c$_.5+{(+\x)%+\~^x}`i$ for 24. It could be shorter (`c$`i${(+\x)%+\~^x}`i$) but your REPL (johnearnest.github.io/ok/index.html) isn't rounding correctly when casting from float to int. I'd hesitate to call this a k solution since _ci and _ic are nowhere in the K5 spec as far as I can tell, while 0: doesn't print to stdout but instead reads a txt file from disk. \$\endgroup\$
    – tmartin
    Jul 24, 2015 at 15:10
  • \$\begingroup\$ @tmartin: correct- _ci and _ic are entirely replaced in K5 with the forms like `c$. The original solution I posted is compatible with Kona, which is based on K2/K3. I generally try not to post solutions with oK specifically because the semantics are still shifting around and partially inaccurate. \$\endgroup\$
    – JohnE
    Jul 24, 2015 at 15:18
  • 1
    \$\begingroup\$ Ah i see, makes sense to me. I figured this was another K5 solution. Here's a 28 char kona solution `0:_ci_0.5+{(+\x)%1.+!#x}_ic \$\endgroup\$
    – tmartin
    Jul 24, 2015 at 15:30
2
\$\begingroup\$

Python 2, 71

i=s=0
r=''
for c in input():s+=ord(c);i+=1.;r+=chr(int(s/i+.5))
print r

With each new character, updates the character sum s and the number of characters i to compute and append the average character.

\$\endgroup\$
3
  • \$\begingroup\$ Almost exactly the same approach as mine, only Python 2 instead of 3, and posted hours earlier: +1. (Also, I found I saved a few bytes printing each character as it came rather than storing them for one final print. Will that work with Python 2? I forget just now how to suppress newlines in the print statement... comma makes it a space instead, right?) \$\endgroup\$ Jul 25, 2015 at 6:06
  • \$\begingroup\$ Python 2 can do print _, to leave a space rather than newline, but no good way to omit the space. Good call with Python 3's end argument, I'd forgotten about that. \$\endgroup\$
    – xnor
    Jul 25, 2015 at 6:17
  • \$\begingroup\$ @TimPederick Maybe the backspace control could be justified for a terminal that uses it, as a hack to delete the space: print'\b'+_, \$\endgroup\$
    – xnor
    Jul 25, 2015 at 6:25
2
\$\begingroup\$

Mathematica, 75 bytes

FromCharacterCode@Floor[.5+Accumulate@#/Range@Length@#]&@ToCharacterCode@#&
\$\endgroup\$
2
\$\begingroup\$

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.

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

Mathcad, 60 "bytes"

enter image description here

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).

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

Japt, 11 bytes

c@V±X /°T r

Try it

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

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!
HW^adY
>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.

\$\endgroup\$
2
  • \$\begingroup\$ 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 ;) \$\endgroup\$
    – cb0
    Sep 24, 2017 at 14:16
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Wheat Wizard
    Sep 24, 2017 at 14:50
2
\$\begingroup\$

Zig 0.6.0, 84 bytes

fn a(b:[]u8)void{var t:u64=0;for(b)|c,i|{t+=c;b[i]=@intCast(u8,(t+(i+1)/2)/(i+1));}}

Try it Online

Formatted:

fn a(b: []u8) void {
    var t: u64 = 0;
    for (b) |c, i| {
        t += c;
        b[i] = @intCast(u8, (t + (i+1)/2) / (i+1));
    }
}
\$\endgroup\$
2
\$\begingroup\$

PHP 7, 79 bytes

As I don't have enough reputation to comment on cb0's answer to provide him hints to improve his answer (mainly using the char index method in a string and while to loop through a string). But I still bothered to post it due to the large reduction in byte count.

<?php $i=$b=0;while($a=ord($argv[1][$i++]??'')){$b+=$a;echo chr(round($b/$i));}

I didn't find a way though to use the <?= shortcut and avoid undefined errors without using command line flags (this is why i used $i=$b=0;). This answer does not work in PHP 5 due to the ?? syntax.

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

Vyxal s, 7 bytes

CKvṁ.+C

Try it Online!

.+ should be , but there's a bug.

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

Knight, 62 bytes

;;=sP=i 0W<=i+1i+1Ls;=aGs=t 0i;Wa;=t+tAa=aGa 1LaO+A/+t/i 2i"\"

Try it online!

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

05AB1E, 15 bytes

.pvyDSÇOsg/îç}J

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ -2 bytes by removing D and }, and replacing s with y. \$\endgroup\$ Aug 10, 2018 at 12:39
  • 1
    \$\begingroup\$ @KevinCruijssen for how old this answer is there's a lot more than that :P. .p is a 1byter now too \$\endgroup\$ Aug 10, 2018 at 14:20
  • \$\begingroup\$ Ah lol, forgot about η xD \$\endgroup\$ Aug 10, 2018 at 14:22
2
\$\begingroup\$

Japt, 13 bytes

£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
\$\endgroup\$
1
  • \$\begingroup\$ Ah, nuts; I thought the "non-competing" filter had been removed from the leaderboard, so I didn't see this before posting this. \$\endgroup\$
    – Shaggy
    Sep 19, 2017 at 13:01
2
\$\begingroup\$

Jelly, 7 bytes

OÆmƤ+.Ọ

Try it online!

OÆmƤ+.Ọ
O       - Get a list of character codes from the input string
   Ƥ    - Over prefixes:
 Æm     -  Get the mean
    +.  - To each, add 0.5
      Ọ - Convert from character codes to charcters. Decimals are rounded down.
\$\endgroup\$
2
\$\begingroup\$

brev, 146 bytes

(as-list reverse(c pair-fold-right(fn(cons(integer->char(inexact->exact(floor(+(/(apply + x)(length x))0.5))))y))'())reverse(c map char->integer))

124 with banker's rounding:

(as-list reverse(c pair-fold-right(fn(cons(integer->char(round(/(apply + x)(length x))))y))'())reverse(c map char->integer))

Which is still a lot. It's clear that a huge painpoint in brev is the type converting (chars to integers, strings to lists etc).

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

Dart, 76 bytes

t(a,[c=1,s=0])=>String.fromCharCodes([...a.runes.map((i)=>(s+=i+.5)~/c++)]);

Try it online!

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

J, 22 bytes

(0.5<.@++/%#)\&.(3&u:)

Try it online!

Explanation

(0.5<.@++/%#)\&.(3&u:)
              &.(    )  do this, the left verb then the inverse of this:
                 3&u:     characters -> ordinates
(           )\          over the prefixes of the input:
        +/%#            take the average (sum divide length)
 0.5   +                add one-half
    <.@                 then floor   
\$\endgroup\$
2
\$\begingroup\$

Matlab, 43 31 bytes

Thanks to @beaker for 9 bytes off!

Using an anonymous function:

@(s)[cumsum(+s)./find(s)+.5 '']

Examples:

>> @(s)[cumsum(+s)./find(s)+.5 '']
ans =
  function_handle with value:
    @(s)[cumsum(+s)./(find(s))+.5 '']
>> f=ans;
>> f('Hello!')
ans =
    'HW^adY'
>> f('test')
ans =
    'tmop'
>> f('42')
ans =
    '43'
>> f('StackExchange')
ans =
    'Sdccd_ccccddd'
\$\endgroup\$
2
  • \$\begingroup\$ Since all printable ASCII codes are non-zero, find(s) is 5 bytes shorter than (1:numel(s)). In Octave, char seems to do automatic rounding of non-integer values, saving another 7 bytes. \$\endgroup\$
    – beaker
    Aug 29, 2022 at 15:17
  • 2
    \$\begingroup\$ @beaker Thanks! How unexperienced I was back then. I didn't even remove f= from the count :-D Matab seems to round down rather than to nearest, so I had to include +.5 \$\endgroup\$
    – Luis Mendo
    Aug 29, 2022 at 16:28
1
\$\begingroup\$

Ruby 59 61

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

Test: http://ideone.com/dT7orT

\$\endgroup\$
2
  • 1
    \$\begingroup\$ c+=1;(s/c)(s/c+=1) ideone.com/H2tB9W \$\endgroup\$
    – manatwork
    Jul 24, 2015 at 9:38
  • \$\begingroup\$ @manatwork Well spotted! Thanks! I applied the change. \$\endgroup\$ Jul 24, 2015 at 10:13

Your Answer

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

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