28
\$\begingroup\$

Disclaimer: This challenge is inspired by a coding error I once made.


Okay, time for a maths lesson. A normal mean average looks like this:

Work out the sum of all numbers in a list
then divide by the size of the list.

But what if we don't know all the numbers at the time we're working out the average? We need a way to work out the average which can be added to over time. For this reason, I present the algorithm for a Progressive Mean™

The running total is the first number in the list
For each of the remaining numbers
  Add the number to the running total
  Divide the running total by two

So in effect we're averaging each number with the current average. (We could add to this later and get the same result)

BUT

This doesn't give the same result at all. It gives an average, but it differs from the standard methodology for finding the mean. Now the order of the list of numbers is significant.

Of course, being a curious type, I want to work out if the Progressive Mean™ tells us anything about the order of our list of numbers. So for this reason I want to compare Mean with Progressive Mean™ by means of a simple subtraction:

trend = Progressive Mean™ - Standard Mean

The Challenge

  • Write a piece of code which accepts a list of numbers (in any format) which then calculates three pieces of information about it:
    • Standard Mean
    • Progressive Mean™
    • Trend (Progressive - standard)
  • Work in any language you like.
  • It's golf, attempt to do the challenge in as few bytes as you can.
  • Avoid Standard Loopholes
  • I want the output to be human-readable numbers.
  • Please include a link to an online interpreter such as tio.run

Test Cases:

[1,2,3]

Normal Mean:        2.0
Progressive Mean:   2.25
Trend:              0.25
[3, 2, 1]

Normal Mean:        2.0
Progressive Mean:   1.75
Trend:              -0.25
[10, 20, 30]

Normal Mean:        20.0
Progressive Mean:   22.5
Trend:              2.5
[300, 200, 100]

Normal Mean:        200.0
Progressive Mean:   175.0
Trend:              -25.0
[10, 100, 10]

Normal Mean:        40.0
Progressive Mean:   32.5
Trend:              -7.5
[4, 4, 9, 8, 1, 8, 6, 9, 1, 1]

Normal Mean:        5.1
Progressive Mean:   2.62890625
Trend:              -2.4710937499999996
[1, 1, 1, 4, 4, 6, 8, 8, 9, 9]

Normal Mean:        5.1
Progressive Mean:   8.5390625
Trend:              3.4390625000000004
[9, 9, 8, 8, 6, 4, 4, 1, 1, 1]

Normal Mean:        5.1
Progressive Mean:   1.47265625
Trend:              -3.6273437499999996
\$\endgroup\$
  • 2
    \$\begingroup\$ Do we have to output all 3 calculations, or just the trend? \$\endgroup\$ – Kobe Feb 3 at 13:07
  • 2
    \$\begingroup\$ ...also a set has no order, while here the order is paramount. \$\endgroup\$ – Jonathan Allan Feb 3 at 13:14
  • 1
    \$\begingroup\$ I’m fine with it being called list. Yes, all three calculations, please. \$\endgroup\$ – AJFaraday Feb 3 at 13:15
  • 3
    \$\begingroup\$ I believe your progressive mean is a type of decaying average. \$\endgroup\$ – Neil Feb 3 at 13:24
  • 13
    \$\begingroup\$ Just commenting to point out that your "progressive mean" is well known and used; it's an exponentially weighted moving average with coefficient 1/2. \$\endgroup\$ – acwaters Feb 4 at 19:39

24 Answers 24

10
\$\begingroup\$

R, 57 bytes

function(v,`!`=sum,N=!1^v)c(A<-!v/N,P<-!v/2^c(N:1,N),P-A)

Try it online!

A clever collaboration with digEmAll and RobinRyder; uses the observation by Grimmy and Kevin's explanation from the comments, which I replicate below:

For anyone else wondering why the example [a,b,c,d] -> [a,b,c,c,d,d,d,d] doesn't match the explanation of the code, it actually transforms [a,b,c,d] to [a,b,b,c,c,c,c,d,d,d,d,d,d,d,d,a] (so two of each value in comparison to the example). The example confused me for a moment. But nice answer, +1 from me! I also like that it has all these different types of the letter 'A' in the code: āÅÅAÂƪ. xD

This uses R's recycling rules to use two copies of l[1]/2^N in the sumby just sticking an extra N at the end of the decay rate.

R, 62 bytes

function(l)c(p<-Reduce(function(x,y)(x+y)/2,l),a<-mean(l),p-a)

Try it online!

Straightforward implementation.

| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ Try it online! - same length (62) but using the fancier approach (maybe I'm missing some trivial improvements) \$\endgroup\$ – digEmAll Feb 4 at 12:54
  • 1
    \$\begingroup\$ 59 bytes by building on @digEmAll 's approach. \$\endgroup\$ – Robin Ryder Feb 4 at 17:49
  • \$\begingroup\$ @RobinRyder neither yours nor digEmAll's (nor my 51 byte solution) works for the case of 1 element...I guess I can ask about that. \$\endgroup\$ – Giuseppe Feb 4 at 21:35
  • 1
    \$\begingroup\$ @digEmAll actually, using the observation of Kevin's comment here, we can just use R's recycling rules to take Robin's answer and shave off another two bytes. \$\endgroup\$ – Giuseppe Feb 4 at 21:43
8
\$\begingroup\$

J, 17 bytes

Translation of this.

-:@+/@|.(,,-)+/%#

Anonymous tacit prefix function. Returns list of Progressive Mean™, Standard Mean, Trend.

Try it online! This consists of three parts: (2÷⍨+)⌿∘⌽(,,-)+⌿÷≢

+/ % # is the sum divided by the number of elements

⌿@|. reverses the list and then reduces from right to left using the function:
-:@+ add next value to previous value and halve that

(,,-) is the concatenation of the PM and the SM, concatenated to their difference

| improve this answer | |
\$\endgroup\$
7
\$\begingroup\$

Python 3.8 (pre-release), 70 69 bytes

-1 byte thanks to Kyle Gullion

returns (mean, p_mean, trend)

lambda x:(m:=sum(x)/len(x),[p:=x[0],*[p:=(p+n)/2for n in x]][-1],p-m)

Try it online!

Alternate version with more of a reducer implementation (89 bytes):

lambda x:(m:=sum(x)/(l:=len(x)),[x:=[sum(x[0:2])/2]+x[2:]for n in range(l-1)][-1],x[0]-m)

Although this is longer, I suspect this reducer implementation may be useful for future python 3.8 code golfing.

Try it online!

I know there has to be some more clever tricks to golf this further...

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ can shave a byte using tuple unpacking: Try it online! \$\endgroup\$ – Kyle G Feb 4 at 14:44
6
\$\begingroup\$

05AB1E, 13 bytes

ÅAIÅ»+;}θ‚Âƪ

Outputs as a triplet [mean, progressive-mean, trend].

Try it online or verify all test cases.

Explanation:

ÅA     # Calculate the arithmetic mean of the (implicit) input-list
I      # Push the input-list again
 Å»    # Left-reduce it by:
   +   #  Add the two values together
    ;  #  And halve it
 }θ    # After the reduction, leave only the last value
‚      # Pair it with the earlier calculated arithmetic mean
 Â     # Bifurcate this pair; short for Duplicate & Reverse copy
  Æ    # Reduce it by subtraction
   ª   # And append this trend to the pair
       # (after which the result is output implicitly)
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ @Grimmy I kinda wish Å»+;}θ could be done shorter though. Unfortunately .»ÅA doesn't work, since ÅA only works on lists, and not on the values on the stack, so it will just output the last integer of the input-list unfortunately. \$\endgroup\$ – Kevin Cruijssen Feb 3 at 14:09
  • 2
    \$\begingroup\$ I found the fix: ā<oÅΓĆ‚€ÅAÂƪ. The first number has the same weight as the second number, my mistake was giving it only half of that weight. This is now 13 bytes like yours; I'll make it a separate answer. \$\endgroup\$ – Grimmy Feb 3 at 14:10
  • 2
    \$\begingroup\$ Actually, ÅA vectorizes, so I can drop the for a 12. \$\endgroup\$ – Grimmy Feb 3 at 14:19
6
\$\begingroup\$

Scratch 2.0/3.0, 35 blocks/263 bytes

Blocks

SB Syntax:

