# Question
Title: Rosetta Stone Challenge: What's Average Anyways?
The goal of a Rosetta Stone Challenge is to write solutions in as many languages as possible. Show off your programming multilingualism!

## The Challenge

When people use the term "average," they generally mean the arithmetic mean, which is the sum of the numbers divided by the number of numbers. There are, however, many more meanings to the word "mean," including the harmonic mean, the geometric mean, the arithmetic mean, the quadratic mean, and the contraharmonic mean.

Your challenge is to write a program which inputs a list of numbers and outputs those 5 different means. Additionally, you are trying to write programs in **as many languages as possible**. You are allowed to use any sort of standard library function that your language has, since this is mostly a language showcase.

## Input

Input will be a list of positive numbers.

```
1,2,3,4,5
1.7,17.3,3.14,24,2.718,1.618
8.6
3,123456
10.1381,29.8481,14.7754,9.3796,44.3052,22.2936,49.5572,4.5940,39.6013,0.9602
3,4,4,6.2,6.2,6.2

```

## Output

Output will be the five means in the order listed above (harmonic, geometric, arithmetic, quadratic, contraharmonic). Conveniently, this is the same as increasing order.

```
2.18978,2.6052,3,3.31662,3.66667
3.01183,4.62179,8.41267,12.2341,17.7915
8.6,8.6,8.6,8.6,8.6
5.99985,608.579,61729.5,87296.6,123453.
5.95799,14.3041,22.5453,27.9395,34.6243
4.5551,4.74682,4.93333,5.10425,5.28108

```

There will be some reasonable leniency in I/O format, but I do want several decimal places of accuracy. Since I want floating-point output, you can assume floating-point input.

# The Objective Winning Criterion

As for an objective winning criterion, here it is: Each language is a separate competition as to who can write the shortest entry, but the overall winner would be the person who wins the most of these sub-competitions. This means that a person who answers in many uncommon languages can gain an advantage. Code-golf is mostly a tiebreaker for when there is more than one solution in a language: the person with the shortest program gets credit for that language.

If there is a tie, the winner would be the person with the most second-place submissions (and so on).

## Rules, Restrictions, and Notes

Your program can be written in any language that existed prior to September 2th, 2014. I will also have to rely on the community to validate some responses written in some of the more uncommon/esoteric languages, since I am unlikely to be able to test them.

Please keep all of your different submissions contained within a single answer.

Also, no shenanigans with basically the same answer in a slightly different language dialects. I will be the judge as to what submissions are different enough.

---

# Current Leaderboard

This section will be periodically updated to show the number of languages and who is leading in each.

* Algoid (337) - Beta Decay
* APL (42) - algorithmshark
* Awk (78) - Dennis
* BBC BASIC (155) - Beta Decay
* C (136) - Dennis
* C++ (195) - Zeta
* C# (197) - Martin Büttner
* CJam (43) - Dennis
* Clojure (324) - Michael Easter
* Cobra (132) - Ourous
* CoffeeScript (155) - Martin Büttner
* Commodore BASIC (104) - Mark
* Common Lisp (183) - DLosc
* Erlang (401) - Mark
* Fortran (242) - Kyle Kanos
* Fortran 77 (286) - Beta Decay
* GNU bc (78) - Dennis
* GolfScript (83) - Dennis
* Groovy (157) - Michael Easter
* Haskell (140) - Zeta
* J (28) - algorithmshark
* Java (235) - Michael Easter
* JavaScript (ES6) (112) - Dennis
* JRuby (538) - Michael Easter
* Julia (79) - Martin Büttner
* Lua (113) - AndoDaan
* Mathematica (65) - Martin Büttner
* Matlab (63) - Martin Büttner
* Octave (68) - Dennis
* Openscript (849?) - COTO
* Pascal (172) - Mark
* Perl (76) - Grimy
* PHP (135) - Dennis
* POV-Ray 3.7 (304) - Mark
* Prolog (235) - DLosc
* Pyth (52) - Dennis
* Python 2 (96) - Dennis
* Python 3 (103) - DLosc
* Q (53) - algorithmshark
* Q'Nial (68) - algorithmshark
* QBasic (96) - DLosc
* R (91) - plannapus
* Ruby (118) - Martin Büttner
* Rust (469) - Vi.
* Scala (230) - Michael Easter
* T-SQL (122) - MickyT
* TI-Basic (85) - Ypnypn
* TypeScript (393) - rink.attendant.6
* VBA (Excel) (387) - Stretch Maniac
* wxMaxima (134) - Kyle Kanos

---

# Current User Rankings

1. Dennis (10)
2. Martin Büttner (6)
3. Michael Easter (5)
4. Mark, DLosc, algorithmshark (4)
5. Beta Decay (3)
6. Zeta, Kyle Kanos (2)
7. Ourous, AndoDaan, COTO, Grimy, plannapus, Vi., MickyT, Ypnypn, rink.attendant.6, Stretch Maniac (1)

(If I made a mistake in the above rankings, let me know and I'll fix it. Also, the tiebreaker has not been applied yet.)

# Answer
# Languages: 1

### Openscript (many hundreds)

(My favourite obscure and sadly defunct programming language, because I learned to program on it many years ago. ;)

```
openFile "inputs.txt"
readFile "inputs.txt" to EOF

put it into my input_string

closeFile "inputs.txt"

local inputs[]

fill the inputs with my input_string in [item] order

put 0 into the harmonic_mean
put 0 into the geometric_mean
put 0 into the arithmetic_mean
put 0 into the quadratic_mean

put the length of the inputs into n

step i from 1 to n
    get inputs[i]
    increment the harmonic_mean by 1/it
    increment the geometric_mean by log( it )
    increment the arithmetic_mean by it
    increment the quadratic_mean by it*it
end

get "outputs.txt"
createFile it

writeFile n/harmonic_mean                & "," to it
writeFile exp( geometric_mean/n )        & "," to it
writeFile arithmetic_mean/n              & "," to it
writeFile sqrt( quadratic_mean/n )       & "," to it
writeFile quadratic_mean/arithmetic_mean to it

closeFile it

```
> 22 votes

# Answer
# Languages: 13

I think this list should now contain every programming language that I know sufficiently well to solve at least simple problems in. I'll try to keep this list complete over time as I look into some new languages. (I *used* to know some Smalltalk and Delphi, but I'd have to look up to much for adding them to feel right.)

## C, ~~196~~ ~~190~~ ~~171~~ 165 bytes

```
main(int c,char**v){float n=c-1,x,h,g=1,q,a=h=q=0;for(;c-1;h+=1/x,g*=pow(x,1/n),a+=x/n,q+=x*x/n)sscanf(v[--c],"%f",&x);printf("%f,%f,%f,%f,%f",n/h,g,a,sqrt(q),q/a);}

```

Reads the input as individual command line arguments and writes a comma-separated list of the means to STDOUT.

Thanks for some improvements to Quentin.

## C++, 200 bytes

This is the same as the above C code, plus two includes. I'm including this because it's longer than the winning C++ submission, so I guess no harm is done, and I'd like this post to actually contain every language I know. :)

```
#include <cmath>
#include <cstdio>
main(int c,char**v){float n=c-1,x,h,g=1,q,a=h=q=0;for(;c-1;h+=1/x,g*=pow(x,1/n),a+=x/n,q+=x*x/n)sscanf(v[--c],"%f",&x);printf("%f,%f,%f,%f,%f",n/h,g,a,sqrt(q),q/a);}

```

## C#, ~~220~~ 197 bytes

```
namespace System{using Linq;class F{double[]f(double[]l){double n=l.Length,a=l.Sum()/n,q=l.Sum(x=>x*x)/n;return new[]{n/l.Sum(x=>1/x),l.Aggregate((p,x)=>p*Math.Pow(x,1.0/n)),a,Math.Sqrt(q),q/a};}}}

```

Defines a function in a class taking a `List` of doubles and returning an array of doubles with the five means.

Thanks for some improvements to Visual Melon and Bob.

## CJam, 52 bytes

```
ea_,:L;:d_Wf#:+L\/\_:*1Ld/#\_:+L/:A\2f#:+L/:QmqQA/]p

```

Takes the input as command-line arguments and prints a list with the five values to STDOUT.

## CoffeeScript, 155 bytes

