Tantangan
Diberi daftar nomor kosong yang kosong, hitung mediannya.
Definisi
Median dihitung sebagai berikut: Pertama urutkan daftar,
- jika jumlah entri ganjil , median adalah nilai di tengah daftar yang diurutkan,
- jika tidak median adalah rata-rata aritmatika dari dua nilai yang paling dekat dengan pusat daftar yang diurutkan.
Contohnya
[1,2,3,4,5,6,7,8,9] -> 5
[1,4,3,2] -> 2.5
[1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,-5,100000,1.3,1.4] -> 1.5
[1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,1.5,-5,100000,1.3,1.4] -> 1.5
code-golf
statistics
cacat
sumber
sumber
7/2
atau8/2
)Jawaban:
Python 2 , 48 byte
Fungsi tanpa nama yang mengembalikan hasilnya. -1 byte terima kasih kepada xnor.
Langkah pertama jelas untuk mengurutkan array, menggunakan
l.sort()
. Namun, kami hanya dapat memiliki satu pernyataan dalam lambda, jadi kami memanfaatkan fakta bahwa fungsi sortir kembaliNone
dengan menambahkanor
- sepertiNone
falsy dalam Python, ini memberitahu untuk mengevaluasi dan mengembalikan bagian selanjutnya dari pernyataan.Sekarang kita memiliki daftar yang diurutkan, kita perlu menemukan nilai tengah, atau tengah.
Menggunakan persyaratan untuk memeriksa paritas panjang akan terlalu bertele-tele, jadi alih-alih kita mendapatkan indeks
len(l)/2
dan~len(l)/2
:Jika daftar panjangnya aneh, indeks ini akan menunjuk ke nilai yang sama. Jika panjangnya genap, maka mereka akan menunjuk ke dua item pusat.
Sekarang kita memiliki dua indeks ini, kita menemukan nilai-nilai ini dalam daftar, menjumlahkannya, dan membaginya dengan 2. Tempat desimal tertinggal di
/2.
memastikan bahwa itu adalah divisi float daripada divisi integer.Hasilnya dikembalikan secara implisit, karena ini adalah fungsi lambda.
Cobalah online!
sumber
lambda l:l.sort()or(l[len(l)/2]+l[~len(l)/2])/2.
f=
, thinking it was 1 byte longer.Python3 -
3130 bytesSaved a byte thanks to @Dennis!
I wasn't planning on a builtin answer, but I found this module and thought it was really cool cuz I had no idea it existed.
Try it online here.
sumber
from statistics import*;median
saves a byte.__import__
, butimport math;math.log
would beatfrom math import*;log
.Actually, 1 byte
Try it online!
sumber
Jelly, 9 bytes
Try it online!
Explanation
I'm still getting the hang of Jelly... I wasn't able to find built-ins for either the median or the mean of a list, but it's very convenient for this challenge that Jelly allows non-integer indices into lists, in which case it will return a pair of the two closest values. That means we can work with half the input length as an index, and get a pair of values when we need to average it.
sumber
Æṁ
will work nowBrain-Flak, 914 + 1 = 915 bytes
Requires the
-A
flag to run.Try it online!
Explanation
The backbone of this algorithm is a bubble sort I wrote a while ago.
I don't remember how this works so don't ask me. But I do know it sorts the stack and even works for negatives
After everything has been sorted I find 2 times the median with the following chunk
Now all that is left is to make convert to ASCII
sumber
R, 6 bytes
Not surprising that R, a statistical programming language, has this built-in.
sumber
R
beating Jelly :D:D:DMATL, 4 bytes
This finds the 0.5-quantile, which is the median.
Try it online!
sumber
i
that you suggested to make implicit? :-PPyth - 11 bytes
Finds the average of the middle item taken both backwards and forwards.
Test Suite.
sumber
Octave, 38 bytes
This defines an anonymous function. Input is a row vector.
Try it online!
Explanation
sumber
bsxfun
" andmean
:-)JavaScript,
5752 bytesSort the array numerically. If the array is an even length, find the 2 middle numbers and average them. If the array is odd, find the middle number twice and divide by 2.
sumber
Array.sort()
doesn't work properly with decimalssort()
directly and getting rid of thet
variable:v=>(v.sort((a,b)=>a-b)[(x=v.length)>>1]+v[--x>>1])/2
x>=2**31
, this would fail.>>
is a sign-propagating right shift, meaning that when the number is interpreted as a 32 bit integer, if the msb is set, then it stays set, making the result negative for2**32>x>=2**31
. Forx>=2**32
, it just yields0
.Matlab/Octave, 6 bytes
A boring built-in:
Try it online!
sumber
@median
?Mathematica, 6 bytes
As soon as I figure out Mthmtca, I'm posting a solution in it.
sumber
CBC8
(ËÈ
). However, until I apply another patch, the notion of function-calling might not meet PPCG's standards.Perl 6, 31 bytes
Try it
Expanded:
sumber
APL (Dyalog Unicode), 14 bytes
Try it online!
This is a train. The original dfn was
{(2+/2/⍵[⍋⍵])[≢⍵]÷2}
.The train is structured as follows
⊢
denotes the right argument.⌷
index⊂∘⍋
the indices which indexed into⊢
results in⊢
being sorted÷∘2
into⊢
divided by 22/
replicate this twice, so1 5 7 8
becomes1 1 5 5 7 7 8 8
2+/
take the pairwise sum, this becomes(1+1)(1+5)(5+5)(5+7)(7+7)(7+8)(8+8)
⊃
from this pick≢
element with index equal to the length of⊢
Previous solutions
sumber
Common Lisp, 89
I compute the mean of elements at position
(floor middle)
and(ceiling middle)
, wheremiddle
is the zero-based index for the middle element of the sorted list. It is possible formiddle
to be a whole number, like1
for an input list of size 3 such as(10 20 30)
, or a fraction for lists with an even numbers of elements, like3/2
for(10 20 30 40)
. In both cases, we compute the expected median value.sumber
Vim, 62 bytes
I originally did this in V using only text manipulation until the end, but got frustrated with handling [X] and [X,Y], so here's the easy version. They're about the same length.
Try it online!
Unprintables:
Honorable mention:
^O
takes you out of insert mode for one command (the let command).^R"
inserts the text that was yanked (in this case the list)sumber
TI-Basic, 2 bytes
Very straightforward.
sumber
Ans
is not an allowed I/O method.C#, 126 bytes
Pretty straightforward, here with LINQ to order the values, skip half the list, take one or two values depending on even/odd and average them.
sumber
using System.Linq;
into your byte count, however you can cancel this out by making some changes. Compile to aFunc<float[], float>
and assign the value of the modulo to a variable for 106 bytes:using System.Linq;a=>{int x=a.Length,m=x%2<1?1:0;return a.OrderBy(g=>g).Skip(x/2-m).Take(++m).Average();};
C++ 112 Bytes
Thanks to @original.legin for helping me save bytes.
Usage:
sumber
float
instead ofdouble
to save two bytes. Also, on GCC, you can use#import<vector>
and#import<algorithm>
instead of#include
. (Note that you don't need the space after either the#include
or#import
)J,
1614 bytesTry it online!
In addition to BMO's array duplication trick, I found that we can add the whole array sorted in two directions. Then I realized that the two steps can be reversed, i.e. add the two arrays, then duplicate them and take the
n
th element.How it works
Previous answers
J with
stats
addon, 18 bytesTry it online!
Library function FTW.
median
's implementation looks like this:J, 31 bytes
Try it online!
How it works
A bit of golfing gives this:
J, 28 bytes
Try it online!
sumber
#{0,2+/\2#-:/:]
at a close 15 bytes (man I miss⎕io
).J, 19 bytes
Explanation:
sumber
~
directly to each<.@-:@#{/:~-:@+\:~
JavaScript, 273 Bytes
sumber
Java 7, 99 bytes
Golfed:
Ungolfed:
Try it online
sumber
java.util.Arrays
?Pari/GP - 37
39BytesLet a be a rowvector containing the values.
Since Pari/GP is interactive, no additional command is needed to display the result.
For the "try-it-online" link a line before and after is added. To get printed, the median-result in stored in variable w
Try it online!
sumber
Japt, 20 bytes
Test it online! Japt really lacks any built-ins necessary to create a really short answer for this challenge...
Explanation
sumber
Java 8, 71 bytes
Parity is fun! Here's a lambda from
double[]
toDouble
.Nothing too complex going on here. The array gets sorted, and then I take the mean of two numbers from the array. There are two cases:
s
ands-1
both divide to the index of the middle element. The number is added to itself and the result divided by two, yielding the original value.Try It Online
sumber
SmileBASIC, 45 bytes
Gets the average of the elements at floor(length/2) and floor(length/2-0.5) Very simple, but I was able to save 1 byte by moving things around:
sumber
Husk, 10 bytes
Try it online!
Explanation
This function uses that the median of[a1…aN] is the same as the median of [a1a1…aNaN] which avoids the ugly distinction of odd-/even-length lists.
Unfortunately
½
for lists has the type[a] -> [[a]]
and not[a] -> ([a],[a])
which doesn't allowF~+→←
sincefoldl1
needs a function of typea -> a -> a
as first argument, forcing me to usee
.sumber
R without using the
median
builtin, 51 bytesTry it online!
sumber
function(x)mean(x,.5)
GolfScript,
27252017 bytesTakes input as an array of integers on stdin. Outputs as an unreduced fraction. Try it online!
Explanation
The median of the array, as BMO's Husk answer explains, is equal to the median of an array twice as long where each element is repeated twice. So we concatenate the array to itself, sort, and take the mean of the middle two elements. If the length of the original array isl , the middle two elements of the doubled array are at indices l−1 and l .
The output will be something like
10/2
.sumber