when gf clicked
set[i v]to(2
set[L v]to(length of[I v
set[T v]to(item(1)of[I v
set[P v]to(T
repeat((L)-(1
change[T v]by(item(i)of[I v
change[P v]by(item(i)of[I v
set[P v]to((P)/(2
change[i v]by(1
end
set[T v]to((T)/(L
say(join(join(join(join(P)[,])(T))[,])((P)-(T

It's accidentally a polyglot. I accidentally forgot my password and email for my other scratch account so I had to make a new one so y'all can Try it on Scratch!

Y'all need to change the input list shown in the top left corner on the project for this to work properly.

| improve this answer | |
\$\endgroup\$
5
\$\begingroup\$

Python 3, 81 \$\cdots\$ 75 71 bytes

Saved 15 bytes thanks to Reinstate Monica!!!

def f(l):
 m=sum(l)/len(l);p=l[0]
 for n in l:p=(p+n)/2
 return m,p,p-m

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You can remove the parentheses in the return statement, no? \$\endgroup\$ – squid Feb 3 at 16:44
  • \$\begingroup\$ @ReinstateMonica Didn't know that - Thanks! :-) \$\endgroup\$ – Noodle9 Feb 3 at 16:46
  • \$\begingroup\$ No problem! Also, since (p[0]+p[0])/2 == p[0], the pop is unnecessary; you can just use l[0] \$\endgroup\$ – squid Feb 3 at 16:50
  • \$\begingroup\$ @ReinstateMonica Clever - thanks again! :-) \$\endgroup\$ – Noodle9 Feb 3 at 17:00
4
\$\begingroup\$

JavaScript (ES6), 55 bytes

Returns [mean, p_mean, trend].

a=>a.map(v=>t=(s+=v,n++)?(t+v)/2:v,n=s=0)&&[s/=n,t,t-s]

Try it online!

| improve this answer | |
\$\endgroup\$
4
\$\begingroup\$

APL (Dyalog Unicode), 20 18 bytesSBCS

-2 thanks to Bubbler.

Anonymous tacit prefix function. Returns list of Progressive Mean™, Standard Mean, Trend.

(2÷⍨+)⌿∘⌽(,,-)+⌿÷≢

Try it online!

This consists of three parts: (2÷⍨+)⌿∘⌽(,,-)+⌿÷≢

+⌿ ÷ ≢ is the sum divided by the count

()⌿∘⌽ reverses the list and then reduces from right to left using the function:
2÷⍨+ add next value to previous value and divide two by that

(,,-) is the concatenation of the PM and the SM, concatenated to their difference

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ @Bubbler Of course it can. Thanks. \$\endgroup\$ – Adám Feb 3 at 13:29
4
\$\begingroup\$

05AB1E, 12 bytes

āÍoîÅΓ‚ÅAÂƪ

Try it online!

The progressive mean is equivalent to a weighted arithmetic mean, with exponentially increasing weights. For example, the progressive mean of a 4 element list [a, b, c, d] is the arithmetic mean of [a, b, c, c, d, d, d, d].

ā              # range [1..length of input]
 Í             # subtract 2 from each
  o            # 2**each: [0.5, 1, 2, ...]
   î           # round up: [1, 1, 2, ...]
    ÅΓ         # run-length decode
      ‚        # pair with the input
       ÅA      # arithmetic mean of each list
         Â     # push a reversed copy
          Æ    # reduce by subtraction
           ª   # append
| improve this answer | |
\$\endgroup\$
  • 4
    \$\begingroup\$ For anyone else wondering why the example [a,b,c,d] -> [a,b,c,c,d,d,d,d] doesn't match the explanation of the code, it actually transforms [a,b,c,d] to [a,b,b,c,c,c,c,d,d,d,d,d,d,d,d,a] (so two of each value in comparison to the example). The example confused me for a moment. But nice answer, +1 from me! I also like that it has all these different types of the letter 'A' in the code: āÅÅAÂƪ. xD \$\endgroup\$ – Kevin Cruijssen Feb 3 at 14:32
  • 1
    \$\begingroup\$ @KevinCruijssen I changed the code to match the explanation (same byte count). \$\endgroup\$ – Grimmy Feb 3 at 14:46
3
\$\begingroup\$

Factor, 80 79 bytes

: f ( s -- s ) [ mean ] [ dup first [ + 2. / ] reduce ] bi 2dup swap - 3array ;

Try it online!

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Wolfram Language (Mathematica), 31 bytes

{a=Mean@#,b=+##/2&~Fold~#,b-a}&

Try it online! Pure function. Takes a list of numbers as input and returns a list of rational numbers as output. I'm pretty sure that improper fractions count as human-readable, but if they aren't, adding N@ (+2 bytes) to the start causes the function to output approximate numbers.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Jelly, 9 bytes

Æm;+H¥/ṄI

A full program which accepts a list of decimals which prints:

[mean, progressive-mean]
trend

Try it online!

How?

Æm;+H¥/ṄI - Link: list of numbers, A
Æm        - arithmetic mean       sum(A)/length(A)            = mean
      /   - reduce (A) by:
     ¥    -   the dyad f(leftEntry, rightEntry):
   +      -     addition          leftEntry + rightEntry
    H     -     halve            (leftEntry + rightEntry) / 2 = progressiveMean
  ;       - concatenate           [mean, progressiveMean]
       Ṅ  - print this list and yield it
        I - deltas                [progressiveMean - mean]
          - implicit print (Jelly represents with a single item as the item)
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

PowerShell, 54 bytes

$args|%{$y+=$_;$z=($_+$z)/(2-!$i++)}
($y/=$i)
$z
$z-$y

Try it online!

Takes input by splatting. The only neat trick is the !$i++ bit which negates the first iteration where $i is 0 to 1, and all subsequent numbers to 0.

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Raku(Perl 6), 41 40 bytes

{|($/=(.reduce((*+*)/2),.sum/$_)),$0-$1}

My original solution had my \a=and used [-]|@a at the end, but abusing $/ is always fun, especially with also abusing assignments. Pretty straightforward calculation wise.

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Charcoal, 27 bytes

≔∕ΣθLθη≔§θ⁰ζFθ≔⊘⁺ιζζI⟦ηζ⁻ζη

Try it online! Link is to verbose version of code. Explanation:

≔∕ΣθLθη

Calculate the arithmetic mean.

≔§θ⁰ζ

Start with the first element. We therefore end up averaging this element with itself, but that doesn't affect the final result of course.

Fθ≔⊘⁺ιζζ

Loop over each element an average it with the progressive mean so far.

I⟦ηζ⁻ζη

Print the arithmetic and progressive means and their difference.

If we had only needed the result once then ΣEθ∕ιX²⁻Lθ∨κ¹ could have been used to calculate the progressive mean directly, saving 3 bytes over the naïve method.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Haskell, 84 bytes

I thought Haskell could do decently here because this challenge works on lists and I tend to think Haskell and lists go well together... But I couldn't come up with anything very clever. Let's see if @xnor drops by and has anything nice :P

f(h:l)=g$foldl(\(p,s,w)n->((p+n)/2,s+n,w+1))(h,h,1)l
f[]=f[0]
g(p,s,l)=(s/l,p,p-s/l)

I am defining an anonymous function \(p,s,w) n -> ((p+n)/2, s+n, w+1) that receives a triplet and the next list element, and does three things: updates the progressive mean, sums the whole list and computes its length. In the end, function g does some last-minute calculations.

You can try it online

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

PHP, 90 88 bytes

function($i){for($j=$i[0];$x=$i[$c++|0];$s+=$x,$j+=$x,$j/=2);return[$s/=$c-1,$j,$j-$s];}

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Perl 5 -MList::Util=sum,reduce -pa, 51 50 bytes

say+($\=reduce{$a=$a/2+$b/2}@F)-($_=(sum@F)/@F.$/)

Try it online!

Output format is

trend
traditional
progressive
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Burlesque, 19 bytes

psJr{.+2./}javq.-c!

Try it online!

Takes input of the form 300.0 200.0 100.0. If we didn't have to print the other values would be 3 bytes shorter (i.e. Without the continuation). Returns progressive mean™, arithmetic mean, trend

ps    # Parse list to array
J     # Duplicate
r{    # Reduce by (Progressive Mean)
  .+  # Adding
  2./ # Dividing by 2
}
jav   # Calulcate regular mean
q.-   # Quoted (boxed) subtract {.-}
c!    # On a non-destructive stack
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Python 3.8, 91 bytes

I wanted to flatten the recursive relation, and I got this:

lambda l:(m:=sum(l)/(n:=len(l)),(p:=sum(l[-i]/2**i for i in range(1,n))+l[0]/2**(n-1)),p-m)

Try it online!

The use of range instead of the list itself makes it much longer.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ you can remove the brackets around the middle section to save 2 bytes Try it online! \$\endgroup\$ – mabel Feb 4 at 16:09
1
\$\begingroup\$

Ruby, 54 bytes

->x{a=x.sum/x.size;b=x.inject{|a,b|a/2+b/2};[a,b,b-a]}

Try it online!

Takes a list of numbers in the format [1.0, 2.0, 3.0] and returns an array containing the mean, progressive-mean, and trend, respectively.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Haskell, 58 bytes

s!p=(s,p,p-s)
f x=(sum x/sum[1|_<-x])!foldl1(((/2).).(+))x

Try it online!

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Rust, 144 122 bytes

let f=|y:&[f64]|{let m=y.iter().sum::<f64>()/y.len()as f64;let pm=y[1..].iter().fold(y[0],|acc,x|(acc+x)/2.);(m,pm,pm-m)};

Straightforward approach. Shaved 22 bytes thanks SirBogman, and thanks Mabel for showing TIO's Rust support.

Try it online!

| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ here you go :) Try it online! \$\endgroup\$ – mabel Feb 5 at 22:49
  • 1
    \$\begingroup\$ You can remove the return keyword and the semicolon following the return statement. \$\endgroup\$ – SirBogman Feb 7 at 0:41
1
\$\begingroup\$

Java (JDK), 116 115 bytes

v->{float m=0,p=0;for(int i=0;i<a.length;i++){m+=a[i];p+=a[i];p=i!=0?p/2:p;}m/=a.length;return m+"\n"+p+"\n"+(p-m);

Try it online!

| improve this answer | |
\$\endgroup\$

Your Answer

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

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