This is almost the same as the JavaScript solution further down (and initially I didn't count it for that reason), but the OP included it in the scoreboard anyway, so I promoted it to a full submission. They *are* technically different languages after all.

```
f=(l)->l.r=l.reduce;n=l.length;[n/l.r(((s,x)->s+1/x),0),Math.pow(l.r(((p,x)->p*x),1),1/n),a=l.r(((s,x)->s+x),0)/n,Math.sqrt(q=l.r(((s,x)->s+x*x),0)/n),q/a]

```

## JavaScript (ES6), ~~155~~ 153 bytes

```
f=l=>{l.r=l.reduce;n=l.length;return[n/l.r((s,x)=>s+1/x,0),Math.pow(l.r((p,x)=>p*x,1),1/n),a=l.r((s,x)=>s+x,0)/n,Math.sqrt(q=l.r((s,x)=>s+x*x,0)/n),q/a]}

```

Defines a function taking a array of numbers and returning a array with the five means.

Thanks for some improvements to William Barbosa.

## Julia, 79 bytes

```
f(l)=(n=length(l);[n/sum(1/l),prod(l)^(1/n),a=mean(l),q=norm(l)/sqrt(n),q*q/a])

```

Defines a function taking a list of numbers and returning a list with the five means.

## Lua, 120 bytes

```
f=function(l)h=0;q=0;a=0;g=1;for i=1,#l do x=l[i]h=h+1/x;a=a+x/#l;g=g*x^(1/#l)q=q+x*x/#l end;return#l/h,g,a,q^.5,q/a end

```

Defines a function taking a list of numbers and returning 5 separate values for the means.

## Mathematica, ~~73~~ ~~67~~ 65 bytes

```
f[l_]:={1/(m=Mean)[1/l],GeometricMean@l,a=m@l,Sqrt[q=m[l*l]],q/a}

```

Defines a function taking a list of floating point numbers and returning a list with the five means.

*Fun fact:* Mathematica has all 5 means built in (and that was my original submission), but three of them can be implemented in fewer characters than their function names.

## Matlab, ~~65~~ 63 bytes

```
l=input('');a=mean(l);q=rms(l);harmmean(l)
geomean(l)
a
q
q*q/a

```

Requests the input as an array of numbers from the user and outputs the five means individually.

Thanks for some improvements to Dennis Jaheruddin.

## PHP ≥ 5.4, ~~152~~ ~~149~~ 143 bytes

```
function f($l){$g=1;$n=count($l);foreach($l as$x){$q+=$x*$x/$n;$h+=1/$x;$g*=pow($x,1/$n);}return[$n/$h,$g,$a=array_sum($l)/$n,sqrt($q),$q/$a];}

```

Same functional implementation as the earlier ones.

Thanks for some improvements to Ismael Miguel.

## Python 2, 127 bytes

```
def f(l):n=len(l);a=sum(l)/n;q=sum(x*x for x in l)/n;return[n/sum(1/x for x in l),reduce(lambda x,y:x*y,l)**(1./n),a,q**.5,q/a]

```

Same functional implementation as the earlier ones.

## Ruby, ~~129~~ 118 bytes

```
f=->l{n=l.size
r=->l{l.reduce :+}
[n/r[l.map{|x|1/x}],l.reduce(:*)**(1.0/n),a=r[l]/n,(q=r[l.map{|x|x*x}]/n)**0.5,q/a]}

```

Same functional implementation as the earlier ones.
> 18 votes

# Answer
# 4 languages

## J - ~~32~~ 28 char!

A function taking the list of numbers as its sole argument.

```
%a,^.a,[a(,,]%%)*:a=.+/%#&.:

```

`a` here is an adverb, which is J's take on second-order functions.

* `+/ % #` is a train in J, meaning Sum Divided-by Count, the definition of the arithmetic mean.
* `&.:` is a conjunction called Under, where `u&.:v(y)` is equivalent to `vi(u(v(y)))` and `vi` is the functional inverse of `v`. Yes, *J can take functional inverses*.
* Finally, a useful feature of J is that certain functions can automatically loop over lists, because J knows to apply them pointwise if it wouldn't make sense to apply them on the whole argument. So the square of a list is a list of the squares, for instance.

Thus `a` takes a function on the left, and returns a mean that "adjusts" the values by the function, takes the arithmetic mean, and then reverses the adjustment afterwards.

* `%a` is the harmonic mean, because `%` means Reciprocal, and is its own inverse.
* `^.a` is the geometric mean, because `^.` is the natural logarithm and its inverse is the exponential. `(Π x)^(1/n) = exp(Σ log(x)/n)`
* `[a` is the arithmetic mean, because `[` is the identity function.
* `*:a` is the quadratic mean, because `*:` is Square, and its inverse is the square root.
* The contraharmonic gives us a whole host of trouble—mean of the squares divided by mean—so we do a little math to get it: (`*:a` divided by (`[a` divided by `*:a`)). This looks like `[a(]%%)*:a`. While we're at it, we prepend each of the means, `[a(,,]*%~)*:a`.

Finally, we use commas to append the rest of the results together. We require no further parens because concatenation is (in this case at least) associative.

In use at the J REPL:

```
   (%a,^.a,[a(,,]%%)*:a=.+/%#&.:) 1,2,3,4,5   NB. used inline
2.18978 2.60517 3 3.31662 3.66667
   f =: %a,^.a,[a(,,]%%)*:a=.+/%#&.:          NB. named
   f 1.7,17.3,3.14,24,2.718,1.618
3.01183 4.62179 8.41267 12.2341 17.7915
   f 8.6
8.6 8.6 8.6 8.6 8.6
   f 3,123456
5.99985 608.579 61729.5 87296.6 123453
   f 10.1381,29.8481,14.7754,9.3796,44.3052,22.2936,49.5572,4.5940,39.6013,0.9602
5.95799 14.3041 22.5453 27.9395 34.6243
   f 3,4,4,6.2,6.2,6.2
4.5551 4.74682 4.93333 5.10425 5.28108

```

## Q - 53 char

Single argument function. We just make a list of all the means we want.

```
{s:(a:avg)x*x;(1%a@1%x;exp a log x;a x;sqrt s;s%a x)}

```

The same thing in other versions of k is below.

* k4, 51 char: `{s:(a:avg)x*x;(%a@%x;exp a log x;a x;sqrt s;s%a x)}`
* k2, 54 char: `{s:(a:{(+/x)%#x})x*x;(%a@%x;(*/x)^%#x;a x;s^.5;s%a x)}`

## APL - 42 char

Function taking list as argument.

```
{(÷M÷⍵)(*M⍟⍵)A(S*.5),(S←M⍵*2)÷A←(M←+/÷≢)⍵}

```

Explained by explosion:

```
{                                         } ⍝ function with argument ⍵
                                   +/÷≢     ⍝ Sum Divide Length, aka mean
                                 M←         ⍝ assign function to M for Mean
                              A←(M     )⍵   ⍝ arithmetic Mean, assign to A
                     (S←M⍵*2)               ⍝ Mean of squares, assign to S
                      S      ÷A             ⍝ S divide A, aka contraharmonic mean
              (S*.5)                        ⍝ sqrt(S), aka quadratic mean/RMS
                    ,                       ⍝ concatenate into a list
             A                              ⍝ prepend A (APL autoprepends to lists)
        *M⍟⍵                                ⍝ exp of Mean of logs, aka geometric
       (    )                               ⍝ prepend (auto)
  ÷M÷⍵                                      ⍝ recip of Mean of recips, aka harmonic
 (    )                                     ⍝ prepend (auto)

```

## Q'Nial - 68 char

You're going to love this one.

```
op\{$is/[+,tally];^is$*[pass,pass];[1/$(1/),exp$ln,$,sqrt^,/[^,$]]\}

```

Q'Nial is another array-oriented language, an implementation of Nial, which is based on an obscure Array Theory in the sam way Haskell is based on category theory. (Get it here.) It's very different from any of the other three—it parses left-to-right, first of all!—but it is still more related to them than to any other languages.
> 13 votes

# Answer
# 12 languages

---

## CJam, ~~45~~ ~~44~~ 43 bytes

```
q~:Q,:LQWf#:+/Q:*LW##Q:+L/_Q2f#:+L/_mq\@/]`

```

Reads an array of floats (e.g., `[1.0 2.0 3.0 4.0 5.0]`) from STDIN. Try it online.

---

## APL, ~~67~~ ~~61~~ ~~53~~ ~~52~~ 50 bytes

```
{(N÷+/÷⍵)(×/⍵*÷N)A(Q*÷2),(Q←+/(⍵*2)÷N)÷A←+/⍵÷N←⍴⍵}

```

Try it online.

---

## Pyth, ~~55~~ 52 bytes

```
JyzKlJ=YcsJK=Zcsm^d2JK(cKsmc1kJ ^u*GHJc1K Y ^Z.5 cZY

```

Reads space-separated numbers (e.g., `1 2 3 4 5`) from STDIN.

---

## Octave, 68 bytes

```
#!/usr/bin/octave -qf
[mean(I=input(''),"h") mean(I,"g") a=mean(I) q=mean(I.*I)**.5 q*q/a]

```

Not counting the shebang. Reads an array (e.g., `[1 2 3 4 5]`) from STDIN.

---

## GNU bc, 78 bytes

```
#!/usr/bin/bc -l
while(i=read()){h+=1/i;g+=l(i);a+=i;q+=i*i;n+=1}
n/h;e(g/n);a/n;sqrt(q/n);q/a

```

Counting the shebang as 1 byte (`-l` switch). Reads whitespace separated floats from STDIN, followed by a zero.

---

## Awk, 78 bytes

```
#!/usr/bin/awk -f
{h+=1/$0;g+=log($0);a+=$0;q+=$0^2;n++}END{print n/h,exp(g/n),a/n,(q/n)^.5,q/a}

```

Not counting the shebang. Reads one number per line from STDIN.

---

## GolfScript, ~~86~~ 83 bytes

```
n%{~.2.-1:$??./*\`,10\?/\+\;}%..,:^0@{$?+}//p.{*}*^$??p.{+}*^/.p\0\{.*+}/^/.2$??p\/

```

GolfScript has no built-in support for floats, so the code is parsing them. Therefore, the input format is rather restrictive: you must input `1.0` and `0.1` rather than `1`, `1.` or `.1`.

Reads floats (as explained above) one by line, from STDIN. Try it online.

---

## Perl, ~~90~~ 85 bytes

```
#!/usr/bin/perl -n
$h+=1/$_;$g+=log;$a+=$_;$q+=$_**2}{$,=$";print$./$h,exp$g/$.,$a/$.,($q/$.)**.5,$q/$a

```

Counting the shebang as 1 byte (`-n` switch). Reads one number per line from STDIN.

---

## Python 2, ~~102~~ 96 bytes

```
#!/usr/bin/python
h=a=q=n=0;g=1
for i in input():h+=1/i;g*=i;a+=i;q+=i*i;n+=1
print n/h,g**n**-1,a/n,(q/n)**.5,q/a

```

Not counting the shebang. Reads a list of floats (e.g., `1.0,2.0,3.0,4.0,5.0`) from STDIN.

---

## ECMAScript 6 (JavaScript), ~~114~~ 112 bytes

```
m=I=>{for(g=1,h=a=q=n=0,p=Math.pow;i=I.pop();h+=1/i,g*=i,a+=i,q+=i*i)n++;
return[n/h,p(g,1/n),a/n,p(q/n,.5),q/a]}

```

Not counting the LF. Expects an array (e.g., `[1,2,3,4,5]`) as argument.

---

## PHP, 135 (or 108?) bytes

```
#!/usr/bin/php
<?for($c=1;$c<$argc;$c++){$i=$argv[$c];$h+=1/$i;$g+=log($i);$a+=$i;$q+=$i*$i;$n++;}
print_r([$n/$h,exp($g/$n),$a/$n,sqrt($q/$n),$q/$a]);

```

Not counting shebang or LF. Reads floats as command-line arguments.

I have a shorter solution, but I don't know how to count the bytes:

```
php -R '$i=$argn;$h+=1/$i;$g+=log($i);$a+=$argn;$q+=$i^2;$n++;' \
-E 'print_r([$n/$h,exp($g/$n),$a/$n,sqrt($q/$n),$q/$a]);'

```

Counting the bytes in each code string and adding two for `-R` and `-E`, this approach would score 108.

---

## C, ~~172~~ ~~140~~ ~~139~~ ~~137~~ 136 bytes

```
float i,h,g=1,a,q,n;main(){for(;scanf("%f",&i)+1;n++)h+=1/i,g*=i,a+=i,q+=i*i;
printf("%f %f %f %f %f",n/h,pow(g,1/n),a/n,sqrt(q/n),q/a);}

```

Not counting the LF. Compile with `gcc -lm`. Reads whitespace separated floats from STDIN.
> 12 votes

# Answer
# J (50):

This is the sort of thing J is good at:

```
(#%+/@:%),(#%:*/),(+/%#),%:@(%@#*+/@:*:),+/@:*:%+/

```

As always: an explosion in the smiley factory. However, some of the smileys were left intact this time around: `:)` and `:*:` (that's a guy with four eyes and a gem embeded in his face) My interactive session that was used to create this: http://pastebin.com/gk0ksn2b

## In action:

```
   f=:(#%+/@:%),(#%:*/),(+/%#),%:@(%@#*+/@:*:),+/@:*:%+/
   f 1,2,3,4,5
2.18978 2.60517 3 3.31662 3.66667
   f 1.7,17.3,3.14,24,2.718,1.618
3.01183 4.62179 8.41267 12.2341 17.7915
   f 8.6
8.6 8.6 8.6 8.6 8.6
   f 3,123456
5.99985 608.579 61729.5 87296.6 123453
   f 10.1381,29.8481,14.7754,9.3796,44.3052,22.2936,49.5572,4.5940,39.6013,0.9602
5.95799 14.3041 22.5453 27.9395 34.6243
   f 3,4,4,6.2,6.2,6.2
4.5551 4.74682 4.93333 5.10425 5.28108

```

## Explanation:

As you might expect, there are actually 5 functions that are bundled into a list with a train of forks and hooks. (Don't worry about it, it's just a convenient way of making multiple functions output to a single list).

The lines that I used to make J generate this answer might be a bit clearer:

```
   f=:harmonic , Geometric , arithmatic , rms , contraharmonic
   f
harmonic , Geometric , arithmatic , rms , contraharmonic
   f f.
(# % +/@:%) , (# %: */) , (+/ % #) , %:@(%@# * +/@:*:) , +/ %~ +/@:*:

```

Let's look at them separately.

### Harmonic

```
(# % +/@:%)

```
* `#` \- Length (of the array)
* `%` \- Divided by
* `+/@:%` \- The sum (`+/`, or fold `+` in the array (`+/1 2 3 4` == `1+2+3+4`)) atop divide, but this time in the monadic case. What this means here, is that J automatically "guesses" that 1 would be the most useful value.

### Geometric

```
(# %: */)

```
* `#` \- Length (of the array)
* `%:` \- Root (`4 %: 7` would mean 'the fourth (or tesseract) root of seven)
* `*/` \- Product (`*/` is similar in meaning to `+/`, see the previous function for this)

### Arithmetic

```
(+/ % #)

```
* `+/` \- sum, should be familiar now
* `%` \- divided by
* `#` \- Lenght

### Root mean square

```
%:@(%@# * +/@:*:)

```

Ehm, yeah...

* `%:` \- The root of
    + `%@#` \- The inverse of the lenght
    + `*` \- Times
    + `+/@:*:` \- The sum of the squares (`*:` is squared, even though `*~` is as well.)

### Contraharmonic

```
+/@:*: % +/

```
* `+/@:*:` \- The sum of the squares
* `%` \- divided by
* `+/` \- the sum.

> I actually found out that my function was ~~one byte~~ two bytes too long by explaining this, so that's good!

If J were just this good at processing strings, we'd be winning a lot more golfing competitions...
> 6 votes

# Answer
# Languages: 3

Unless noted otherwise, numbers need to be seperated by space.

## C: 181 163

Takes numbers till end of input.

```
#include<math.h>
main(){double h=0,g=1,a=0,q=0,k,n=0;for(;scanf("%lf",&k);++n)h+=1/k,g*=k,a+=k,q+=k*k;printf("%f %f %f %f %f\n",n/h,pow(g,1/n),a/n,sqrt(q/n),q/a);}

```

## (ISO) C++: 195

Takes numbers till end of input.

```
#include<iostream>
#include<cmath>
int main(){double h=0,g=1,a=0,q=0,k,n=0;for(;std::cin>>k;++n)h+=1/k,g*=k,a+=k,q+=k*k;std::cout<<n/h<<" "<<pow(g,1/n)<<" "<<a/n<<" "<<sqrt(q/n)<<" "<<q/a<<"\n";}

```

## Haskell: 185 180 164 159 149 140

Takes arbitrarily many lists of numbers seperated by newline.

### Implementation

```
m=map
f x=let{s=sum;n=s$m(\_->1)x;t=s$m(^2)x}in[n/s(m(1/)x),product x**(1/n),s x/n,sqrt$t/n,t/s x]
main=getLine>>=print.f.m read.words>>main

```

50 41 (thanks shiona) bytes are just for IO :/.

### Example

(Powershell's `echo` aka `Write-Output` prints every parameter on a single line)

```
PS> echo "1 2 3 4 5" "1.7 17.3 3.14 24 2.718 1.618" | runhaskell SO.hs
[2.18978102189781,2.605171084697352,3.0,3.3166247903554,3.6666666666666665]
[3.011834514901806,4.621794669196026,8.412666666666668,12.234139719108438,17.791525635945792]

```
> 5 votes

# Answer
# Languages: 5

### POV-Ray 3.7 Scene Description Language: 304 bytes

```
#fopen I"i"read#declare S=0;#declare N=0;#declare Q=0;#declare P=1;#declare R=0;#while(defined(I))#read(I,V)#declare S=S+V;#declare N=N+1;#declare Q = Q+V*V;#declare P=P*V;#declare R=R+1/V;#end#warning concat(str(N/R,0,5),",",str(pow(P,1/N),0,5),",",str(S/N,0,5),",",str(sqrt(Q/N),0,5),",",str(Q/S,0,5))

```

(POV-Ray SDL doesn't have console input functions, so I've substituted file input. Output is to the console, but is surrounded by a good deal of program status output.)

### Commodore BASIC: 111 104 bytes

```
1 P=1:O┐1,0
2 I/#1 V:IF V=0T|G┌4
3 S=S+V:N=N+1:Q=Q+V*V:P=P*V:R=R+1/V:G┌2
4 ?N/R,P↑(1/N),S/N,(Q/N)↑.5,Q/S

```

(Not all of the characters in this program can be represented in Unicode. `|` is used to represent `SHIFT+H`,  represents `SHIFT+O`,  represents `SHIFT+P`, `/` represents `SHIFT+N`. Because of the limitations in Commodore Basic I/O, the input is entered one number at a time, with an input of -1 to indicate the end of input. Output is tab-delimited.)

### QBasic: 96 bytes

```
P=1:INPUT V:WHILE V:S=S+V:N=N+1:Q=Q+V*V:P=P*V:R=R+1/V:INPUT V:WEND:?N/R;P^(1/N);S/N;(Q/N)^.5;Q/S

```

Uses the same I/O scheme as DLosc's entry; I golfed 15 bytes off by using the fact that `INPUT V` returns 0 (which evaluates to false) when an empty line is input (at least in MS-DOS QBasic 1.1 -- I don't know if it also works in QB64).

### Pascal (FPC compiler): 172 bytes

```
program M;uses math;var v,p,s,n,q,r:real; begin p:=1;while not eoln do begin read(v);s:=s+v;n:=n+1;q:=q+v*v;p:=p*v;r:=r+1/v end;write(n/r,p**(1/n),s/n,(q/n)**0.5,q/s);end.

```

The input is separated by spaces, not commas, and is newline terminated. Output is space-separated.

### Erlang: 401 bytes

```
-module(means).
-import(io).
-import(math).
-import(string).
-import(lists).
-export([means/6]).

means(S,N,Q,P,R,[]) -> io:fwrite("~f,~f,~f,~f,~f~n", [N/R,math:pow(P,(1/N)),S/N,math:sqrt(Q/N),Q/S]);
means(S,N,Q,P,R,[V|T]) -> means(S+V,N+1,Q+V*V,P*V,R+1/V,T).

means:means(0,0,0,1,0,lists:map(fun({F,R}) -> F end, lists:map(fun(X) -> string:to_float(X) end, string:tokens(io:get_line(""), ",\n")))).

```

String handling in Erlang is a royal pain. Consequently, all floating-point numbers must be entered with at least one digit after the decimal point -- `string:to_float/1` will not convert `1`, but will convert `1.0`.

(More to come, especially if I figure out how to do this in RoboTalk, a language with neither floating-point operations nor I/O)
> 5 votes

# Answer
# Languages - 4

I always love an excuse to pull out good old

## QBasic, ~~112~~ 96 bytes

```
g=1:INPUT x:WHILE x:h=h+1/x:g=g*x:a=a+x:q=q+x^2:n=n+1:INPUT x:WEND:?n/h;g^(1/n);a/n;SQR(q/n);q/a

```

QBasic isn't good with variable numbers of inputs, so the program requires one number per line, terminated with 0 or an empty line. Output is separated with spaces.

(Shortened once I realized that 0 isn't a valid number and can be used for input termination.)

Tested using QB64:

## Common Lisp, 183 bytes

```
(defun m(l)(let((a(apply #'+ l))(q(apply #'+(map'list #'(lambda(x)(* x x))l)))(n(length l)))(list(/ n(apply #'+(map'list #'/ l)))(expt(apply #'* l)(/ n))(/ a n)(sqrt(/ q n))(/ q a))))

```

For some reason I expected this to be shorter. I'm not any kind of Lisp expert, so tips are appreciated. Ungolfed version:

```
(defun means (l)
  (let ((a (apply #'+ l))                                    ; sum of numbers
        (q (apply #'+ (map 'list #'(lambda (x) (* x x)) l))) ; sum of squares
        (n (length l)))
    (list                                 ; Return a list containing:
      (/ n (apply #'+ (map 'list #'/ l))) ; n over sum of inverses
      (expt (apply #'* l) (/ n))          ; product to the power of 1/n
      (/ a n)                             ; a/n
      (sqrt (/ q n))                      ; square root of q/n
      (/ q a)                             ; q/a
    )
  )
)

```

Probably the best way to test is by pasting the function into the `clisp` REPL, like so:

```
$ clisp -q
[1]> (defun m(l)(let((a(apply #'+ l))(q(apply #'+(map'list #'(lambda(x)(* x x))l)))(n(length l)))(list(/ n(apply #'+(map'list #'/ l)))(expt(apply #'* l)(/ n))(/ a n)(sqrt(/ q n))(/ q a))))
M
[2]> (m '(1 2 3 4 5))
(300/137 2.6051712 3 3.3166249 11/3)
[3]> (m '(8.6))
(8.6 8.6 8.6 8.6 8.6)
[4]> (m '(3 123456))
(246912/41153 608.5787 123459/2 87296.58 5080461315/41153)

```

I love how Lisp uses exact fractions instead of floats when dividing two integers.

## Prolog, 235 bytes

Prolog isn't great at math, but we're gonna use it anyway. Tested with SWI-Prolog. I think the `sumlist` predicate may not be standard Prolog, but whatever, I'm using it.

```
m(L,H,G,A,Q,C):-length(L,N),h(L,I),H is N/I,p(L,P),G is P^(1/N),sumlist(L,S),A is S/N,q(L,R),Q is sqrt(R/N),C is R/S.
p([H|T],R):-p(T,P),R is H*P.
p([],1).
q([H|T],R):-q(T,P),R is H*H+P.
q([],0).
h([H|T],R):-h(T,P),R is 1/H+P.
h([],0).

```

Ungolfed:

```
m(L, H, G, A, Q, C) :-
        length(L, N),   % stores the length into N
        h(L, I),        % stores the sum of inverses into I
        H is N/I,
        p(L, P),        % stores the product into P
        G is P^(1/N),
        sumlist(L, S),  % stores the sum into S
        A is S/N,
        q(L, R),        % stores the sum of squares into R
        Q is sqrt(R/N),
        C is R/S.

% Helper predicates:

% p calculates the product of a list
p([H|T], R) :-
        p(T, P),     % recursively get the product of the tail
        R is H*P.    % multiply that by the head
p([], 1).            % product of empty list is 1

% q calculates the sum of squares of a list
q([H|T], R) :-
        q(T, P),     % recursively get the sum of squares of the tail
        R is H*H+P.  % add that to the square of the head
q([], 0).            % sum of empty list is 0

% h calculates the sum of inverses of a list
h([H|T], R) :-
        h(T, P),     % recursively get the sum of inverses of the tail
        R is 1/H+P.  % add that to the inverse of the head
h([], 0).            % sum of empty list is 0

```

On Linux, with the code in a file called `means.pro`, test like this:

```
$ swipl -qs means.pro
?-  m([1,2,3,4,5],H,G,A,Q,C).
H = 2.18978102189781,
G = 2.605171084697352,
A = 3,
Q = 3.3166247903554,
C = 3.6666666666666665.

```

Gives a correct but rather amusing result when there's only one number:

```
 ?- m([8.6],H,G,A,Q,C).
 H = G, G = A, A = Q, Q = C, C = 8.6.

```

## Python 3, 103 bytes

```
h=a=q=n=0;g=1
for x in eval(input()):h+=1/x;g*=x;a+=x;q+=x*x;n+=1
print(n/h,g**(1/n),a/n,(q/n)**.5,q/a)

```

Same strategy as Dennis's Python 2 version. Takes a comma-separated list of numbers; handles both ints and floats. A single-number input must be wrapped in square braces (and a list of numbers always *may* be); a fix would cost 4 bytes.
> 4 votes

# Answer
# 8 Languages

## Fortran 77 - 286

```
      READ*,l
      b1=0
      b2=1
      b3=0
      b4=0
      DO 10 i=1,l
        READ*,j
        b1=b1+1/j
        b2=b2*j
        b3=b3+j
        b4=b4+j**2
   10 CONTINUE
      h=l/b1
      g=b2**(1/l)
      a=b3/l
      q=(b4/l)**0.5
      c=b4/b3
      PRINT*,h,g,a,q,c
      END

```

## BBC BASIC - 131

```
INPUT l
b=0:d=1:e=0:f=0
FOR i=1 TO l
  INPUTj:b+=1/j:d*=j:e+=j:f+=j^2
NEXT l
h=l/b:g=d^(1/l):a=e/l:q=(f/l)^0.5:c=f/e
PRINTh,g,a,q,c

```

**Output:**

```
5
5
100
12
15
1
9.7914836236097695 26.600000000000001 45.596052460711988 78.15789473684211

```

## C++ - 292

```
#include <iostream>
#include <cmath>
using namespace std;int main(){cout << "Length of sequence?: ";cin >> l;int b=0;int d=1;int e=0;int f=0;int j;int seq[l];for(int i=0;i<l;i++){cin >> j;b+=1/j;d*=j;e+=j;f+=pow(j,2);}
    h=l/b;g=pow(d,(1/l));a=e/l;q=pow((f/l),0.5);c=f/e;cout << h,g,a,q,c;}

```

## Python 3 - 151

```
s=input().split(',');l=len(s);b=0;d=1;e=0;f=0
for i in s:i=float(i);b+=1/i;d*=i;e+=i;f+=i**2
h=l/b;g=d**(1/l);a=e/l;q=(f/l)**0.5;c=f/e
print(h,g,a,q,c)

```

**Output:**

```
5,100,12,15,1       # Input
3.6764705882352944 9.7914836236097695 26.600000000000001 45.596052460711988 78.15789473684211

```

## Java - 421

```
class Sequences {
    public static void main( String[] args){
        System.out.println("Length of sequence?: ");Scanner reader = new Scanner(System.in);l=reader.nextInt();int b=0;int d=1;int e=0;int f=0;int j;int seq[l];
        for(int i=0;i<l;i++){j=reader.nextInt();b+=1/j;d*=j;e+=j;f+=Math.pow(j,2);}
        h=l/b;g=Math.pow(d,(1/l));a=e/l;q=Math.sqrt(f/l);c=f/e;System.out.println(h+' '+g +' '+ a+' '+q+' '+c);}}

```

## Javascript - 231

I'm not a Javascripter so any tips would be greatly appreciated

```
console.log("Length of sequence?: ");
var l=readline(),b=0,d=1,e=0,f=0;
for(var i = 0;i<l;i++) {var j=readline();b+=1/j;d*=j;e+=j;f+=pow(j,2);}
h=l/b;g=pow(d,(1/l));a=e/l;q=sqrt(f/l);c=f/e;
console.log(h+' '+g+' '+a+' '+q+' '+c);

```

## Algoid - 337

Look it up on the Google Play Store or the Raspberry Pi Store

```
text.clear();
set l=text.inputNumber("Length of sequence?: ");set b=0;set d=1;set e=0;set f=0;set seq=array{};
for(set i=1; i<=l; i++){set j=text.inputNumber(i..": ");b+=1/j;d*=j;e+=j;f+=math.pow(j,2);}
set h=l/b;set g=math.pow(d,(1/l));set a=e/l;set q=math.sqrt(f/l);set c=f/l;set str=h.." "..g.." "..a.." "..q.." "..c;text.output(str);

```

# var'aQ - 376

This is syntactically correct and all, but all current interpreters just *don't work*...

```
0 ~ b cher
1 ~ d cher
0 ~ e cher
0 ~ f cher
'Ij mI'moH ~ l cher
l {
    'Ij mI'moH ~ j cher
    b 1 j wav boq ~ b cher
    d j boq'egh ~ d cher
    e j boq ~ e cher
    f j boqHa'qa boq ~ f cher
} vangqa'
l b boqHa''egh ~ h cher
d 1 l boqHa''egh boqHa'qa  ~ g cher
e l boqHa''egh ~ a cher
f l boqHa''egh loS'ar ~ q cher
f e boqHa''egh c cher
h cha'
g cha'
a cha'
q cha'
c cha'

```
> 4 votes

# Answer
# Languages: 3

## CJam, 58

```
qS%:d:A{1\/}%:+A,\/SA:*1.A,/#SA:+A,/:BSA{2#}%:+A,/:CmqSCB/

```

## TI-Basic, 85

```
Input L1:{dim(L1)/sum(1/(L1),dim(L1)√prod(L1),mean(L1),√(mean(L1²)),mean(L1²)/mean(L1

```

## Java, 457

```
import java.util.*;class C{public static void main(String[]s){List r=new ArrayList();double[]d=Arrays.stream(new Scanner(System.in).nextLine().split(",")).mapToDouble(Double::new).toArray();double x=0,y,z;for(double D:d){x+=1/D;}r.add(d.length/x);x=1;for(double D:d){x*=D;}r.add(Math.pow(x,1./d.length));r.add(y=Arrays.stream(d).average().getAsDouble());x=1;for(double D:d){x+=D*D;}r.add(Math.sqrt(z=x/d.length));r.add(z/y);r.forEach(System.out::println);}}

```
> 3 votes

# Answer
# Languages - 2

## Cobra - 132

```
def f(l as number[])
    a,b,c,d=0d,1d,0d,0d
    for i in l,a,b,c,d=a+1/i,b*i,c+i,d+i**2
    print (e=l.length)/a,b**(1/e),c/e,(d/e)**0.5,d/c

```

## Python - 129

```
def f(l):a,b,c=len(l),sum(i*i for i in l),sum(l);print(a/sum(1/i for i in l),eval('*'.join(map(str,l)))**(1/a),c/a,(b/a)**.5,b/c)

```
> 3 votes

# Answer
## Languages: 5

Some entries strive to avoid rounding errors (to 4 decimal places), using Java's BigDecimal instead of float/double, and accept IO rules per OP.

Newer entries relax both IO rules and BigDecimal.

## Groovy - 409 400 164 157 chars

```
float i=0,j=1,k=0,l,n=0,m=0,p;args.each{x=it as float;i+=1/x;j*=x;k+=x;m+=x*x;n++};l=k/n;p=m/n;println "${n/i},${Math.pow(j,1f/n)},$l,${Math.sqrt p},${p/l}"

```

sample run:

```
bash$ groovy F.groovy 10.1381 29.8481 14.7754 9.3796 44.3052 22.2936 49.5572 4.5940 39.6013 0.9602
5.957994213465398,14.304084339049883,22.545269,27.939471625408938,34.62429631138658

```

## Java - 900 235 chars

```
class F{public static void main(String[]a){float i=0,j=1,k=0,l,n=0,m=0,p;for(String s:a){float x=Float.valueOf(s);i+=1/x;j*=x;k+=x;m+=x*x;n++;}l=k/n;p=m/n;System.out.println(n/i+","+Math.pow(j,1f/n)+","+l+","+Math.sqrt(p)+","+p/l);}}

```

sample run:

```
bash$ java F 10.1381 29.8481 14.7754 9.3796 44.3052 22.2936 49.5572 4.5940 39.6013 0.9602
5.957994,14.304084906138343,22.545269,27.939471625408938,34.6243

```

## Clojure - 524 324 chars

```
(defn r[x](/ (reduce + 0.0 x)(count x)))
(defn s[x](reduce #(+ %1 (* %2 %2)) 0.0 x))
(defn f[x](let[n (* 1.0 (count x))][(/ n(reduce #(+ %1 (/ 1.0 %2)) 0.0 x))(Math/pow(reduce * x)(/ 1.0 n))(r x)(Math/sqrt(/(s x) n))(/(/(s x) n)(r x))]))
(doseq [x(f(map #(Float/valueOf %) *command-line-args*))](print(str x ",")))
(println)

```

sample run (it does have a trailing comma at the end):

```
bash$ java -jar clojure-1.6.0.jar m2.clj 10.1381,29.8481,14.7754,9.3796,44.3052,22.2936,49.5572,4.5940,39.6013,0.9602
5.957994368133907,14.30408424976292,22.545269936323166,27.93947151073554,34.62429460831333,

```

## Scala - 841 663 230 chars

```
import java.math._
object F{def main(a:Array[String]){
var i,j,k,l,m,p=0f;var n=0
a.foreach{y=>var x=y.toFloat;i+=1/x;j*=x;k+=x;m+=x*x;n+=1}
l=k/n;p=m/n;System.out.println(n/i+","+Math.pow(j,1f/n)+","+l+","+Math.sqrt(p)+","+p/l)}}

```

sample run:

```
bash$ scala F.scala 10.1381 29.8481 14.7754 9.3796 44.3052 22.2936 49.5572 4.5940 39.6013 0.9602
5.957994,0.0,22.545269,27.939471625408938,34.6243

```

## JRuby - 538 chars

It is unclear if JRuby differs from Ruby: this must run on the JVM. Yet it is Ruby syntax. Either way, I'm including it in the spirit of a Rosetta Stone.

```
require 'java'
java_import 'java.math.BigDecimal'
o=BigDecimal::ONE
z=BigDecimal::ZERO
def b(s) java.math.BigDecimal.new s end
def p(x,y) java.lang.Math::pow(x.doubleValue,y.doubleValue) end
def d(x,y) x.divide y,5,BigDecimal::ROUND_UP end
def r(x,n) d(x.inject(b(0)){|a,v|a.add v},n) end
def s(x) x.inject(b(0)){|a,v|a.add(v.multiply v)} end
x=[]
ARGV[0].split(",").each{|i|x<<b(i)}
n=b x.size
puts "#{d n,x.inject(z){|a,v|a.add(d o,v)}},#{p x.inject(o){|a,v|a.multiply v},d(o,n)},#{r(x,n)},#{p d(s(x),n),b("0.5")},#{d d(s(x),n),r(x,n)}"

```

sample run (does print a warning to stderr):

```
bash$ jruby Mean.rb 10.1381,29.8481,14.7754,9.3796,44.3052,22.2936,49.5572,4.5940,39.6013,0.9602
5.95781,14.30408436301878,22.54527,27.939471541172715,34.62430

```
> 3 votes

# Answer
## 1 Language

### Golfscript, 162

```
n/:@,:^;'(1.0*'@'+'*+')/'+^+'('@'*'*+')**(1.0/'+^+')'+^'/(1.0/'+@'+1.0/'*+')'+'(1.0/'^+'*('+@'**2+'*+'**2))**0.5'+'('@'**2+'*+'**2)/'+4$+'*'+^+]{'"#{'\+'}"'+~}%n*

```

Yes, it's huge. And it can definitely be made smaller. Which I will do sometime later. Try it out here.

It expects the input to be newline separated. If that is not allowed, I'll fix it (+2 chars). It outputs the list newline separated.

Here's a slightly more readable version:

```
n/:@,:^;
'(1.0*'@'+'*+')/'+^+
'('@'*'*+')**(1.0/'+^+')'+
^'/(1.0/'+@'+1.0/'*+')'+
'(1.0/'^+'*('+@'**2+'*+'**2))**0.5'+
'('@'**2+'*+'**2)/'+4$+'*'+^+
]{'"#{'\+'}"'+~}%
n*

```
> 3 votes

# Answer
# 1 language

---

## R, ~~92~~ 91

```
f=function(x){n=length(x);s=sum;d=s(x^2);c(n/s(1/x),prod(x)^(1/n),mean(x),(d/n)^.5,d/s(x))}

```

Takes a vector of value and output a vector of means.
> 3 votes

# Answer
# Languages 2

## Fortran: 242

I've ungolfed it for clarity, but the golfed version is what is counted. you first need to input the number of values to be added, then the values.

```
program g
   real,allocatable::x(:)
   read*,i
   allocate(x(i));read*,x
   print*,m(x)
 contains
   function m(x) result(p)
      real::x(:),p(5)
      n=size(x)
     p(1:4)=[n/sum(1/x),product(x)**(1./n),sum(x)/n,sqrt(sum(x**2)/n)]
     p(5)=p(4)**2/p(3)
   endfunction
end

```

## wxMaxima 134

Copy this into the editor, `ctrl+enter` and then call via `m([1,2,3,4,5]),numer` to get floating point output (otherwise you get symbolic output).

```
m(x):=block([n:length(x),d:0,c:mean(x)],for i:1 thru n do(g:x[i],d:d+g*g),return([1/mean(1/x),apply("*",x)^(1/n),c,sqrt(d/n),d/n/c]));

```
> 3 votes

# Answer
# Perl, 86 76

```
$,=$";$h+=1/uc,$g+=log,$a+=lc,$q+=$_**2for<>;print$./$h,exp$g/$.,$a/$.,sqrt$q/$.,$q/$a

```

Input: one number per line.

EDIT: this is one character longer, but since apparently shebang lines aren’t counted toward the total, it ends up being better:

```
#!perl -pl
$"+=1/uc,$,+=log,$}+=lc,$;+=$_**2}for($./$",exp$,/$.,$}/$.,sqrt$;/$.,$;/$}){

```
> 3 votes

# Answer
## T-SQL, ~~136~~ 122

With the number lists stored in table S with I (integer) identifying the list and V (float) the value.

```
SELECT COUNT(*)/SUM(1/V),EXP(SUM(LOG(V))/COUNT(*)),AVG(V),SQRT((1./COUNT(*))*(SUM(V*V))),SUM(V*V)/SUM(V) FROM S GROUP BY I

```

SQLFiddle

Saved 14 thanks to Alchymist
> 3 votes

# Answer
# Languages 1

### lua - 113

```
e=arg s=#e h,g,a,r=0,1,0,0 for i=1,s do x=e[i]h=h+1/x g=g*x a=a+x/s r=r+x^2/s end print(s/h,g^(1/s),a,r^.5,r/a)

```
> 2 votes

# Answer
# Languages - 1

### Groovy:

```
def input = [1.7,17.3,3.14,24,2.718,1.618];
def arithmeticMean
def harmonicMean
def geometricMean
def quadraticMean
def contraharmonicMean

def sum = 0
def product = 1
// Arithmetic Mean
for(each in input){
    sum += each
}
arithmeticMean = sum / input.size()

// Harmonic Mean
sum = 0
for(each in input){
    sum += (1/each)
}
harmonicMean = input.size() / sum

// Geometric Mean
for(each in input){
    product *= each
}
geometricMean = Math.pow(product,1/input.size());

// Quadratic Mean
sum = 0
for(each in input){
    sum += (each*each)
}
quadraticMean = Math.pow(sum/input.size() ,(1/2))

// Contraharmonic Mean
sum = 0
def sum2 = 0
for( each in input ){
    sum += each
    sum2 += (each * each)
}
contraharmonicMean = (sum2/input.size()) / (sum/input.size())

println "Arithmetic Mean: $arithmeticMean"
println "Harmonic Mean: $harmonicMean"
println "Geometric Mean: $geometricMean"
println "Quadratic Mean: $quadraticMean"
println "Contraharmoic Mean: $contraharmonicMean"

```
> 2 votes

# Answer
# 2 Languages

# Java - 243 bytes

```
class M{public static void main(String[]a){float h=0,l=a.length,p=1,s=0,q=0;for(int i=0;i<l;i++){float v=Float.valueOf(a[i]);q+=v*v;s+=v;h+=1/v;p*=v;}System.out.println(l/h+"\n"+Math.pow(p,1.0/l)+"\n"+s/l+"\n"+Math.sqrt((1.0/l)*q)+"\n"+q/s);}}

```

expanded:

```
class Means {
    public static void main(String[] a) {
        float h = 0, l = a.length, p = 1, s = 0, q = 0;
        for (int i = 0; i < l; i++) {
            float v = Float.valueOf(a[i]);
            q += v * v;
            s += v;
            h += 1 / v;
            p *= v;
        }
        System.out.println(l / h + "\n" + Math.pow(p, 1.0 / l) + "\n" + s / l
                + "\n" + Math.sqrt((1.0 / l) * q) + "\n" + q / s);
    }
}

```

# vba - excel, 387 bytes

Fill in values in the first column, then press the button (that triggers this code) and it outputs the values in the second column.

```
Private Sub a_Click()
Dim d,s,q,h,p As Double
Dim y As Integer
h=0
q=0
s=0
p=1
y=1
While Not IsEmpty(Cells(y,1))
s=s+Cells(y,1)
q=q+Cells(y,1)*Cells(y,1)
h=h+1/Cells(y,1)
p=p*Cells(y,1)
y=y+1
Wend
y=y-1
Cells(1,2)=y/h
Cells(2,2)=p^(1/y)
Cells(3,2)=s/y
Cells(4,2)=((1/y)*q)^0.5
Cells(5,2)=q/s
End Sub

```
> 2 votes

# Answer
# 1 language

## Rust - 469

(`rustc 0.11.0-pre (3851d68 2014-06-13 22:46:35 +0000)`)

```
use std::io;use std::from_str::from_str;use std::num;fn main(){loop{let a:Vec<f64>=io::stdin().read_line().ok().expect("").as_slice().split(',').map(|x|std::from_str::from_str(x.trim_chars('\n')).expect("")).collect();let n:f64=num::from_uint(a.len()).expect("");let s=a.iter().fold(0.0,|a,b|a+*b);let q=a.iter().fold(0.0,|a,b|a+*b* *b);println!("{},{},{},{},{}",n / a.iter().fold(0.0,|a,b|a+1.0/ *b),(a.iter().fold(1.0,|a,b|a**b)).powf(1.0/n),s/n,(q/n).sqrt(),q/s,);}}

```

Ungolfed version:

```
use std::io;
use std::from_str::from_str;
use std::num;

fn main() {
    loop {
        let a : Vec<f64>  = io::stdin().read_line().ok().expect("").as_slice().split(',')
                               .map(|x|std::from_str::from_str(x.trim_chars('\n')).expect("")).collect();
        let n : f64 = num::from_uint(a.len()).expect("");
        let s = a.iter().fold(0.0, |a, b| a + *b);
        let q = a.iter().fold(0.0, |a, b| a + *b * *b);
        println!("{},{},{},{},{}",
                 n / a.iter().fold(0.0, |a, b| a + 1.0 / *b),
                 (a.iter().fold(1.0, |a, b| a * *b)).powf(1.0/n),
                 s / n,
                 (q / n).sqrt(),
                 q / s,
                 );
    }
}

```

Compacted 430-byte version without loop or input, for testing in playrust:

```
use std::from_str::from_str;use std::num;fn main(){let a:Vec<f64>="1,2,3,4".as_slice().split(',').map(|x|std::from_str::from_str(x.trim_chars('\n')).expect("")).collect();let n:f64=num::from_uint(a.len()).expect("");let s=a.iter().fold(0.0,|a,b|a+*b);let q=a.iter().fold(0.0,|a,b|a+*b**b);println!("{},{},{},{},{}",n / a.iter().fold(0.0, |a, b| a + 1.0 / *b),(a.iter().fold(1.0, |a, b| a * *b)).powf(1.0/n),s/n,(q/n).sqrt(),q/s);}

```

---

Updated for newer Rust:

Ungolfed:

```
use std::io;
fn main(){
    let mut s=String::new();
    io::stdin().read_line(&mut s);
    let a:Vec<f64>=s
        .split(',')
        .map(|x|x.trim().parse().expect(""))
        .collect();
    let n:f64=a.len() as f64;
    let s=a.iter().fold(0.0,|a,b|a+*b);
    let q=a.iter().fold(0.0,|a,b|a+*b**b);
    println!("{},{},{},{},{}",
        n / a.iter().fold(0.0, |a, b| a + 1.0 / *b),
        (a.iter().fold(1.0, |a, b| a * *b)).powf(1.0/n),s/n,
        (q/n).sqrt(),q/s);
}

```

Golfed (402 bytes):

```
use std::io;fn main(){ let mut s=String::new(); io::stdin().read_line(&mut s); let a:Vec<f64>=s .split(',') .map(|x|x.trim().parse().expect("")) .collect(); let n:f64=a.len() as f64; let s=a.iter().fold(0.0,|a,b|a+*b); let q=a.iter().fold(0.0,|a,b|a+*b**b); println!("{},{},{},{},{}", n / a.iter().fold(0.0, |a, b| a + 1.0 / *b), (a.iter().fold(1.0, |a, b| a * *b)).powf(1.0/n),s/n, (q/n).sqrt(),q/s);}

```
> 2 votes

# Answer
# Languages: 4

## CoffeeScript, 193

Takes a comma-separated string of input:

```
m=(q)->m=Math;q.r=q.reduce;q=q.split(',').map Number;l=q.length;x=q.r ((p,v)->(p+v)),0;y=q.r ((p,v)->(p+v*v)),0;[l/q.r(((p,v)->(p+1/v)),0),m.pow(q.r(((p,v)->(p*v)),1),1/l),x/l,m.sqrt(y/l),y/x];

```

## JavaScript (ES5), 256

Again, takes a comma-separated string of input:

```
function m(q){m=Math,q=q.split(',').map(Number),q.r=q.reduce,l=q.length,x=q.r(function(p, v){return p+v;},0),y=q.r(function(p,v){return p+v*v},0);return[l/q.r(function(p,v){return p+1/v},0),m.pow(q.r(function(p,v){return p*v},1),1/l),x/l,m.sqrt(y /l),y/x]}

```

## PHP, 252

Same concept:

```
<?function m($q){$r=array_reduce;$q=explode(',',$q);$l=count($q);$x=array_sum($q);$y=$r($q,function($p,$v){return $p+$v*$v;});return[$l/$r($q,function($p,$v){return $p+1/$v;}),pow($r($q,function($p,$v){return $p*$v;},1),1/$l),$x/$l,sqrt($y/$l),$y/$x];}

```

## TypeScript, 393\*

Since TypeScript is a superset of JavaScript, I could have just submitted the same code but that wouldn't really be fair now. Here's a minified TypeScript code with all functions, variables, and parameters fully typed:

```
function m(q:String):number[]{var a:number[]=q.split(',').map(Number),l:number=a.length,x:number=a.reduce(function(p:number,v:number):number{return p+v},0),y:number=a.reduce(function(p:number,v:number):number{return p+v*v},0);return[l/a.reduce(function(p:number,v:number):number{return p+1/v},0),Math.pow(a.reduce(function(p:number,v:number):number{return p*v},1),1/l),x/l,Math.sqrt(y/l),y/x]}

```

Could have cheated and used the type `any` as well... but, you know.
> 1 votes

# Answer
# Excel - 120

Not sure if this counts as a "programming" language, but thought people may actually use a spreadsheet for this type of thing

With the numbers in A2:J2

```
L2 (harmonic) =HARMEAN(A2:J2)
M2 (geometric) =GEOMEAN(A2:J2)
N2 (arithmetic) =AVERAGE(A2:J2)
O2 (quadratic) =SQRT(SUMSQ(A2:J2)/COUNT(A2:J2))
P2 (contraharmonic) =(SUMSQ(A2:J2)/COUNT(A2:J2))/AVERAGE(A2:J2)

```
> 0 votes

# Answer
## VBA (Excel) - 105

```
a=1:for each n in i:a=a*n:b=b+1/n:c=c+n:d=d+n*n:next:x=ubound(i)+1:?x/b","a^(1/x)","c/x","(d/x)^0.5","d/c

```

Ungolfed :

```
a=1:               set a variable to 1 (for the geometric mean)
for each n in i:   loop through the list
    a=a*n:            product of the list
    b=b+1/n:          sum of inverses of the list
    c=c+n:            sum of the list
    d=d+n*n:          sum of squares of the list
next:              end loop
x=ubound(i)+1:     get the number of elements in the list
?                  prepare to print
 x/b","               harmonic = count / sum(inverses)
 a^(1/x)","           geometric = product^(1/count)
 c/x","               arithmetic = sum / count
 (d/x)^0.5","         quadratic = square root of ( sum of squares / count )
 d/c                  contraharmonic = sum of squares / sum

```

This code has to be run in the immediate window, and the array must be called *i*. Since there is no error collection, no cleaning, no variable dropping/releasing, if you want to test this code you can use the following piece of code (just paste in the immediate window and run the lines in order) :

```
b=0:c=0:d=0:set i = nothing:i= array(1,2,3,4,5)
a=1:for each n in i:a=a*n:b=b+1/n:c=c+n:d=d+n*n:next:x=ubound(i)+1:?x/b","a^(1/x)","c/x","(d/x)^0.5","d/c

```

Nothing very special, just the choice to use the immediate window with *:* to replace line breaks, which saves a few bytes vs setting up a sub or function and closing it; using ? to print rather than debug.print (only in the immediate window); and relying on how vba determines implicit values (adding a value to an un-set variable returns the value) and implicit operations (anything involving a string is implicitly concatenation).
> 0 votes

---
Tags: code-golf, rosetta-stone
---


title: Outputting a base-proof expression

text:
# Question
Title: Outputting a base-proof expression
## Background

In some possible futures, the world will convert their numerical systems from decimal (base 10 or `b10`) to some other base (binary `b2`, octal `b8`, hexadecimal `b16`, or even unary `b1`, in which case we're screwed!). Thus, in preparation for this possible world-changing event, you decide to base-proof all of your programs. This can be done by using only singular `0`s and `1`s in conjunction with operators to replace the existing number constants.

However, there's just one problem: You have a ton of programs to change, and manually converting each number to an expression would take weeks! Thus, you decide to write a program (or function) to decide for you what expression should replace each number.

## Input

The input will be a positive integer. Your code **must** be able to handle any integer up to 1000.

(If your code supports decimals and/or negative inputs, see **Scoring** below.)

## Output

Your code must output an expression that evaluates to the input in at least one language. This may be any language; it does not have to be the same one your program or function is written in. Also, this expression does not need to be a full program or function.

For clarity, the output may contain any of these operations:

* increment / decrement
* add / sum
* subtract / negate
* multiply / double (only if it doesn't directly involve the number `2`!)
* divide / modulo
* exponents / logarithms
* square / sqrt (again, only if these don't directly involve the number `2`!)
* bitwise operations (bOR, bAND, bNOT, bXOR, bit-shifts)
* setting / getting variables
* stack manipulation

You may **not** use `eval()` or any similar functions in the output. You may also not use in the output any functions that perform an action(s) other than the ones mentioned above.

Oh, and one more thing: since we want the output to be valid in as many bases as possible, the only number constants it may contain are `0` and `1`. Numbers such as `10` (ten) are disallowed, unless the language interprets it as a `1` and a `0`. Using strings to contain numbers is not allowed either, as is using characters such as CJam's `A`-`K` (which represent `10`-`20`).

## Test-cases

(All outputs are in JavaScript, but may work in other languages.)

**Input 1:**

```
2

```

**Possible output 1:**

```
1+1

```

**Input 2:**

```
13

```

**Possible output 2:**

```
(a=1+1+1)*a+a+1

```

**Input 3:**

```
60

```

**Possible output 3:**

```
(b=(a=1+1+1+1)*a)*a-a

```

**Input 4:**

```
777

```

**Possible output 4:**

```
(c=(b=((a=1+1+1+1)*a-a+1)*a)*a+b)+c+c-a+1

```

**Input 5:**

```
1000

```

**Possible output 5:**

```
Math.pow((a=1+1+1)*a+1,a)

```

---

## Scoring

The goal of this challenge is to shorten your code's output as much as possible. Your score will be calculated in this way:

* **Base score:** The average byte-count of all outputs for integers 1 to 1000.
* **Decimal score:** If your code supports at least 3 decimal places, this is the average byte-count of all outputs of the sequence of numbers starting at `0.001` and ending at `1000`, increasing by `1.001` each time. `0.001, 1.002, 2.003...998.999, 1000.000` Then take 50% off of this score.
* **Negative score:** If your code supports negative numbers and zero, this is the average byte-count of the outputs of all integers from `-1000` to `0`. Then take 10% off of this score.

(The easiest way to calculate these would likely be a loop with your program/function inside.)

**Your final score is the average of whichever of the above formulas apply.**

If the output is non-deterministic (i.e. somewhat random; multiple runs with the same input produces multiple unique outputs), then the score for each input is determined by the largest output over ten runs on my CPU.

Also, as you don't know how precious computer data will be in the future, **the byte-count of your generator code must be less than 512 bytes.**

~~**Lowest score in two weeks (on Sep 30) will be declared the winner.**~~ Congratulations to your winner, **@ThomasKwa**!

---

## Leaderboard

```
var QUESTION_ID=58084,OVERRIDE_USER=42545;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[3],language:a[1]+'/'+a[2],lang2:a[2],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size.toFixed(3)).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.lang2,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){var E=e.lang.toLowerCase(),S=s.lang.toLowerCase();return E>S?1:E<S?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size.toFixed(3)).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,])\/([^\n,]*[^\s,]),.*?([\.\d]+)(?=[^\n\.\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\.\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Languages</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Output Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

To make sure your answer shows up correctly, please start it with this header:

```
# Language name/Other language name, X points

```

Where `X` is the score of your answer. Example:

```
# CJam/Pyth, 25.38 points

```

If you have any questions or suggestions, please let me know. Good luck!

# Answer
> 10 votes
# Python/Zilog Z80 machine code, ~~11.653~~ 11.488

```
import math,numpy as np
def R(n):
    if n==0:return []
    if n<0:return -R(-n)
    e=int(math.log(n,2))
    if n >= 5/3 * 2**e:
        return np.append(2**(e+1),-R(2**(e+1)-n))
    return np.append(2**e,R(n-2**e))

def strR(n):
    b = R(n)
    s = ""
    if n==0:return s
    e=max(abs(b))
    while e:
        if e in b:s+="#"
        elif -e in b:s+="+"
        s+=")"
        e//=2
    return s[:-1]

```

Bonuses: Negative numbers.

Assumes that the `hl` register pair initially holds 0, and returns the result in `hl`.

Only these three instructions are used:

```
ASCII   Hex    Instruction
--------------------------
#       23     inc hl
)       29     add hl,hl
+       2B     dec hl

```

We use a small modification of the minimum-weight balanced binary representation BBR2. Since BBR2 minimizes the weight (number of nonzero digits), but we want to minimize the weight plus the number of bit shifts, we change a constant in the algorithm from `3/2` to `5/3`.

To compute the score and verify, use this code:

```
def verify(n):
v = 0
for c in strR(n):
    if c=="#":v += 1
    elif c=="+":v -= 1
    else: v *= 2
return v==n

print(0.5*(sum([len(strR(n)) for n in range(1,1001)])/1000 + \
           sum([len(strR(n)) for n in range(-1000,1)])/1001 * 0.9))

print(all([verify(n) for n in range(-1000,1001)]))

```

Example output:

```
strR(486)
         '#)))))+)+))+)'

```

Or in assembly:

```
inc hl \ add hl,hl \ add hl,hl \ add hl,hl \ add hl,hl \ add hl,hl \ dec hl \ add hl,hl \ dec hl \ add hl,hl \ add hl,hl \ dec hl \ add hl,hl

```

More example programs:

```
-256  +))))))))
-255  +))))))))#
-254  +)))))))#)
-253  +)))))))#)#
-252  +))))))#))
-251  +))))))#))#
-250  +))))))#)#)
-249  +)))))#)))+
-248  +)))))#)))
-247  +)))))#)))#
-246  +)))))#))#)
-245  +)))))#))#)#
-244  +)))))#)#))
-243  +)))))#)#))#
-242  +))))#)))+)
-241  +))))#))))+

  -5  +))+
  -4  +))
  -3  +)+
  -2  +)
  -1  +
   0
   1  #
   2  #)
   3  #)#
   4  #))
   5  #))#

