# Am I a golfy array?

## Definition and Rules

A golfy array is an array of integers, where each element is higher than or equal to the arithmetic mean of all the previous elements. Your task is to determine whether an array of positive integers given as input is golfy or not.

• You do not need to handle the empty list.

• You can choose any two distinct non-empty values. They must be consistent, and must comply with all other rules. This is , shortest code in each language wins!

## Test Cases & Example

For example the following array:

[1, 4, 3, 8, 6]


Is a golfy array, because each term is higher than the arithmetic mean of those preceding it. Let's work it out step-by-step:

Number -> Preceding elements -> Average -> Follows the rule?

1      -> []                 -> 0.0     -> 1 ≥ 0.0   (True)
4      -> [1]                -> 1.0     -> 4 ≥ 1.0   (True)
3      -> [1, 4]             -> 2.5     -> 3 ≥ 2.5   (True)
8      -> [1, 4, 3]          -> 2.(6)   -> 8 ≥ 2.(6) (True)
6      -> [1, 4, 3, 8]       -> 4.0     -> 6 ≥ 4.0   (True)


All the elements respect the condition, thus this is a golfy array. Note that for the purpose of this challenge, we will assume that the average of an empty list ([]) is 0.

More test cases:

Input -> Output

[3]                 -> True
[2, 12]             -> True
[1, 4, 3, 8, 6]     -> True
[1, 2, 3, 4, 5]     -> True
[6, 6, 6, 6, 6]     -> True
[3, 2]              -> False
[4, 5, 6, 4]        -> False
[4, 2, 1, 5, 7]     -> False
[45, 45, 46, 43]    -> False
[32, 9, 15, 19, 10] -> False


Note that this is Puzzle 1 from CodeGolf-Hackathon and is also posted on Anarchy Golf (that one is broken) - Reposted by histocrat, but I am the original author on both sites, and thus allowed to repost them here.

• Is the input always a list of positive integers? Oct 18 '17 at 18:42
• @KellyLowder Yes. Oct 18 '17 at 18:42
• It's a fun problem, I was thinking of reposting it on Anarchy Golf with more test cases but thought you might be working on that. Oct 18 '17 at 19:06
• @histocrat Go ahead and repost it on Anarchy Golf, I should have thought about the things that could be exploited first. I am rather glad you find it interesting (Btw please ping me here and give a link if you repost it). Oct 18 '17 at 19:07
• @streetster Those are equivalent. Sum/i > x is the same as Sum > xi is the same as Sum+x > x(i+1) is the same as (Sum+x)/(i+1) > x. Oct 19 '17 at 13:20

# Python 2, 37 bytes

def g(a):sum(a)>len(a)*a.pop()or g(a)


Try it online!

Outputs via exit code: crashes (exit code 1) for golfy arrays, just exits with exit code 0 for non-golfy arrays. ovs and Jonathan Frech saved 3 bytes.

### Python 2, 44 bytes

f=lambda a:a and sum(a)<=len(a)*a.pop()*f(a)


Try it online!

A more traditional variant, which returns True for golfy arrays, else False. Jonathan Frech saved 2 bytes.

• I think a==[]or can be a and. Oct 18 '17 at 19:20
• That’s actually clever — it comes out to sum(a)<=len(a)*a.pop()*[] for the base case, which is always true as int < list!
– Lynn
Oct 18 '17 at 19:32
• 39 bytes as a function which crashes for truthy inputs.
– ovs
Oct 18 '17 at 20:59
• @ovs 37 bytes using an imperative function. Oct 18 '17 at 22:36

# Jelly, 6 5 bytes

<ÆmƤE


Try it online!

### How it works

<ÆmƤE  Main link. Argument: A (integer array)

ÆmƤ   Compute the arithmetic means (Æm) of all prefixes (Ƥ) of A.
<      Perform element-wise comparison. Note that the leftmost comparison always
yields 0, as n is equal to the arithmetic mean of [n].
E  Test if all elements of the resulting array are equal, which is true if and
only if all comparisons yielded 0.

• cairdcoinheringaahing's 6-byter (alternative): ÆmƤµ⁼Ṣ Oct 18 '17 at 18:54
• @Mr.Xcoder Golfed! Oct 18 '17 at 18:59
• Wow that's brilliant :-) Oct 18 '17 at 19:00

## JavaScript (ES6), 33 32 bytes

a=>a.some(e=>e*++i<(s+=e),s=i=0)


