Apakah saya array golf?


18

Definisi dan Aturan

Sebuah Array Golfy adalah sebuah array bilangan bulat, di mana setiap elemen adalah lebih besar atau sama dengan mean aritmetik dari semua elemen sebelumnya. Tugas Anda adalah menentukan apakah array bilangan bulat positif yang diberikan sebagai input golf atau tidak.

Uji Kasus & Contoh

Misalnya array berikut:

[1, 4, 3, 8, 6]

Adalah array golf, karena setiap istilah lebih tinggi dari rata-rata aritmatika dari mereka yang mendahuluinya. Mari kita selesaikan langkah demi langkah:

Nomor -> Elemen sebelumnya -> Rata-rata -> Mengikuti aturan?

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

Semua elemen menghormati kondisi ini, jadi ini adalah array golf. Perhatikan bahwa untuk tujuan tantangan ini, kami akan menganggap bahwa rata-rata daftar kosong ( []) adalah 0.

Lebih banyak kasus uji:

Input -> Output

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

Perhatikan bahwa ini adalah Puzzle 1 dari CodeGolf-Hackathon dan juga diposting di Anarchy Golf (yang rusak) - Diposting ulang oleh histokrat , tetapi saya adalah penulis asli di kedua situs, dan dengan demikian diizinkan untuk memposting ulang di sini.


Apakah input selalu daftar bilangan bulat positif?
Kelly Lowder

@KellyLowder Ya.
Tn. Xcoder

Ini masalah yang menyenangkan, saya berpikir untuk membuat ulang di Anarchy Golf dengan lebih banyak test case tetapi saya pikir Anda mungkin bisa mengatasinya.
histokrat

@ histokrat Silakan maju dan memposting ulang di Anarchy Golf, saya seharusnya memikirkan hal-hal yang bisa dieksploitasi terlebih dahulu. Saya senang Anda menganggapnya menarik (Btw tolong ping saya di sini dan berikan tautan jika Anda mengirim ulangnya).
Tn. Xcoder

3
@streetster Itu setara. Jumlah / i> x sama dengan Jumlah> xi sama dengan Jumlah + x> x (i + 1) sama dengan (Jumlah + x) / (i + 1)> x.
histokrat

Jawaban:


13

Python 2 , 37 byte

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

Cobalah online!

Output melalui kode keluar: crash (kode keluar 1) untuk array golf, hanya keluar dengan kode keluar 0 untuk array non-golf. ovs dan Jonathan Frech menyimpan 3 byte.

Python 2 , 44 byte

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

Cobalah online!

Varian yang lebih tradisional, yang kembali Trueuntuk array golf, selain itu False. Jonathan Frech menyimpan 2 byte.


1
Saya pikir a==[]orbisa a and.
Jonathan Frech

2
Itu sebenarnya pintar - itu keluar sum(a)<=len(a)*a.pop()*[]untuk kasus dasar, yang selalu benar int < list!
Lynn

3
39 byte sebagai fungsi yang macet untuk input yang benar.
Ovs

1
@ovs 37 byte menggunakan fungsi imperatif.
Jonathan Frech

11

Jelly , 6 5 byte

<ÆmƤE

Cobalah online!

Bagaimana itu bekerja

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

6-byter (alternatif) ÆmƤµ⁼Ṣ
cairdcoinheringaahing

@ Mr.Xcoder Bercabang Golf!
Dennis

Wow itu brilian :-)
Tn. Xcoder

5

JavaScript (ES6), 33 32 byte

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

Kode juga berfungsi pada nilai negatif seperti [-3, -2]. Pengembalian falseuntuk array golf, trueuntuk array lainnya. Sunting: Disimpan 1 byte berkat @JustinMariner.


1
Anda dapat menjatuhkan !karena spec hanya meminta dua nilai yang berbeda, jadi kembali falseketika array golf itu baik-baik saja.
Justin Mariner


4

MATL , 9 8 byte

tYstf/<a

Output 0untuk array golf, 1jika tidak.

Cobalah online!

Penjelasan

Pertimbangkan 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

4

Haskell , 53 50 48 byte

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