```

Possible optimizations: OP rules that the `inc h` and `dec h` instructions, which directly change the upper byte of `hl`, are illegal, but `sla h` and the undocumented `sl1 h` (left bit shifts by 1 on `h` that shift in a `0` and `1` respectively) are permitted. `sla h` and `sl1 h` are two bytes each, but they can sometimes shorten the output.

# Answer
> 9 votes
# CJam/CJam, ~~143.263~~ ~~42.713~~ ~~28.899~~ ~~23.901~~ ~~21.903~~ 20.468

```
ri
[
    ['X\2b1>e`{~{"1)*)"*}{_({(')*1\"m<"}{"1)*"*}?}?}/]s
    "X1)*"/"1)"*
    "1)1)*"/"1)))"*
    "X1)m<"/"1)))"*
    _"1)"/("1):Y"+\'Y*+
]
{,}$0=

```

No bonuses apply.

Try it online: sample run | score calculator | verification

### Example runs

```
   1 X
   2 1)
   3 1))
   4 1)))
   5 1))))
   6 1))1)*
   7 1))1)*)
   8 X1))m<
   9 1)))1)*)
  10 1))))1)*
  11 1))))1)*)
  12 1))1)m<
  13 1))1)*1)*)
  14 1))1)*)1)*
  15 1))1)*)1)*)
  16 X1)))m<
  17 X1))m<1)*)
  18 1)))1)*)1)*
  19 1)))1)*)1)*)
  20 1))))1)m<