Code also works on negative values such as[-3, -2]. Returns false for a golfy array, true for other arrays. Edit: Saved 1 byte thanks to @JustinMariner.

• You can drop the ! since the spec only asks for two different values, so returning false when it's a golfy array is fine. Oct 18 '17 at 19:33

## Wolfram Language (Mathematica), 35 bytes

Max[Accumulate@#-Range@Tr[1^#]#]>0&


Try it online!

Outputs False for golfy arrays and True otherwise.

• I see the false/true relationship is reversed but that's OK Oct 18 '17 at 18:50

# MATL, 9 8 bytes

tYstf/<a


Outputs 0 for golfy arrays, 1 otherwise.

Try it online!

### Explanation

Consider input [1, 4, 3, 8, 6].

t    % Implicit input. Duplicate
% STACK: [1, 4, 3, 8, 6], [1, 4, 3, 8, 6]
Ys   % Cumulative sum
% STACK: [1, 4, 3, 8, 6], [1, 5, 8, 16, 22]
t    % Duplicate
% STACK: [1, 4, 3, 8, 6], [1, 5, 8, 16, 22], [1, 5, 8, 16, 22]
f    % Find: indices of nonzeros. Gives [1, 2, ..., n], where n is input size
% STACK: [1, 4, 3, 8, 6], [1, 5, 8, 16, 22], [1, 2, 3, 4, 5]
/    % Divide, element-wise
% STACK: [1, 4, 3, 8, 6], [1, 2.5, 2.6667, 4, 4.4]
<    % Less than?, element-wise
% STACK: [0, 0, 0, 0, 0]
a    % Any: true if and only there is some nonzero. Implicit display
% STACK: 0


and.(z(<=).scanl1(+)<*>z(*)[1..].tail)
z=zipWith


Try it online!

Edit: -3 bytes thanks to Zgarb!

Explanation

The above point-free version is equivalent to the following program:

f s = and $zipWith(<=) (scanl1(+)s) (zipWith(*)[1..](tail s))  Given an input s=[1,4,3,8,6], scanl1(+)s computes the prefix sums [1,5,8,16,22] and zipWith(*)[1..](tail s) drops the first element and multiplies all other elements with their index: [4,6,24,24]. The list is now golfy if pairwise the prefix sums are smaller or equal to the elements times index, which can be checked by zipping both lists with (<=) and checking that all results are True with and. • You can avoid the type error like this. Oct 18 '17 at 21:34 • @Zgarb In hindsight this is the obvious solution. Thanks for pointing out! Oct 18 '17 at 21:40 # C# (Visual C# Compiler), 71 + 18 = 89 bytes x=>x.Select((n,i)=>new{n,i}).Skip(1).All(y=>x.Take(y.i).Average()<=y.n)  additional 18 bytes for using System.Linq; Try it online! • Welcome to the site! :) Oct 18 '17 at 19:09 • Generally speaking, import statements are not considered free in code golf. Because this requires the statement using System.Linq; it would actually be 89 bytes, sometimes expressed as "71 + 18 = 89" to show that 18 bytes are required but not part of the solution while still having the final count be the last number in the title line (which is helpful for some automatic parsers). Oct 18 '17 at 19:20 # APL (Dyalog), 10 bytes This is an anonymous tacit prefix function (called a monadic train in APL terms). ∧/⊢≥+\÷⍳∘≢  Try all the test cases on TIO! Is it ∧/ all-true that ⊢ the elements ≥ are greater than or equal to +\ the cumulative sums ÷ divided by ⍳ the integers 1 through ∘ the ≢ number of elements ? • APL has a symbol for "the"?? Oct 19 '17 at 10:29 • @user2390246 ∘ binds together things the same way "the" binds together in "count the cats". It is really called Compose. – Adám Oct 19 '17 at 10:32 # C (gcc), 6260 62 bytes • Removed two superfluous parentheses. • Added two bytes to fix function's reusability (b=). f(A,S,k,b)int*A;{for(S=k=b=0;*A;S+=*A++)b+=!(S<=*A*k++);b=!b;}  Try it online! # 05AB1E, 5 bytes ηÅA÷W  Try it online! Extensive help from Dennis and Adnan got to this reduced version. Also a bug was fixed to make this possible, thanks again you guys. I take little credit for this answer. # 05AB1E, 10 bytes ηεÅA}ü.S_P  Try it online! Long because DgsO/ is the equivalent of "mean" in 05AB1E. Apparently ÅA is arithmetic mean. • To compute the means, I'd use +\÷J (divide cumulative sum by indices) in Jelly. Is it not that easy in 05AB1E? Edit: Nevermind. Oct 18 '17 at 20:49 • @Dennis ah, cumulative sum in 05AB1E is ü+ then there's really no divie by indices other than g to get array length, L to push 1,2,...,n and divide to get the mean, which is still essentially 5 bytes. Oct 18 '17 at 20:51 • .S_ is a LONG way to go for <=, if anyone has any ideas lmk. Oct 18 '17 at 21:10 • Would ÷W work instead of ü.S_P? Oct 18 '17 at 21:39 • Oh, @Adnan just fixed the vectorization of ÅA, so ηÅA÷W works now. Oct 18 '17 at 23:25 # APL (Dyalog), 15 bytes ∧/⊢≥((+/÷≢)¨,\)  Try it online! How?  ,\ all prefixes ¨ for each +/÷≢ calculate arithmetic mean ⊢≥ element wise comparison ∧/ logically and the result  # PowerShell, 60 bytes param($a)$o=1;$a|%{$o*=$_-ge($a[0..$i++]-join'+'|iex)/$i};$o


Try it online!

Takes input as a literal array (e.g., @(1, 4, 3, 8, 6)) into $a. Sets our $output variable to be 1. Then loops through $a. Each iteration, we're (ab)using PowerShell's implicit casting to *= the result of a Boolean comparison against our $output. The Boolean is whether the current value $_ is -greater-than-or-equal to the previous terms $a[0..$i++] added together (-join'+'|iex) divided by how many terms we've already seen $i. So, if any step along the way is false, then $o will get multiplied by 0. Otherwise, it will remain 1 throughout. We then simply place $o onto the pipeline and output is implicit. 1 for truthy and 0 for falsey.

# Perl 5, 27 +2 (-ap) bytes

$_=!grep$_*++$n<($s+=$_),@F  Try It Online # C# (.NET Core), 74 bytes x=>{for(int i=1,s=0;i<x.Count;)if(x[i]<(s+=x[i-1])/i++)return 0;return 1;}  Try it online! Returns 0 for false and 1 for true. 3 Bytes longer than core of chryslovelaces answer. But in total several Bytes shorter because my variant doesn't need any using statements. # Cubix, 35 bytes /I?/\+psu0^.\)*sqs;-\;;U;O1.....?@^  Try it online! Not the most efficient use of space (6 no-ops in the code) Produces no output for a golfy array, 1 for a not-golfy array. Expands to the following cube:  / I ? / \ + p s u 0 ^ . \ ) * s q s ; - \ ; ; U ; O 1 . . . . . ? @ ^ . . . . . . . . . . . . . . . . . . .  Explanation forthcoming, but it basically ports something like Luis Mendo's MATL answer or Dennis' Julia answer. Watch it run! # Matlab and Octave, 41 36 bytes 5 bytes saved thx to Luis Mendo all([a inf]>=[0 cumsum(a)./find(a)])  Try it online! • @LuisMendo That would break it if any element of a is zero. But that's a handy trick nonetheless in similar situations, have to keep that one in mind. Oct 21 '17 at 11:56 • Reading is difficult! Thx! Oct 21 '17 at 14:01 • Happens to me all the time :-) Oct 21 '17 at 14:29 # SQL (MySQL), 68 bytes select min(n>=(select ifnull(avg(n),1)from t s where s.i<t.i))from t  Try it online! Returns 1 for golfy arrays, and 0 otherwise. Takes input from a named table, t. In order to create t, run: CREATE TABLE t(i SERIAL,n INT)  and to load the values: truncate table t;insert into t(n)values(3),(2);  # Ruby, 30 bytes ->a{0until a.pop*a.size<a.sum}  Try it online! Inspired by Lynn's answer. Throws NoMethodError for golfy, returns nil otherwise. # Python 2, 52 bytes lambda A:all(k*j>=sum(A[:j])for j,k in enumerate(A))  Try it online! # Python 2, 504844 42 bytes • Saved two bytes by inlining and using and. • Saved two bytes thanks to Mr. Xcoder by chaining assignment S=k=0. • Saved two bytes by using or and the comparison's boolean value as k's increment value. • Saved two bytes thanks to ovs; raising a NameError by using an undefined variable instead of a ZeroDivisionError. S=k=0 for j in input():k+=S<=j*k or J;S+=j  Try it online! • 46 bytes for your alternative version. Oct 18 '17 at 18:51 • @Mr.Xcoder Thanks. Oct 18 '17 at 18:56 • 42 bytes – ovs Oct 18 '17 at 20:50 • @ovs Thanks; neat one-byte way to raise an exception. Oct 18 '17 at 21:12 # q/kdb+, 14 bytes Solution: min x>=avgs x:  Examples: q)min x>=avgs x:1 4 3 8 6 1b / truthy q)min x>=avgs x:4 2 1 5 7 0b / falsey  Explanation: Fairly simple with the avgs built-in: min x>=avgs x: / solution x: / store input in variable x avgs / calculate running averages x>= / array comparison, x greater than running average min / take minimum of list of booleans  # Julia 0.6, 29 bytes !x=any(find(x).*x.<cumsum(x))  Returns false or true. Try it online! # R, 38 34 bytes function(x)any(cumsum(x)/seq(x)>x)  Try it online! • very nice. Dunno why there wasn't an R answer before... Jun 26 '18 at 15:11 • You were all saving an easy one for me. – ngm Jun 26 '18 at 15:23 • instead of defining y in the function arguments, using cumsum(x) directly is 4 bytes shorter. It's a shame cummean doesn't exist in base R. Jun 26 '18 at 15:24 # Add++, 54 bytes D,g,@@#,BFB D,k,@,¦+AbL/ D,f,@,dbLR$€g€k0b]$+ABcB]£>ª!  Try it online! ### Unoriginal version, 30 bytes D,f,@,¬+AbLRBcB/@0@B]ABcB]£>ª!  Try it online! Both output 1 for golfy arrays and 0 otherwise ## How they work The first version was created by me, without checking any other solutions. The second was inspired by Dennis' comment, so I'm less happy with it. ### The first version Here, we define our main function $$\f\$$ that computes the golfiness of our input array, $$\A\$$. First, we need to yield the suffixes of $$\A\$$, which is done by first generating the range $$\B := [1, ... \vert{A}\vert]\$$, where $$\\vert{A}\vert\$$ denotes the length of $$\A\$$. This is done with the code dbLR$, which leaves $$\[B, A]\$$ as the stack. We then iterate the dyadic function $$\g\$$ over these two lists. Being dyadic, the function binds its left argument as $$\A\$$ for each iterated element. It then iterates over the range $$\B\$$, which each element from $$\B\$$ being the right argument provided to $$\g\$$. $$\g\$$ is defined as

D,g,@@#,BFB


which is a dyadic function (i.e. takes $$\2\$$ arguments), and pushes its arguments to the stack in reversed order (#) before execution. BF then flattens the two arguments. We'll assume that the arguments are $$\A\$$ and $$\e \in x\$$. This leaves the stack as $$\[...A, e]\$$, where $$\...\$$ represents an array splat. Finally, B takes the first $$\e\$$ elements of $$\A\$$ and returns a list containing those elements.

Note : The function names $$\g\$$ and $$\k\$$ aren't chosen randomly. If the commands given to an operator (such as €) doesn't currently have a function (which g and k don't), then the named functions are searched for a matching function. This saves $$\2\$$ bytes, as normally the function would have to wrapped in {...} to be recognised as a user-defined function. At the time of writing, the currently unused single byte commands are I, K, U, Y, Z, g, k, l, u and w.

When $$\g\$$ is applied over the elements of a range $$\x\$$, this returns a list of prefixes for $$\A\$$. We then map our second helper function $$\k\$$ over each of these prefixes. $$\k\$$ is defined as

D,k,@,¦+AbL/


which is the standard implementation of the arithmetic mean. ¦+ calculates the sum of the argument, AbL calculates its length, then / divides the sum by the length. This calculates the arithmetic mean of each prefix, yielding a new array, $$\C\$$.

Unfortunately, $$\C\$$ contains the mean of $$\A\$$ as its final element, and does not include the mean of the empty list, $$\0\$$. Therefore, we would have to remove the final element, and prepend a $$\0\$$, but popping can be skipped, saving two bytes, for reasons explained in a second. Instead, we push $$\[0]\$$ underneath $$\C\$$ with 0b]$, then concatenate the two arrays forming a new array, $$\C^+\$$. Now, we need to check each element as being less than its corresponding element in $$\A\$$. We push $$\A\$$ once again and zip the two arrays together with ABcB]. This is the reason we don't need to pop the final element: Bc is implemented with Python's zip function, which truncates the longer arrays to fit the length of the shortest array. Here, this removes the final element of $$\C^+\$$ when creating the pairs. Finally, we starmap $$\p \in A, q \in C^+; p < q \equiv \neg(p \ge q)\$$ over each pair $$\p, q\$$ to obtain an array of all $$\0\$$s if the array is golfy, and array containing at least a single $$\1\$$ if otherwise. We then check that all elements are falsey i.e. are equal to $$\0\$$ with ª! and return that value. ### The second version This takes advantage of Dennis' approach to remove $$\24\$$ bytes, by eliminating the helper functions. Given our input array of $$\A\$$, we first compute the cumulative sums with ¬+, i.e the array created from $$\[A_0, A_0+A_1, A_0+A_1+A_2, ..., A_0+...+A_i]\$$. We then generate Jelly's equivalent of J (indicies), by calculating the range $$\B := [1 ... \vert{A}\vert]\$$ where $$\\vert{A}\vert\$$ once again means the length of the array. Next, we divide each element in $$\A\$$ by the corresponding index in $$\B\$$ with BcB/ and prepend $$\0\$$ with @0@B]. This results in a new array, $$\C^+\$$, defined as $$C^+ := [0, A_0, \frac{A_0+A_1}{2}, \frac{A_0+A_1+A_2}{3}, ..., \frac{A_0+...+A_i}{i+1}]$$ The final part is identical to the first version: we push and zip $$\A\$$ with $$\C^+\$$, then starmap inequality over each pair before asserting that all elements in the resulting array were falsy. # Pyth, 11 10 bytes -1 byte thanks to Mr. Xcoder .A.egb.O<Q  Try it online! • 7 bytes: SI.OM._ (port of cairdcoinheringaahing's solution from Jelly, by Erik the Outgolfer), or 10 bytes using your approach: .A.egb.O<Q Oct 19 '17 at 12:19 • Post the port as yourself, it's a totally different approach! – Dave Oct 19 '17 at 12:21 # Java (OpenJDK 8), 96 bytes I know it's not a good golfing language, but I still gave it a go! Input array as first argument of comma separated ints to test. Returns 1 for true, 0 for false. a->{int i=1,j,r=1,s=0;for(;i<a.length;i++,s=0){for(j=0;j<i;s+=a[j++]);r=s/i>a[i]?0:r;}return r;}  Try it online! # Java 7, 100 bytes Golfed: int g(int[]a){int i=1,m=0,s=m,r=1;for(;i<a.length;){s+=a[i-1];m=s/i;r-=a[i++]<m&&r>0?1:0;}return r;}  Ungolfed: int golfy(int[]a) { int i = 1, m = 0, s = m, r = 1; for (; i < a.length;) { s += a[i-1]; m = s / i; r -= a[i++] < m && r>0? 1 : 0; } return r; }  Try it online Returns 0 for ungolfy and 1 for golfy arrays. Slightly longer than java 8 answer. # PHP, 44 bytes while($n=$argv[++$i])$n<($s+=$n)/$i&&die(1);


takes input from command line arguments, exits with 0 (ok) for a golfy array, with 1 else.

Run with -nr or try it online.

# J, 19 bytes

[:*/[>:[:}:0,+/\%#\


+/\ % #\ averages of the prefixes: #\ produces 1..n

}:0, add 0 to the beginning and remove the last

[>: is the original list element by element >= to the shifted list of averages?

*/ are all the elements greater, ie, the previous list is all 1s?

Try it online!

# AWK, 39 bytes

{for(;i++*$i>=s&&i<=NF;s+=$i);\$0=i>NF}1


Try it online!

Note that the TIO link has 5 extra bytes i=s=0 to allow for multi-line input.

# Japt, 10 bytes

Came up with two 10 byte solutions, can't seem to improve on that.

eÈ¨U¯Y x÷Y


Try it

## Explanation

               :Implicit input of array U
eÈ             :Is every element, at 0-based index Y
¨            :Greater than or equal to
U¯Y         :U sliced from index 0 to index Y
÷Y     :Divide each element by Y


## Alternative

eÈ*°Y¨(T±X


Try it

               :Implicit input of array U
eÈ             :Is every element X (at 0-based index Y)
*°Y          :Multiplied by Y incremented by 1
¨         :Greater than or equal to
(T±X     :T (initially 0) incremented by X