Cobalah online!

Edit: -3 byte terima kasih kepada Zgarb!

Penjelasan

Versi bebas poin di atas setara dengan program berikut:

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

Diberi masukan s=[1,4,3,8,6], scanl1(+)smenghitung jumlah awalan [1,5,8,16,22]dan zipWith(*)[1..](tail s)tetes elemen pertama dan mengalikan semua elemen lain dengan indeks mereka: [4,6,24,24]. Daftar sekarang Golfy jika berpasangan dengan jumlah awalan lebih kecil atau sama dengan indeks elemen kali, yang dapat diperiksa dengan zipping kedua daftar dengan (<=)dan memeriksa bahwa semua hasil adalah Truedengan and.


1
Anda dapat menghindari kesalahan ketik seperti ini .
Zgarb

@ Zgarb Kalau dipikir-pikir ini adalah solusi yang jelas. Terima kasih telah menunjukkan!
Laikoni

3

C # (Visual C # Compiler) , 71 + 18 = 89 byte

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

tambahan 18 byte untuk using System.Linq;

Cobalah online!


2
Selamat datang di situs ini! :)
DJMcMayhem

Secara umum, pernyataan impor tidak dianggap gratis dalam kode golf. Karena ini memerlukan pernyataan using System.Linq;itu sebenarnya akan menjadi 89 byte, kadang-kadang dinyatakan sebagai "71 + 18 = 89" untuk menunjukkan bahwa 18 byte diperlukan tetapi bukan bagian dari solusi sementara masih memiliki hitungan akhir menjadi angka terakhir di baris judul ( yang bermanfaat untuk beberapa parser otomatis).
Kamil Drakari

3

APL (Dyalog) , 10 byte

Ini adalah fungsi awalan diam-diam anonim (disebut kereta monadik dalam istilah APL).

∧/⊢≥+⍳∘≢

Coba semua test case di TIO!

Apakah itu

∧/ itu benar

 elemen-elemen

 lebih besar atau sama dengan

+\ jumlah kumulatif

÷ dibagi dengan

   bilangan bulat 1 sampai

   itu

   sejumlah elemen

?


APL memiliki simbol untuk "itu" ??
user2390246

1
@ user2390246 mengikat bersama hal-hal dengan cara yang sama "the" mengikat bersama dalam "menghitung kucing". Ini benar-benar disebut Tulis .
Adám

3

C (gcc) , 62 60 62 byte

  • Menghapus dua tanda kurung berlebihan.
  • Menambahkan dua byte untuk memperbaiki usabilitas fungsi ( b=).
f(A,S,k,b)int*A;{for(S=k=b=0;*A;S+=*A++)b+=!(S<=*A*k++);b=!b;}

Cobalah online!


3

05AB1E , 5 byte

ηÅA÷W

Cobalah online!

Bantuan luas dari Dennis dan Adnan sampai ke versi yang dikurangi ini. Juga bug telah diperbaiki untuk memungkinkan ini, terima kasih sekali lagi kawan. Saya menerima sedikit pujian untuk jawaban ini.


05AB1E , 10 byte

ηεÅA}ü.S_P

Cobalah online!


Lama karena DgsO/ setara dengan "rata-rata" di 05AB1E.

Rupanya ÅAberarti aritmatika.


Untuk menghitung cara, saya akan menggunakan +\÷J(bagi jumlah kumulatif dengan indeks) di Jelly. Bukankah itu mudah di 05AB1E? Sunting: Nevermind.
Dennis

@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.
Magic Octopus Urn

.S_ is a LONG way to go for <=, if anyone has any ideas lmk.
Magic Octopus Urn

Would ÷W work instead of ü.S_P?
Dennis

1
Oh, @Adnan just fixed the vectorization of ÅA, so ηÅA÷W works now.
Dennis

2

APL (Dyalog), 15 bytes

∧/⊢≥((+/÷≢)¨,\)

Try it online!

How?

            ,\  all prefixes
           ¨    for each
      +/÷≢      calculate arithmetic mean
  ⊢≥            element wise comparison
∧/              logically and the result

2

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.




2

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!



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
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.