```

```
 981 1):Y)Y*)Y*)Y*Y*)Y*Y*)Y*Y*)
 982 1):Y)Y*)Y*)Y*Y*)Y*Y*)Y*)Y*
 983 1):Y)Y*)Y*)Y*Y*)Y*Y*)Y*)Y*)
 984 1):Y)Y*)Y*)Y*Y*)Y*)Y)m<
 985 1):Y)Y*)Y*)Y*Y*)Y*)Ym<Y*)
 986 1):Y)Y*)Y*)Y*Y*)Y*)Y*Y*)Y*
 987 1):Y)Y*)Y*)Y*Y*)Y*)Y*Y*)Y*)
 988 1):Y)Y*)Y*)Y*Y*)Y*)Y*)Ym<
 989 1):Y)Y*)Y*)Y*Y*)Y*)Y*)Y*Y*)
 990 1):Y)Y*)Y*)Y*Y*)Y*)Y*)Y*)Y*
 991 1):Y)Y*)Y*)Y*Y*)Y*)Y*)Y*)Y*)
 992 1):Y)Y*)Y*)Y*)Y)))m<
 993 1):Y)Y*)Y*)Y*)Y))m<Y*)
 994 1):Y)Y*)Y*)Y*)Y)m<Y*)Y*
 995 1):Y)Y*)Y*)Y*)Y)m<Y*)Y*)
 996 1):Y)Y*)Y*)Y*)Ym<Y*)Ym<
 997 1):Y)Y*)Y*)Y*)Ym<Y*)Y*Y*)
 998 1):Y)Y*)Y*)Y*)Ym<Y*)Y*)Y*
 999 1):Y)Y*)Y*)Y*)Ym<Y*)Y*)Y*)
