我是高尔夫球爱好者吗?


18

定义和规则

golfy阵列是一个整数数组,其中每个元素是高于或等于所有先前元素的算术平均值。您的任务是确定作为输入给定的正整数数组是否适合。

测试案例与范例

例如以下数组:

[1, 4, 3, 8, 6]

是一个高尔夫球状数组,因为每个项都高于其前面的算术平均值。让我们逐步解决:

数字->前置元素->平均->是否遵循规则?

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

所有元素都符合条件,因此这是一个高尔夫球阵列。请注意,就本挑战而言,我们将假定一个空列表([])的平均值为0

更多测试用例:

输入->输出

[3]->正确
[2,12]->是
[1,4,3,8,6]->是
[1、2、3、4、5]->是
[6,6,6,6,6]->是
[3,2]->错误
[4、5、6、4]->错误
[4,2,1,5,7]->错误
[45,45,46,43]->错误
[32,9,15,19,10]->错误

请注意,这是拼图1CodeGolf-黑客马拉松,也张贴在无政府状态高尔夫(即一个被打破) - 转贴通过histocrat,但我在这两个网站的原作者,从而允许在这里重新发布它们。


输入是否始终是正整数列表?
凯莉·洛德

@KellyLowder是的。
Xcoder先生17年

这是一个有趣的问题,我本来打算通过更多测试用例将其重新发布到Anarchy Golf上,但认为您可能正在研究中。
历史学家

@histocrat继续并在Anarchy Golf上重新发布它,我应该考虑可以首先利用的东西。我很高兴您发现它很有趣(顺便说一句,如果您重新发布它,请在这里ping我并提供一个链接)。
Xcoder先生17年

3
@streetster这些是等效的。Sum / i> x等于Sum> xi与Sum + x> x(i + 1)相同,等于(Sum + x)/(i + 1)> x。
历史学家

Answers:


13

Python 2,37个字节

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

在线尝试!

通过出口代码输出:golfy阵列崩溃(退出代码1),对于非高尔夫阵列仅退出,出口代码为0。ovs和Jonathan Frech保存了3个字节。

Python 2,44字节

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

在线尝试!

一个更传统的变体,返回True高尔夫球状阵列,否则False。乔纳森·弗雷希(Jonathan Frech)保存了2个字节。


1
我认为a==[]or可以a and
乔纳森·弗雷奇

2
这实际上很聪明-它是sum(a)<=len(a)*a.pop()*[]针对基本情况得出的,总是如此int < list
林恩

3
39个字节作为函数,对于真实输入会崩溃。
ovs

1
@ovs 使用命令式函数的37个字节
乔纳森·弗雷希

11

果冻6 5字节

<ÆmƤE

在线尝试!

怎么运行的

<Æ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的6人制(替代):ÆmƤµ⁼Ṣ
Xcoder先生,17年

@ Mr.Xcoder打高尔夫球了!
丹尼斯,

哇,真是
太好了

5

JavaScript(ES6),33 32字节

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

代码还适用于负值,例如[-3, -2]。返回falsegolfy数组,true其他数组。编辑:感谢@JustinMariner,节省了1个字节。


1
您可以删除,!因为规范仅要求提供两个不同的值,所以false当它是golfy数组时返回就可以了。
贾斯汀·马里纳


4

MATL9 8字节

tYstf/<a

0Golfy数组的输出,1否则。

在线尝试!

说明

考虑输入[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

4

Haskell53 50 48字节

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

在线尝试!

编辑: -3字节感谢Zgarb!

说明

上面的无积分版等效于以下程序:

f s = and $ zipWith(<=) (scanl1(+)s) (zipWith(*)[1..](tail s))

给定输入s=[1,4,3,8,6]scanl1(+)s计算前缀和,[1,5,8,16,22]zipWith(*)[1..](tail s)删除第一个元素,然后将所有其他元素与其索引相乘:[4,6,24,24]。现在,这份清单golfy如果成对前缀款项是小于或等于元素时报指数,它可以通过压缩和解两份名单进行检查(<=),并检查所有的结果都Trueand


1
你能避免错误类型是这样
Zgarb

@Zgarb事后看来,这是显而易见的解决方案。感谢您指出!
Laikoni '17

3

C#(Visual C#编译器),71 + 18 = 89字节

x=>x.Select((n,i)=>new{n,i}).Skip(1).All(y=>x.Take(y.i).Average()<=y.n)

额外的18个字节 using System.Linq;

在线尝试!


2
欢迎光临本站!:)
DJMcMayhem

