| Bytes | Lang | Time | Link |
|---|---|---|---|
| 053 | Janet | 250507T211648Z | xigoi |
| nan | Perl 5 | 180123T223427Z | Xcali |
| 049 | Juby | 250507T153220Z | Jordan |
| 004 | Thunno 2 | 230726T110613Z | The Thon |
| 005 | Vyxal r | 210728T032914Z | emanresu |
| 051 | R | 180207T195445Z | rturnbul |
| 008 | Pyt | 180206T184616Z | mudkip20 |
| 006 | Japt | 180123T172653Z | Shaggy |
| 016 | K4 | 180123T194842Z | mkst |
| 059 | AWK | 180123T161123Z | Robert B |
| 048 | PHP | 170126T182816Z | Titus |
| 050 | Haskell | 160526T011748Z | Michael |
| 087 | C# | 160601T180650Z | raive |
| 063 | Clojure | 160526T162832Z | mark |
| 015 | J | 160527T091625Z | Zgarb |
| 027 | Julia | 160525T041307Z | Dennis |
| 014 | Dyalog APL | 160525T232019Z | Adá |
| 072 | Swift | 160526T123741Z | John McD |
| 090 | Java | 160525T090241Z | Shaun Wi |
| 022 | J | 160526T033840Z | ljeabmre |
| 008 | Jelly | 160525T231104Z | Adá |
| 010 | Jolf | 160525T182430Z | Conor O& |
| 032 | Perl 6 | 160525T163405Z | Brad Gil |
| 011 | CJam | 160525T073222Z | Luis Men |
| 054 | Perl 5.10 | 160525T113509Z | Sake |
| 064 | PowerShell v2+ | 160525T125804Z | AdmBorkB |
| 008 | Pyke | 160525T125322Z | Blue |
| 026 | Vitsy | 160525T110301Z | Addison |
| 006 | Pyth | 160525T020051Z | Maltysen |
| 028 | Mathematica | 160525T103158Z | Martin E |
| 010 | Jelly | 160525T093328Z | jimmy230 |
| 007 | 05AB1E | 160525T083726Z | Emigna |
| 007 | Actually | 160525T053119Z | user4594 |
| 015 | J | 160525T035055Z | Leaky Nu |
| 032 | JavaScript ES7 | 160525T080250Z | Neil |
| 071 | Hoon | 160525T050841Z | RenderSe |
| 009 | MATL | 160525T045821Z | beaker |
| 009 | MATL | 160525T033555Z | Suever |
| 006 | Jelly | 160525T032711Z | Leaky Nu |
| 034 | Ruby | 160525T024107Z | Value In |
| 028 | Julia | 160525T032638Z | Sp3000 |
| 043 | Python 3 | 160525T031509Z | Sp3000 |
| 055 | JavaScript ES5 | 160525T030626Z | Downgoat |
| 029 | Octave | 160525T024053Z | beaker |
| 046 | Python 3 | 160525T022120Z | Keatinge |
| 023 | Minkolang 0.15 | 160525T025129Z | El'e |
Janet, 53 bytes
|(/(+;(seq[k :down[$ 0]](math/ceil(math/log2 k)))1)$)
\$\displaystyle a_n = \frac{1 + \sum_{k=1}^n \left\lceil \log_2 k \right\rceil}{n}\$
Perl 5, 39 + 1 (-p) = 40 bytes
map$b+=0|(log)/log 2,2..$_-1;$_=$b/$_+1
Perl 5, 44 43 + 2 (-pa) = 45 bytes
-1 thanks to @DomHastings
$\+=(length sprintf'%b',$_)/"@F"while$_--}{
Thunno 2, 4 bytes
Lḃḷm
Explanation
Lḃḷm # Implicit input
L # Push [0..input)
ḃ # Convert each to binary
ḷ # And get the length of each one
m # Take the average of the result
# Implicit output
Vyxal r, 5 bytes
ʁbfL/
ʁ # 0...a
b # Turn each into base 2
f # Flatten
L # Get the length
/ # Divide by the input
R, 51 bytes
Takes input from stdin. Uses the OEIS formula and then divides by n.
(2+ceiling(log2(n<-scan()))*n-2^ceiling(log2(n)))/n
Pyt, 8 bytes
⁻řļ⌊⁺Á1µ
Explanation:
Implicit input (N)
⁻ Decrement by 1 (N-1)
ř Push [1,2,...,N-1]
ļ element-wise log base 2 of [1,2,...,N-1]
⌊⁺ element-wise floor and increment
Á Push contents of array onto stack
1 Push 1
µ Get mean of stack
Implicit output
Japt, 6 bytes
o¤xÊ/U
Explanation
:Implicit input of integer U
o :Range [0,U)
¤ :Convert each to a base-2 string
Ê :Get length of each
x :Reduce by addition
/U :Divide by U
:Implicit output of result
K4, 16 bytes
Solution:
(1+#,/2\:'!x)%x:
Example:
(1+#,/2\:'!x)%x:5
1.8
(1+#,/2\:'!x)%x:6
2f
(1+#,/2\:'!x)%x:7
2.142857
Explanation:
Convert each number to binary, sum up the bits, add 1 for 0, divide by input.
(1+#,/2\:'!x)%x: / the solution
x: / store input as x
( )% / divide left by right
!x / range 0..x-1
2\:' / convert each (') to bits (2\:)
,/ / flatten result
# / count length of list
1+ / add one (as 0 contains 0 bits!)
Extra:
Precision is determined by the P system setting. Default is 7, max is 17
\P 7
(1+#,/2\:'!x)%x:7
2.142857
\P 12
(1+#,/2\:'!x)%x:7
2.14285714286
\P 17
(1+#,/2\:'!x)%x:7
2.1428571428571428
AWK, 59 bytes
{for(s=1;++n<$0;s+=int(log(n*2)/log(2)));printf"%.8g",s/$0}
Since AWK only does base-10 logs, I had to convert to base-2 and I chose to multiply the argument by 2 rather than add 1 to the result. It's the same byte-count, but I like it. :)
Haskell, 50 bytes
r x|x<1=0|1<2=1+r(x/2)
f n=(sum(r<$>[0..n-1])+1)/n
C#, 87 bytes
double f(int n){return Enumerable.Range(0,n).Average(i=>Convert.ToString(i,2).Length);}
I wrote a C# answer because I didn't see one. This is my first post to one of these, so please let me know if I'm doing anything wrong.
Clojure, 71 64 63 bytes
It looks like ratios are ok according to Which number formats are acceptable in output?
(fn[n](/(inc(apply +(map #(.bitLength(bigint %))(range n))))n))
- n=1 => 1
- n=7 => 15/7
ungolfed (and slightly rewritten for ease of explanation)
(fn [n]
(->
(->>
(range n) ;;Get numbers from 0 to N
(map #(.bitLength (bigint %))) ;;Cast numbers to BigInt so bitLength can be used
(apply +) ;;Sum the results of the mapping
(inc)) ;;Increment by 1 since bitLength of 0 is 0
(/ n))) ;;Divide the sum by N
old answer that used (float):
(fn[n](float(/(inc(apply +(map #(..(bigint %)bitLength)(range n))))n)))
output is like:
- n=1 => 1.0
- n=7 => 2.142857
J, 15 bytes
%~[:+/#@#:"0@i.
This is a monadic verb, used as follows:
f =: %~[:+/#@#:"0@i.
f 7
2.14286
Explanation
I implemented the challenge spec pretty literally. There are other approaches, but all turned out to be longer.
%~[:+/#@#:"0@i. Input is y
i. Range from 0 to y-1.
"0@ For each number in this range:
#@ Compute the length of
#: its base-2 representation.
[:+/ Take the sum of the lengths, and
%~ divide by y.
Julia, 27 bytes
n->endof(prod(bin,0:n-1))/n
How it works
Since * is string concatenation in Julia, prod can be used to concatenate an array of strings. It optionally takes a function as first argument that it maps over the second one before taking the actual "product", so prod(bin,0:n-1) is the string of the binary representation of all integers in the desired range. Taking the length with endof and dividing by n yields the mean.
Dyalog APL, 14 bytes
(+/1⌈(⌈2⍟⍳))÷⊢
range ← ⍳
log ← ⍟
log2 ← 2 log range
ceil ← ⌈
bits ← ceil log2
max ← ⌈
fix0 ← 1 max bits
sum ← +/
total ← sum fix0
self ← ⊢
div ← ÷
mean ← sum div self
Swift, 72 bytes
func f(n:Double)->Double{return n<1 ?1:f(n-1)+1+floor(log2(n))}
f(N-1)/N
Java, 135 95 90 bytes
float a(int n){int i=0,t=0;for(;i<n;)t+=Integer.toString(i++,2).length();return t/(n+0f);}
J, 22 bytes
[:(+/%#)[:([:##:)"0 i.
Usage:
bin =: [:(+/%#)[:([:##:)"0 i.
bin 7
2.14286
Jelly, 8 bytes
Not shorter, but interesting algorithm, and my first Jelly submission:
Rl2Ċ»1S÷
R 1 to n
l2 log2
Ċ ceiling
»1 max of 1 and...
S sum
÷ divided by n
Jolf, 10 bytes
/uΜr0xdlBH
Explanation
/uΜr0xdlBH
Μr0x map range 0..x
dlBH over lengths of binary elements
/u divide sum of this
by implicit input (x)
Perl 6, 34 32 bytes
{$_ R/[+] map *.base(2).chars,^$_}
{$_ R/[+] map {(.msb||0)+1},^$_}
Explanation:
{
$_ # the input
R/ # divides ( 「$a R/ $b」 is the same as 「$b / $a」 )
[+] # the sum of:
map
{
(
.msb # the most significant digit (0 based)
|| 0 # which returns Nil for 「0.msb」 so use 0 instead
# should be 「(.msb//0)」 but the highlighting gets it wrong
# it still works because it has the same end result
)
+ 1 # make it 1 based
},
^$_ # 「0 ..^ $_」 all the numbers up to the input, excluding the input
}
Test:
use v6.c;
# give it a name
my &mean-bits = {$_ R/[+] map {(.msb||0)+1},^$_}
for 1..7 {
say .&mean-bits
}
say '';
say mean-bits(7).perl;
say mean-bits(7).base-repeating(10);
1
1
1.333333
1.5
1.8
2
2.142857
<15/7>
(2. 142857)
CJam, 13 12 11 bytes
One byte saved thanks to @Sp3000, and another thanks to @jimmy23013
rd_,2fbs,\/
Explanation
Straightforward. Applies the definition.
rd e# read input and convert to double
_ e# duplicate
, e# range from 0 to input minus 1
2fb e# convert each element of the array to binary
s e# convert to string. This flattens the array
, e# length of array
\ e# swap
/ e# divide
Perl 5.10, 54 bytes
for(1..<>){$u+=length sprintf"%b",$_;$n++}$u/=$n;say$u
Pretty much straightforward. sprintf"%b" is a neat way to output a number in binary in Perl without using additional libraries.
PowerShell v2+, 64 bytes
param($n)0..($n-1)|%{$o+=[convert]::ToString($_,2).Length};$o/$n
Very straightforward implementation of the spec. Loops from 0 to $n-1 with |%{...}. Each iteration, we [convert] our input number $_ to a string base2 and take its length. We accumulate that in $o. After the loops, we simply divide $o/$n, leaving that on the pipeline, and output is implicit.
As long as this is, it's actually shorter than the formula that Sp & others are using, since [math]::Ceiling() and [math]::Log() are ridiculously wordy. Base conversion in PowerShell is yucky.
Vitsy, 26 bytes
This is a first attempt, I'll golf this down more and add an explanation later.
0vVV1HV1-\[2L_1+v+v]v1+V/N
Pyth, 6 bytes
.Oml.B
.Oml.BdUQ Filling in implict vars
.O Average of list
m UQ Map over [0..input)
l Length of
.B Binary string representation of int
d Lambda var
Mathematica, 28 bytes
(Tr@⌈Log2@Range@#⌉+1)/#&
or
Tr@⌈Log2@Range@#⌉/#+1/#&
In either case, it's an unnamed function which takes N as an input and returns an exact (rational) result for the mean.
Jelly, 10 bytes
BL©2*2_÷+®
From Sp3000's suggestion.
Jelly, 11 bytes
æḟ2’Ḥ÷_BL$N
Not very short but I need some tips.
Using the same formula as in Sp3000's answer. (It's not very hard to get it yourself, by differentiating geometric progression.)
05AB1E, 9 7 bytes
Code:
L<bJg¹/
Explanation:
L< # range from 0..input-1
b # convert numbers to binary
J # join list of binary numbers into a string
g # get length of string (number of bits)
¹/ # divide by input
Edit: saved 2 bytes thanks to @Adnan
Actually, 7 bytes:
;r♂├Σl/
Explanation:
;r♂├Σl/
; duplicate input
r push range(0, n) ([0, n-1])
♂├ map binary representation
Σ sum (concatenate strings)
l/ divide length of string (total # of bits) by n
If it weren't for a bug that I just discovered, this solution would work for 6 bytes:
r♂├♂læ
æ is the builtin mean command.
J, 21 17 15 bytes
From 17 bytes to 15 bytes thanks to @Dennis.
+/@:%~#@#:"0@i.
Can anyone help me golf this?...
Ungolfed version
range =: i.
length =: #
binary =: #:
sum =: +/
divide =: %
itself =: ~
of =: @
ofall =: @:
binarylength =: length of binary "0
average =: sum ofall divide itself
f =: average binarylength of range
JavaScript (ES7), 38 32 bytes
n=>(l=-~Math.log2(n))-(2**l-2)/n
Using @sp3000's formula (previous version was a recursive solution). ES6 version for 34 bytes:
n=>(l=-~Math.log2(n))-((1<<l)-2)/n
Explanation of formula: Consider the case of N=55. If we write the binary numbers (vertically to save space), we get:
11111111111111111111111
111111111111111100000000000000001111111
11111111000000001111111100000000111111110000000
111100001111000011110000111100001111000011110000111
11001100110011001100110011001100110011001100110011001
0101010101010101010101010101010101010101010101010101010
The size of this rectangle is nl so the average is just l but we need to exclude the blanks. Each row of blanks is twice as long as the previous so the total is 2 + 4 + 8 + 16 + 32 = 64 - 2 = 2l - 2.
Hoon, 71 bytes
|=
r/@
(^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq
...I'm pretty sure this is actually the first time I've used Hoon's floating point cores. It's actually an implementation written in Hoon that jets out to SoftFloat, since the only data types in Hoon are atoms and cells.
Create a function that takes an atom, r. Create a list from [0..(r - 1)], map over the list taking the binary logarithm of the number, then fold over that list with ++add. Convert both the output of the fold and r to @rq (quad-precision floating point numbers) with ++sun:rq, and then divide one by the other.
The oddest thing in this snippet is the :.^rq at the end. a:b in Hoon means "evaluate a in the context of b". ++rq is the core that contains the entire quad-precision implementation, like a library. So running (sun 5):rq is the same thing as doing (sun:rq 5).
Luckily, cores in Hoon are like nesting dolls; when you evaluate the arm ++rq to get the core, it adds the entire stdlib to it as well, so you get to keep roll and turn and gulf and all that fun stuff instead of being stuck with only the arms defined in ++rq. Unluckily, rq redefines ++add to be floating-point add instead, along with not having r in its context. . (the entire current context) does, however.
When evaluating an expression in a context, the compiler looks for the limb depth-first. In our case of a:[. rq] it would look in the entire current context for a before moving on to looking in rq. So add will look up the function that works on atoms instead of floating-point numbers...but so will div. Hoon also has a feature where using ^name will ignore the first found reference, and look for the second.
From there, it's simply using the syntatic sugar of a^b being equal to [a b] to evaluate our snippet with both our current context and the quad-precision float library, ignoring the atomic div in favor of ++div:rq.
> %. 7
|=
r/@
(^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq
.~~~2.1428571428571428571428571428571428
MATL, 9 bytes
:qBYszQG/
Explanation
:qBYszQG/
: % take vector [1..n]
q % decrement by 1 to get [0..n-1]
B % convert from decimal to binary
Ys % cumulative sum (fills in 0's after first 1)
z % number of nonzero elements
Q % increment by 1 to account for zero
G % paste original input (n)
/ % divide for the mean
MATL, 9 bytes
q:ZlksG/Q
Modified version with all test cases
Explanation
% Implicitly grab input (N)
q: % Create array from 1:N-1
Zl % Compute log2 for each element of the array
k % Round down to the nearest integer
s % Sum all values in the array
G % Explicitly grab input again
/ % Divide by the input
Q % Add 1 to account for 0 in [0, ... N - 1]
% Implicitly display the result
Jelly, 6 bytes
R’BFL÷
R’BFL÷ Main monadic chain. Argument: n
R yield [1, 2, ..., n]
’ decrement; yield [0, 1, ..., n-1]
B convert to binary; yield [[0], [1], [1,0], [1,1], ...]
F flatten list; yield [0, 1, 1, 0, 1, 1, ...]
L length of list
÷ divide [by n]
Ruby, 44 34 bytes
Now starring the formula used by @Sp3000
->x{(2.0-2**b=x.to_s(2).size)/x+b}
Old version:
->x{r=0.0;x.times{|i|r+=i.to_s(2).size};r/x}
Julia, 28 bytes
n->mean(ceil(log2([2;2:n])))
Since bin doesn't automatically map over arrays, we're using ceil(log2(n)) to get the number of bits in n-1. This works out nicely because Julia's a:b notation is inclusive on both ends, so 2:n is a range from 2 to n, but we're really calculating the number of bits for numbers in the range 1:n-1. Unfortunately though, we need to tack on an extra 2 to account for 0.
Python 3, 43 bytes
def f(n):x=len(bin(n))-2;return(2-2**x)/n+x
Makes use of the formula on the OEIS page. Surprisingly, a named function is somehow cheaper here because of the assignment to x.
Alternative approach for 46 bytes:
lambda n:-~sum(map(int.bit_length,range(n)))/n
Unfortunately, the -~ is necessary since (0).bit_length() is 0, but even then it'd be a byte too long.
JavaScript ES5, 55 bytes
n=>eval(`for(o=0,p=n;n--;o+=n.toString(2).length/p);o`)
Explanation
n => // anonymous function w/ arg `n`
for( // loop
o=0, // initalize bit counter to zero
p=n // copy the input
;n-- // will decrease input every iteration, will decrease until it's zero
;o+= // add to the bitcounter
n.toString(2) // the binary representation of the current itearations's
.length // length
/p // divided by input copy (to avergage)
);o // return o variable
Octave, 29 bytes
@(n)1+sum(fix(log2(1:n-1)))/n
Explanation
log2(1:n-1) % log2 of numbers in range [1..n-1]
% why no 0? because log2(0) = -Inf :/
fix( ) % floor (more or less, for positive numbers)
sum( ) % sum... wait, didn't we miss a +1 somewhere?
% and what about that missing 0?
/n % divide by n for the mean
1+ % and add (1/n) for each of the n bit lengths
% (including 0!)
Sample run on ideone.
Python 3, 46 Bytes
lambda x:sum(len(bin(i))-2for i in range(x))/x
Call it like
f = lambda x: sum(len(bin(i))-2for i in range(x))/x
print(f(6))
# 2.0
I had to revert the map revision because it failed for input of 5
Minkolang 0.15, 23 bytes
n$z1z[i1+2l$M$Y+]kz$:N.
Explanation
n$z Take number from input and store it in register (n)
1 Push 1 onto the stack
z[ For loop that repeats n times
i1+ Loop counter + 1
2l$M log_2
$Y Ceiling
+ Add top two elements of stack
] Close for loop
z$: Float divide by n
N. Output as number and stop.
Pretty straightfoward implementation.