1000 1):Y)Y*)Y*)Y*)Y*Y*)Y)m<

```

# Answer
> 3 votes
## Ceylon/Ceylon, ~~49.86~~ 40.95 points

The third version uses Ceylon 1.2 for the generator and 509 bytes of code:

`import ceylon.language{S=String,I=Integer,e=expand}S q(I n)=>n==0then"0"else(n<0then"-"+p(-n,"-")else p(n,"+"));variable Map<[I,S],S>c=map{};S p(I n,S s){S v=c[[n,s]]else(n<8then s.join([1].repeat(n)))else(let(a="+-".replace(s,""))e(e{for(x in 2..8)let(l=(n^(1.0/x)).integer){for(r in l:2)if(r>1)let(w=r^x){if(w-n<n)"("+p(r,"+")+")^("+p(x,"+")+")"+(w<n then s+p(n-w,s)else(n<w then a+p(w-n,a)else""))}}}).reduce<S>((x,y)=>x.size<y.size then x else y))else"";c=[n,s]in c then c else map{[n,s]->v,*c};return v;}`

It gets down to 35.22 points, but I won't put this in the title line because Celyon 1.2 only was published at october 29. I don't think I would be able to implement this algorithm in Ceylon 1.1 in this size.). More details down there, here I'll describe the second version. (The first version can be seen in the history – it supported only positive numbers, but did fit into 256 bytes.)

### Second version

Now the second version, which supports negative integers (and 0), and generally creates a bit shorter output by using in addition `-`. (This version actually uses the permitted length, the first one tried to stay under 256 bytes instead of 512.)

```
String proof(Integer n) {
    if (n == 0) { return "0"; }
    if (n < 0) { return "-" + p(-n, "-"); }
    return p(n, "+");
}
String p(Integer n, String sign) {
    if (n < 9) {
        return sign.join([1].repeat(n));
    }
    value anti = (sign == "+") then "-" else "+";
    value root = ((n^0.5) + 0.5).integer;
    return "(" + p(root, "+") + ")^(1+1)" +
       ( (root^2 < n) then sign + p(n - root^2, sign) else
         ((n < root^2) then anti + p(root^2 - n, anti) else ""));
}