一般来说,代码声明中不会将import声明视为免费的。因为这需要该语句,using System.Linq;所以它实际上是89个字节,有时表示为“ 71 + 18 = 89”,以表示需要18个字节,但不是解决方案的一部分,而最终计数仍是标题行中的最后一个数字(这对某些自动解析器很有帮助)。
卡米尔·德拉卡里

3

APL(Dyalog),10字节

这是一个匿名的默认前缀函数(在APL术语中称为单子串)。

∧/⊢≥+⍳∘≢

在TIO上尝试所有测试用例!

是吗

∧/ 完全正确

 要素

 大于或等于

+\ 累计金额

÷ 除以

   整数1到整数

   的

   元素数量


APL有一个符号“ the”?
user2390246 '17

1
@ user2390246 将事物绑定在一起的方式与“ the”在“计数猫”中绑定在一起的方式相同。它真的叫做Compose
阿达姆(Adám)


3

05AB1E,5个字节

ηÅA÷W

在线尝试!

丹尼斯(Dennis)和阿德南(Adnan)提供了广泛的帮助,简化了版本。还修正了一个错误,以使之成为可能,再次感谢你们。我对这个答案不屑一顾。


05AB1E,10个字节

ηεÅA}ü.S_P

在线尝试!


长期以来 DgsO/等同于05AB1E中的“平均值”。

显然ÅA是算术平均值。


为了计算均值,我+\÷J将在Jelly中使用(将累积总和除以索引)。在05AB1E中不是那么容易吗?编辑:没关系。
丹尼斯

@Dennis啊,05AB1E中的累加总和ü+实际上不是除索引以外的除数之外,除了g获得数组长度,L1,2,...,n和除以得到均值外,该均值本质上仍为5个字节。
魔术章

.S_<=如果有人有任何想法,这是一个漫长的路要走。
魔术章鱼缸

÷W代替ü.S_P吗?
丹尼斯,

1
哦,@ Adnan刚刚修复了的向量化ÅA,所以ηÅA÷W现在可以使用。
丹尼斯


2

PowerShell,60字节

param($a)$o=1;$a|%{$o*=$_-ge($a[0..$i++]-join'+'|iex)/$i};$o

在线尝试!

将输入作为文字数组(例如@(1, 4, 3, 8, 6))输入$a。将$output变量设置为1。然后循环$a。每次迭代时,我们都(使用)PowerShell的隐式强制转换为*=与我们的$output 进行布尔比较的结果。布尔值$_是当前值是否-g等于或等于e先前项的总和$a[0..$i++]-join'+'|iex)除以我们已经看到的项数$i。因此,如果过程中的任何步骤为假,$o则将乘以0。否则,它将保留1

然后,我们只需将其放置$o在管道上即可,输出是隐式的。1为真与0假。




2

Cubix,35个字节

/I?/\+psu0^.\)*sqs;-\;;U;O1.....?@^

在线尝试!

不是最有效地利用空间(代码中没有6个操作),1对于golfy阵列和非golfy阵列不产生任何输出。

扩展到以下多维数据集:

      / I ?
      / \ +
      p s u
0 ^ . \ ) * s q s ; - \
; ; U ; O 1 . . . . . ?
@ ^ . . . . . . . . . .
      . . .
      . . .
      . . .

即将到来的解释,但是它基本上移植了Luis Mendo的MATL答案或Dennis的Julia答案之类的东西

观看它运行!



2

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


1

Python 2, 52 bytes

lambda A:all(k*j>=sum(A[:j])for j,k in enumerate(A))

Try it online!

Python 2, 50 48 44 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.
Mr. Xcoder

@Mr.Xcoder Thanks.
Jonathan Frech


@ovs Thanks; neat one-byte way to raise an exception.
Jonathan Frech

1

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


1

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

You were all saving an easy one for me.
ngm

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

1

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,...|A|], where |A| 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 ex. 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 pA,qC+;p<q¬(pq) over each pair p,q to obtain an array of all 0s 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 [A0,A0+A1,A0+A1+A2,...,A0+...+Ai]. We then generate Jelly's equivalent of J (indicies), by calculating the range B:=[1...|A|] where |A| 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,A0,A0+A12,A0+A1+A23,...,A0+...+Aii+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.


0

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

Post the port as yourself, it's a totally different approach!
Dave

0

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!


0

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.


0

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.


0

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!



0

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
       x       :Reduce by addition

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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.