```

Code has length 487, so there is still some space for more optimizations later. (There are also lots of reserves in form of whitespace and long variable names.)

The scoring:

```
Total positive: 42652
Average positive:42.652
Total negative: 43653
Average negative: 43.60939060939061
With bonus:39.24845154845155
Overall score: 40.95022577422577

```

Some sample outputs:

```
   27:  21: (1+1+1+1+1)^(1+1)+1+1
   28:  23: (1+1+1+1+1)^(1+1)+1+1+1
   29:  25: (1+1+1+1+1)^(1+1)+1+1+1+1
   30:  27: (1+1+1+1+1)^(1+1)+1+1+1+1+1
   31:  29: (1+1+1+1+1+1)^(1+1)-1-1-1-1-1
   32:  27: (1+1+1+1+1+1)^(1+1)-1-1-1-1
   33:  25: (1+1+1+1+1+1)^(1+1)-1-1-1
   34:  23: (1+1+1+1+1+1)^(1+1)-1-1

  -27:  22: -(1+1+1+1+1)^(1+1)-1-1
  -28:  24: -(1+1+1+1+1)^(1+1)-1-1-1
  -29:  26: -(1+1+1+1+1)^(1+1)-1-1-1-1
  -30:  28: -(1+1+1+1+1)^(1+1)-1-1-1-1-1
  -31:  30: -(1+1+1+1+1+1)^(1+1)+1+1+1+1+1
  -32:  28: -(1+1+1+1+1+1)^(1+1)+1+1+1+1
  -33:  26: -(1+1+1+1+1+1)^(1+1)+1+1+1
  -34:  24: -(1+1+1+1+1+1)^(1+1)+1+1

  993:  65: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1+1)^(1+1)+1+1+1+1+1
  994:  63: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)-1-1-1-1-1
  995:  61: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)-1-1-1-1
  996:  59: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)-1-1-1
  997:  57: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)-1-1
  998:  55: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)-1
  999:  53: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)
 1000:  55: ((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)-(1+1+1+1+1)^(1+1)+1

 -993:  66: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1+1)^(1+1)-1-1-1-1-1
 -994:  64: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)+1+1+1+1+1
 -995:  62: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)+1+1+1+1
 -996:  60: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)+1+1+1
 -997:  58: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)+1+1
 -998:  56: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)+1
 -999:  54: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)
-1000:  56: -((1+1+1+1+1+1)^(1+1)-1-1-1-1)^(1+1)+(1+1+1+1+1)^(1+1)-1

    1:   1: 1
    2:   3: 1+1
    3:   5: 1+1+1
    4:   7: 1+1+1+1
    5:   9: 1+1+1+1+1
    6:  11: 1+1+1+1+1+1
    7:  13: 1+1+1+1+1+1+1
    8:  15: 1+1+1+1+1+1+1+1
    9:  13: (1+1+1)^(1+1)
   10:  15: (1+1+1)^(1+1)+1

    0:   1: 0
   -1:   2: -1
   -2:   4: -1-1
   -3:   6: -1-1-1
   -4:   8: -1-1-1-1
   -5:  10: -1-1-1-1-1
   -6:  12: -1-1-1-1-1-1
   -7:  14: -1-1-1-1-1-1-1
   -8:  16: -1-1-1-1-1-1-1-1
   -9:  14: -(1+1+1)^(1+1)
  -10:  16: -(1+1+1)^(1+1)-1

```

As you can see, the negative ones are always one byte (the leading `-`) longer than the corresponding positive ones.

The base idea is the same as the previous program: find a square near our target number, and represent its root and the remainder recursively. But now we allow our square being also some larger than the target number, which then makes the remainder negative. (The `+0.5` can be changed to a different constant to tweak the algorithm, but it seems that I already did hit the optimum here – both 0.4 and 0.6 give worse results.)

To make negative values negative (and otherwise have the same structure as the positive ones, we pass the operator `sign` to our recursive function `p` – that is either `"+"` or `"-"`. We can use that for the joiner in the trivial cases (i.e. n \< 9) as well as for the remainder if it's positive, and use the opposite sign for the remainder if it is negative.

The `proof` function handles the initial sign (with a special case for 0), the `p` function does the actual work, with recursion.

### Third version, for Ceylon 1.2

```
import ceylon.language { S=String, I=Integer,e=expand }

// output a base-proof Ceylon expression for an integer
// (i.e. using only 0 and 1 as digits).
//
// Question: http://codegolf.stackexchange.com/q/58084/2338
// My Answer:  http://codegolf.stackexchange.com/a/58122/2338
//
// The goal is to produce an expression as short as possible, with
// the code staying under 512 bytes in length.
//
// This approach is to represent a positive integer as a square
// of a positive integer plus some remainder (where the remainder
// can be negative), and for negative integers replace the + on the
// outer level by -.

S q(I n) =>
        n == 0 then "0"
        else (n < 0 then "-" + p(-n, "-")
            else p(n, "+"));

// cache for values of p
variable Map<[I, S],S> c = map { };

// Transforms a positive number into a base-proof term, using
// the given sign for the summation on the outer level.
S p(I n, S s) {
    S v =
    // look into the cache
            c[[n, s]] else (
        // hard-code small numbers
        n < 8 then s.join([1].repeat(n)))
            else
    // do the complicated stuff
    (let (a = "+-".replace(s,""))
            e(e {
                    for (x in 2..8) // try these exponents
                        let (l = (n ^ (1.0 / x)).integer) // \[ sqrt[exp]{n} \] in LaTeX
                            { for (r in l:2) // lowerRoot, lowerRoot + 1
                                    if (r > 1)
                                        let (w = r ^ x)
                                            { if (w-n < n) // avoid recursion to larger or same number
                                                    // format the string as  r^x + (n-w)
                                                    "(" + p(r, "+") + ")^(" + p(x, "+") + ")" +
                                                            (w < n then s + p(n - w, s)
                                                                else (n < w then a + p(w - n, a)
                                                                    else ""))
                                            } } })
            // and now find the shortest formatted string
                .reduce<S>((x, y) => x.size < y.size then x else y))
    // this should never happen, but we can't tell the compiler
    // that at least some of the iterables are non-empty due to the if clause.
            else "";

    // this builds a new cache in each step – quite wasteful,
    // as this also happens when the value was found in the cache,
    // but we don't have more characters remaining.
    //// c = map { [n, s] -> v, *c };
    ///better way:
     c = [n,s] in c then c else map{[n,s]->v, *c};
    return v;
}

```

The golfed version (i.e. comments and whitespace removed) is posted at the top, at exactly 509 bytes of code.

This uses the same base principle as the second version, but instead of just squares, it also tries to use higher powers of numbers (trying exponents from 2 to 8), and uses the shortest result. It also caches the results, as otherwise this would be unacceptably slow for larger numbers with many recursive calls.

Scoring:

```
Total positive: 36622
Average positive: 36.622
Total negative: 37623
Average negative: 37.58541458541458
With bonus:33.826873126873124
Overall score: 35.22443656343656

```

The big indented construct in the middle are three nested iterable comprehensions, the inner two inside a let expression. These are then unnested using the expand function twice, and the `reduce` function finds the shortest of those strings.

I've filed a feature request to be able to do this in a single comprehension.

Inside the comprehension, we are building a string from the root `r`, the exponent `x` and the remainder (`n-w` or `w-n`).

The `let` expression and the `map` function are new in Ceylon 1.2. `map` could have been replaced by `HashMap` (which would have needed more characters for the import, although it would probably be even faster, as I wouldn't build the map new for each new entry). The `let` expressions like `let (w = r ^ x)` could have been replaced by using an `if` clause like `if(exists w = true then r ^ x)` (and then I wouldn't have needed the two `expand` calls either), but this would still be a bit longer, not fitting inside the 511 allowed bytes.

Here the sample outputs corresponding to those selected above, all of them except the really small numbers are shorter:

```
   27:  15: (1+1+1)^(1+1+1)
   28:  17: (1+1+1)^(1+1+1)+1
   29:  19: (1+1+1)^(1+1+1)+1+1
   30:  21: (1+1)^(1+1+1+1+1)-1-1
   31:  19: (1+1)^(1+1+1+1+1)-1
   32:  17: (1+1)^(1+1+1+1+1)
   33:  19: (1+1)^(1+1+1+1+1)+1
   34:  21: (1+1)^(1+1+1+1+1)+1+1

  -27:  16: -(1+1+1)^(1+1+1)
  -28:  18: -(1+1+1)^(1+1+1)-1
  -29:  20: -(1+1+1)^(1+1+1)-1-1
  -30:  22: -(1+1)^(1+1+1+1+1)+1+1
  -31:  20: -(1+1)^(1+1+1+1+1)+1
  -32:  18: -(1+1)^(1+1+1+1+1)
  -33:  20: -(1+1)^(1+1+1+1+1)-1
  -34:  22: -(1+1)^(1+1+1+1+1)-1-1

  993:  39: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1-1-1-1-1-1
  994:  37: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1-1-1-1-1
  995:  35: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1-1-1-1
  996:  33: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1-1-1
  997:  31: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1-1
  998:  29: ((1+1+1)^(1+1)+1)^(1+1+1)-1-1
  999:  27: ((1+1+1)^(1+1)+1)^(1+1+1)-1
 1000:  25: ((1+1+1)^(1+1)+1)^(1+1+1)

 -993:  40: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1+1+1+1+1+1
 -994:  38: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1+1+1+1+1
 -995:  36: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1+1+1+1
 -996:  34: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1+1+1
 -997:  32: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1+1
 -998:  30: -((1+1+1)^(1+1)+1)^(1+1+1)+1+1
 -999:  28: -((1+1+1)^(1+1)+1)^(1+1+1)+1
-1000:  26: -((1+1+1)^(1+1)+1)^(1+1+1)

    1:   1: 1
    2:   3: 1+1
    3:   5: 1+1+1
    4:   7: 1+1+1+1
    5:   9: 1+1+1+1+1
    6:  11: 1+1+1+1+1+1
    7:  13: 1+1+1+1+1+1+1
    8:  13: (1+1)^(1+1+1)
    9:  13: (1+1+1)^(1+1)
   10:  15: (1+1+1)^(1+1)+1

    0:   1: 0
   -1:   2: -1
   -2:   4: -1-1
   -3:   6: -1-1-1
   -4:   8: -1-1-1-1
   -5:  10: -1-1-1-1-1
   -6:  12: -1-1-1-1-1-1
   -7:  14: -1-1-1-1-1-1-1
   -8:  14: -(1+1)^(1+1+1)
   -9:  14: -(1+1+1)^(1+1)
  -10:  16: -(1+1+1)^(1+1)-1

```

For example, now we have 1000 = (3^2 + 1)^3, instead of 1000 = (6^2-4)^2-5^2+1.

# Answer
> 3 votes
# /BrainFuck, 34.201 points

### source (194B):

```
E='++[------>+<]>++'°\c[1]<0°{E&='.'µA=ß"-ß°°c[1]),'')µE&='+++'°/B=1°(A[0]°\A[B]='.'°{µE&='--.++'°]E&=ß~A'+',A[B])&'.'&ß~A'-',A[B])°}°)°'ß"&E,'+-')+ß"&E,'-+')>0µE=ß"'ß"'E,'-+',''),'+-','')°!€E)

```

If someone is interested, I'll add an explanation. The BF output is pretty optimized already, but I guess I could use the remaining 318B of ß code to implement

* a loop-nesting-optimization,
* more 8bit overflow shortcuts,
* ~~operator collision removal~~.

### Samples:

Running in windows:

```
$ sharps encode.ss 42
++[------>+<]>+++++++++.--.--

$ sharps encode.ss -42
++[------>+<]>++.+++++++.--.--

$ sharps encode.ss 1.427
++[------>+<]>++++++.---.++++++.--.+++++.-------

$ sharps encode.ss -946.427
++[------>+<]>++.++++++++++++.-----.++.--------.++++++.--.+++++.-------

```

Running in linux:

```
$ WINEDEBUG=-all wine sharps source.ss -4.72
++[------>+<]>++.+++++++.------.+++++++++.-----.--

```

Validate in the online BF interpreter.

### Scores:

1. Base average `= 37.495`.
2. Decimal average `= 60.959 * 0.5 = ~30.48`.
3. Negative avg. `= 38.4765234765235 * 0.9 = ~34.629`
4. Avg of the above, final score `= (37.495 + 30.48 + 34.629)/3 = 34.201`.

# Answer
> 3 votes
# Ruby/Ruby, 29.77885

31.873\*0.9 (negative) 30.872 (positive).

Basic strategy is symmetrical base 3 representation ("balanced ternary"), ie when the digits are `-1,0,1` instead of `0,1,2`

```
#function
f=->n{m=n
  a='0'
  7.times{|i|
    r=m%3;r-=r/2*3
    m=(m-r)/3
    #produce expression: replace 0 with (0*x+-1)
    #only add 0*x if there are higher base 3 digits to follow.
    #only add (..+-1) if the current base 3 digit is nonzero.
    a.sub!('0',['','(','('][r]+(m.abs>0?'0*x':'')+['','+1)','-1)'][r])
  }
  #tidy up expression
  a.sub!('(-1)*','-')          #remove internal (-1)*
  a.sub!('(+1)*','')           #remove internal (+1)*
  a[-1]==')' && a=a[1..-2]     #remove unnecessary global brackets
  a.sub!('x','(x=1+1+1)')      #find the first x and define it as 1+1+1=3
  #special cases for small numbers
  n.abs<8 && a=n==0?'0':['','1'+'+1'*(n-1).abs,'-1'*n.abs][n<=>0]
  a
}

#call like this
(1..1000).each{|p|
b=f.call(p)
puts b

```

Here's the output from 0 to 40 before cleanup

```
(+1)
((+1)*x-1)
(+1)*x
((+1)*x+1)
(((+1)*x-1)*x-1)
((+1)*x-1)*x
(((+1)*x-1)*x+1)
((+1)*x*x-1)
(+1)*x*x
((+1)*x*x+1)
(((+1)*x+1)*x-1)
((+1)*x+1)*x
(((+1)*x+1)*x+1)
((((+1)*x-1)*x-1)*x-1)
(((+1)*x-1)*x-1)*x
((((+1)*x-1)*x-1)*x+1)
(((+1)*x-1)*x*x-1)
((+1)*x-1)*x*x
(((+1)*x-1)*x*x+1)
((((+1)*x-1)*x+1)*x-1)
(((+1)*x-1)*x+1)*x
((((+1)*x-1)*x+1)*x+1)
(((+1)*x*x-1)*x-1)
((+1)*x*x-1)*x
(((+1)*x*x-1)*x+1)
((+1)*x*x*x-1)
(+1)*x*x*x
((+1)*x*x*x+1)
(((+1)*x*x+1)*x-1)
((+1)*x*x+1)*x
(((+1)*x*x+1)*x+1)
((((+1)*x+1)*x-1)*x-1)
(((+1)*x+1)*x-1)*x
((((+1)*x+1)*x-1)*x+1)
(((+1)*x+1)*x*x-1)
((+1)*x+1)*x*x
(((+1)*x+1)*x*x+1)
((((+1)*x+1)*x+1)*x-1)
(((+1)*x+1)*x+1)*x
((((+1)*x+1)*x+1)*x+1)

```

And after cleanup

```
0
1
1+1
1+1+1
1+1+1+1
1+1+1+1+1
1+1+1+1+1+1
1+1+1+1+1+1+1
(x=1+1+1)*x-1
(x=1+1+1)*x
(x=1+1+1)*x+1
((x=1+1+1)+1)*x-1
((x=1+1+1)+1)*x
((x=1+1+1)+1)*x+1
(((x=1+1+1)-1)*x-1)*x-1
(((x=1+1+1)-1)*x-1)*x
(((x=1+1+1)-1)*x-1)*x+1
((x=1+1+1)-1)*x*x-1
((x=1+1+1)-1)*x*x
((x=1+1+1)-1)*x*x+1
(((x=1+1+1)-1)*x+1)*x-1
(((x=1+1+1)-1)*x+1)*x
(((x=1+1+1)-1)*x+1)*x+1
((x=1+1+1)*x-1)*x-1
((x=1+1+1)*x-1)*x
((x=1+1+1)*x-1)*x+1
(x=1+1+1)*x*x-1
(x=1+1+1)*x*x
(x=1+1+1)*x*x+1
((x=1+1+1)*x+1)*x-1
((x=1+1+1)*x+1)*x
((x=1+1+1)*x+1)*x+1
(((x=1+1+1)+1)*x-1)*x-1
(((x=1+1+1)+1)*x-1)*x
(((x=1+1+1)+1)*x-1)*x+1
((x=1+1+1)+1)*x*x-1
((x=1+1+1)+1)*x*x
((x=1+1+1)+1)*x*x+1
(((x=1+1+1)+1)*x+1)*x-1
(((x=1+1+1)+1)*x+1)*x
(((x=1+1+1)+1)*x+1)*x+1

```

# Answer
> 2 votes
# Ruby/dc, ~~20.296~~ ~~18.414~~ 16.968

Dynamic programming! Defines a list of functions that, given a dc instruction, return a new expression and the numeric value of that expression. Then, starting with `1` prefined, it builds a list of all reachable values up to and including the wanted value.

### edit:

Added a function for *n-1* and made it run the algorithm through multiple passes. It seems to need 7 passes to stabilize. Had to shorten some variable names to stay within 512 bytes.

### edit 2:

Added functions for *n(n-1)*, *n(n+1)* and *n^3* while I was at it. Shortened the code some more, landing at exactly 512 bytes.

```
N = gets.to_i

fns = [
  ->(n,s){[n-1,   s+'1-']},
  ->(n,s){[n+1,   s+'1+']},
  ->(n,s){[n*2,   s+'d+']},
  ->(n,s){[n*3,   s+'dd++']},
  ->(n,s){[n*~-n, s+'d1-*']},
  ->(n,s){[n*n,   s+'d*']},
  ->(n,s){[n*-~n, s+'d1+*']},
  ->(n,s){[n*n*n, s+'dd**']},
]

lst = []*(N+1)
lst[0..2] = %w[0 1 1d+]

loop do
  prev = lst.dup

  (1..N).each do |n|
    fns.each do |f|
      m,s = f[n, lst[n]]
      lst[m] = s if m <= N && (lst[m].nil? || lst[m].size > s.size)
    end
  end

  break if lst == prev
end

puts lst[N]

```

### Generated numbers:

Output consists entirely of five different characters: `1` pushes the value 1 on the stack; `d` duplicates the top of the stack; `+`, `-`, and `*` pops the two top values and pushes their sum, difference, and product, respectively. Each generated expression adds only one value to the stack after execution.

```
   1: 1
   2: 1d+
   3: 1dd++
   4: 1d+d+
   5: 1d+d+1+
   6: 1d+dd++
   7: 1d+dd++1+
   8: 1d+dd**
   9: 1dd++d*
  10: 1d+d+1+d+
  11: 1d+d+1+d+1+
  12: 1dd++d1+*
  13: 1dd++d1+*1+
  14: 1d+dd++1+d+
  15: 1d+d+d*1-
  16: 1d+d+d*
  17: 1d+d+d*1+
  18: 1dd++d*d+
  19: 1dd++d*d+1+
  20: 1d+d+d1+*
  21: 1d+d+d1+*1+
  22: 1d+d+1+d+1+d+
  23: 1d+dd**dd++1-
  24: 1d+dd**dd++
  25: 1d+d+1+d*

```

...

```
 989: 1d+d+d*d+d1-*1-1-1-
 990: 1d+d+d*d+d1-*1-1-
 991: 1d+d+d*d+d1-*1-
 992: 1d+d+d*d+d1-*
 993: 1d+d+d*d+d1-*1+
 994: 1d+d+d*d+d1-*1+1+
 995: 1d+d+d*d+d1-*1+1+1+
 996: 1d+d+1+dd**d+1-d+d+
 997: 1d+d+1+d+dd**1-1-1-
 998: 1d+d+1+d+dd**1-1-
 999: 1d+d+1+d+dd**1-
1000: 1d+d+1+d+dd**

```

# Answer
> 0 votes
# Python 2.6, ~~78.069~~ \- 66.265 points

Submitting my answer for what it's worth (not a lot in this case ... but clearly demonstrating that for this challenge it's not enough to simply think of composing the output as a sum of bit-shifted values; when taken into account that no digits outside of 0 or 1 may appear in the output). I might come back later with a different way of generating output.

The code itself is not too long (176 characters):

```
def f(a):return'+'.join(('(1<<%s)'%['0','+'.join('1'*x)][x>0]).replace('(1<<0)','1')for x in[i for i,e in enumerate(bin(a)[::-1][:-2])if int(e)])
print"".join(f(int(input())))

```

It generates correct but verbose output:

```
17
1+(1<<1+1+1+1)

800
(1<<1+1+1+1+1)+(1<<1+1+1+1+1+1+1+1)+(1<<1+1+1+1+1+1+1+1+1)

```

Snippet that calculates the score:

```
def f(a):return'+'.join(('(1<<%s)'%['0','+'.join('1'*x)][x>0]).replace('(1<<0)','1')for x in[i for i,e in enumerate(bin(a)[::-1][:-2])if int(e)])
print sum(len("".join(f(i)))for i in range(1000))

```

---
Tags: number, arithmetic, metagolf
---


# Question
Title: Generate a Brainf_ck program that outputs a string of given length
Your friend is trying to break into a vault that has a peculiar locking system: it requires a certain number of gentle knocks in a particular spot. Your friend discovered the number (which is in the range 1...99999) and possesses a gadget that produces the required knocks. However, the gadget is a Brainfuck interpreter! So your friend needs to feed it a Brainfuck program, which, obviously, should be as short as possible (the gadget's I/O is slow).

Your task is to help him! Write a program or a subroutine, in any language, that accepts as input a number `N`, and outputs a Brainfuck program, which takes no input and outputs a string of printable ASCII characters (excluding the space character - codes in the range 33...126) of length `N`.

Example: for input `10`, the output might be

```
+++++++++++++++++++++++++++++++++..........

```

(but I am sure it can be shortened!)

Your score will be the sum of lengths of your outputs for the following values of `N` (they are random numbers):

```
55
68
15
28
841
838
522
846
4898
9004
9363
3810
13230
67175
37231
44701

```

Oh, and you will be transmitting your code (the generator program) to your friend by Twitter. So make sure it's 140 characters or less!

---

P.S. The Brainfuck language has many variants. Let's assume the tape is infinite in both directions (or "circular and large enough"), and the cells have 32-bit int capacity (finite and able to hold numbers up to 99999). Also, no wrapping: when a cell overflows, the machine self-destructs!

# Answer
> 3 votes
## Python 2, score: 1021

I've just realized that this contest is pretty old but still, since I came up with a better solution than those posted, I posted it as well.

Here's a 102 byte python script that does the job:

```
n=input()
s='>'
while n:
    s+='>'+'+'*(n%5+1);n/=5
print s+'[->[-<+++++>]<<]<+++++++[>+++++<-]>>[-<.>]'

```

The idea is to use base 5 encoding for N (best base at least for the current inputs, which do not seem very "random" by the way, looks like they were arbitrarily chosen by OP), and to write a generic Brainfuck algorithm to decode a number of arbitrary length (the number is encoded with each digit increased by one in order to detect the end of conversion). I chose to print character 35 `#`, character 36 `$` is equivalent.

You may run the following bash script to get the score:

```
i=0
while read p; do
  i=$((i+`echo $p | python convert.py | wc -m`))
done
echo $i

```

With a more advanced program that replaces encoding with multiplication for small numbers and chooses the best base for encoding each number, I can reach 958 Brainfuck characters, but Python is far too verbose (and I'm a pretty bad/lazy golfer) in order to get the converter into 144 bytes!

# Answer
> 8 votes
## BrainF\***, score: 193,313

It's not under 140 characters (it's 147, so close!!), so this can't win, but I thought it was cool.

Prints 43 plus signs, then `N` periods. Not very optimal.

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

```

If anyone can help shorten this I would love it.

# Answer
> 5 votes
# J, Total score = 1481

*(For my previous entry and explanation check revision history.)*

```
f10=.('>++++++++++<';'')rplc~;@([:(<@('+++++[>+++++++<-]>>+',;@((<'[>++++++++++')#~#)),[<@(']',~'<-','<.>'#~],[,])"0 #-i.@# )10#.inv])

```

This function generates nested BF loops based on the base10 digits of the input number. Checking all reasonable bases and choosing the smallest BF code would improve the score with a small amount.

BF programs for the test set:

```
   f10 every 55 68 15 28 841 838 522 846 4898 9004 9363 3810 13230 67175 37231 44701
+++++[>+++++++<-]>>+[>++++++++++[-<<.....>>]<-<.....>]
+++++[>+++++++<-]>>+[>++++++++++[-<<......>>]<-<........>]
+++++[>+++++++<-]>>+[>++++++++++[-<<.>>]<-<.....>]
+++++[>+++++++<-]>>+[>++++++++++[-<<..>>]<-<........>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[-<<<........>>>]<-<<....>>]<-<.>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[-<<<........>>>]<-<<...>>]<-<........>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[-<<<.....>>>]<-<<..>>]<-<..>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[-<<<........>>>]<-<<....>>]<-<......>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[-<<<<....>>>>]<-<<<........>>>]<-<<.........>>]<-<........>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[-<<<<.........>>>>]<-<<<>>>]<-<<>>]<-<....>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[-<<<<.........>>>>]<-<<<...>>>]<-<<......>>]<-<...>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[-<<<<...>>>>]<-<<<........>>>]<-<<.>>]<-<>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[>++++++++++[-<<<<<.>>>>>]<-<<<<...>>>>]<-<<<..>>>]<-<<...>>]<-<>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[>++++++++++[-<<<<<......>>>>>]<-<<<<.......>>>>]<-<<<.>>>]<-<<.......>>]<-<.....>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[>++++++++++[-<<<<<...>>>>>]<-<<<<.......>>>>]<-<<<..>>>]<-<<...>>]<-<.>]
+++++[>+++++++<-]>>+[>++++++++++[>++++++++++[>++++++++++[>++++++++++[-<<<<<....>>>>>]<-<<<<....>>>>]<-<<<.......>>>]<-<<>>]<-<.>]

```

Computing score on the test set:

```
   +/#@> f10 each 55 68 15 28 841 838 522 846 4898 9004 9363 3810 13230 67175 37231 44701
1481

```

# Answer
> 3 votes
# Pyth, 1702

Reconstruct numbers using factors of N + x.

```
+holN+]++">>"*"+"Q"<<"mjk(">>"j">"m*"+"kP+Qd"<[[->[->+>+<<]>>[-<<+>>]<<<]>[-]>[-<<+>>]<<<]>"*"-"d"<<")50"++++++[>++++++<-]>>[<.>-]"

```

# Answer
> 3 votes
# CJam, 52 74 108 bytes, total = 1304 1244 1210

```
ri5b_,1>{(_3<{\(@5*+}*\+}*W%)\{T+_2>:T5*-_0>"-+"=\z*}%\T+'+*a+W%{"[->+++++<]>"\}*">x[>x<-]<[->>.<<]"'x/'+6**

```

A test script (slow in the online interpreter):

```
q~]
{
_[0:T;
5b_,1>{(_3<{\(@5*+}*\+}*W%)\{T+_2>:T5*-_0>"-+"=\z*}%\T+'+*a+W%{"[->+++++<]>"\}*">x[>x<-]<[->>.<<]"'x/'+6**
]s
_[L:RL@0\
"-+><.]"['('){+\_{)}0?@\}{@\+\_{)}0?}{R1$c+:R;}]:`"]a"{{_aa+1$4G#%{:~~1}{;0}?}g}`+a+er:~:~
];R,@=!"Error."N+*o
}%s,

```

# Answer
> 2 votes
# Befunge-98, N + 41, total = 193281

```
&>'+\:v
v^-1,\_
' >1-:v
>v^,+'_
,'    :
>ff3++^
>2f*+v
^>/9+:,
>'>,61v
, v*6+<
^/2,:<@
v >+2+,
>'<,']^

```

I know it's bad, but I felt like writing some Befunge today. The best part of Befunge is that the programs are even less understandible than the actual golf languages, especially when they reuse code :D

Uses a similar algorithm to Martin Büttner's CJam answer:

```
(N +'s)>+++++++++++++++++++++++++++++++++<[->.<]

```

# Answer
> 1 votes
# CJam, 40 + N, Total: 193265

```
'+33*'>'+l~*"[<.>-]"

```

Just to get this started, here is the baseline solution. It generates the following code:

```
+++++++++++++++++++++++++++++++++>_[<.>-]

```

where `_` is `N` copies of `+`.

Run the generator here.

# Answer
> 1 votes
## Befunge-93 - 24 + N, total = 193009

```
&>">>]-<]-<++++>[++++>[+++"v
v  ,,,,,,,,,,,,,,,,,,,,,,, <
>:v
,v_@
"1
.-
"
^<

```

This uses a prefix of `+++[>++++[>++++<-]<-]>>` to set the first tape index to '0' with 24 characters. The Befunge program is very basic and outputs that along with N '.' characters.

---
Tags: kolmogorov-complexity, restricted-source, brainfuck, metagolf, code-generation
---