Daily Programming Challange

Previously >>>NA
Write a function that takes an undefined number of integers and returns their Median.

Example:
med(2, 12, 19, 20)
returns 15.50
med(9, 10, 12, 12, 12)
returns 12

Other urls found in this thread:

alcula.com/calculators/statistics/median/
codegolf.stackexchange.com/a/58821
jsfiddle.net/z7hvtphk/
bbc.co.uk/bitesize/ks2/maths/data/mode_median_mean_range/read/1/
sourceware.org/git/?p=glibc.git;a=blob;f=stdio-common/printf_fp.c
twitter.com/AnonBabble

Additional information (I hope you don't need it)
source
alcula.com/calculators/statistics/median/

How short can you write a c++ fizzbuzz

Take it in as an array then add up the array with a for loop then return it divided by arr.length?

That's average/mean, not median. To get median you basically have to remove the largest and smallest items from the array until you're left with just one number in the middle. A simple pseudocode algorithm for it would look something like

function median(array) {
while(array.length() > 2) {
remove smallest item from array;
remove largest item from array;
}
if(array.length == 2) return(average of array's two elements);
if(array.length == 1) return(only element left in array);
}

I found out the secret to programming guys just look at a lot of programming exercises and code and eventually you will notice the same patterns made up of basically the same kinds of programs involving sorting storing data etc it's easy

def median *args
length = args.size
return nil if length.zero?

sorted = args.sort
ix = length / 2

if length.even? then ((sorted[ix] + sorted[ix-1]) / 2.0)
else sorted[ix]
end

Ruby sempai always delivers.

What are you waiting for, Sup Forums?

She's too dumb to be a dpt mascot.

package main

import "fmt"

func med(nums ...int) float64 {
n := len(nums)
if n%2 == 0 {
return (float64(nums[n/2]) + float64(nums[(n/2)-1])) / 2
} //else
return float64(nums[(n+1)/2])

}

func main() {
fmt.Println(med(2, 12, 19, 20))
fmt.Println(med(9, 10, 12, 12, 12))
}


user0@primary:~/testdir/go$ go run main.go
15.5
12


What happenned to Sup Forums?

Pseudo code.

def med(array):
if len(array) % 2 == 0:
return (array[len(array)/2 - 1] + array[len(array)/2]) / 2
else:
return array[round(len(array), 0)-1] // round() should take a decimal number and round it to the number of decimal places requested by the second parameter

import System.Environment

median n
| length n > 2 = median (tail (init n))
| length n == 2 = [(n!!0 + n!!1) / 2]
| length n == 1 = n

main = do
x read x :: Double)x


I did this senpai

What language is this? and where is your proof that it's working?

Python.
def median(*arg):
sum = 0
print("Count of numbers", len(arg), "; And numbers are:", arg)
for number in arg:
sum += number
median = sum / len(arg)
print("Median is: ", median)

median(4, 5, 8)

Rust:
fn median(list: &[i64]) -> Option {
if list.is_empty() { return None; }

let mut list = list.to_vec();
list.sort();

let i = list.len() / 2;

if list.len() % 2 == 0 {
Some((list[i] + list[i-1]) as f64 / 2.0)
} else {
Some(list[i] as f64)
}
}

Most solutions in this thread have the wrong output if the input isn't sorted, for example median(3, 2, 1, 0, 1, 2, 3) -> 2

python is quite popular in Sup Forums. But why are there so many python haters?

really makes me think

Haskell

Does it also work on unsorted input or empty lists?

Like in and

Why would you ever need to sort a list to find the median?

This challenge is too boring, as it doesn't allow for a wide variety of solutions.
Basically, all that's going to happen is "Sort the list/array, get the middle and possibly average".

How else would you do it?

see

Doesn't work on arbitrary input. That solution requires input to be sorted and not empty.

thanks, I forgot
it should now
import System.Environment
import Data.List

median n
| length n > 2 = median (tail (init n))
| length n == 2 = [(n!!0 + n!!1) / 2]
| length n == 1 = n
| length n == 0 = []

main = do
x read x :: Double)x)

(defun med (&rest numbers)
(/ (apply #'+ numbers)
(length numbers)))

Sup Sup Forumsentoomen we need a scheme in here.

#lang racket

(define (m ls)
(let loop ([sorted (sort ls

That's the mean, OP wanted the median.

Why think about it like this?
It's the middle value. For an unsorted array you need to sort it first or do what you do and do what's a double ended bubble sort effectively.
It's far easier to just call a sort (whatever sort) and then pick the middle value or average the two values in the middle.

Bonus: Generalized over the quantile:

fn median(list: &[i64]) -> Option {
quantile(list, 0.5)
}

fn quantile(list: &[i64], quantile: f64) -> Option {
if quantile < 0.0 || quantile > 1.0 || list.is_empty() {
return None;
}

let mut list = list.to_vec();
list.sort();

let i = (list.len() as f64 * quantile) as usize;

if list.len() % 2 == 0 {
Some((list[i] + list[i-1]) as f64 / 2.0)
} else {
Some(list[i] as f64)
}
}

def med(*nums):
s = sorted(nums)
h = len(nums) >> 1
if len(nums) & 1:
return s[h]
return (s[h]+s[h - 1]) /2

codegolf.stackexchange.com/a/58821

>len(nums) >> 1
That's silly.

git gud

int division by 2, also it can be len(nums) // 2 for python 3.

>h = len(nums) >> 1
> if len(nums) & 1:
is this python?

def med(*x):
return __import__("numpy").median(x)

>def med(*x):
passing by reference?

arbitrary argument list

JS anyone?
jsfiddle.net/z7hvtphk/

NO ONE IN THIS THREAD KNOWS THE DIFFERENCE BETWEEN MEAN AND MEDIAN

bbc.co.uk/bitesize/ks2/maths/data/mode_median_mean_range/read/1/

back to lower school you go

Get on my efficiency level.
template
double median(const std::vector& xs)
{
std::priority_queue ys; //max heap
std::priority_queue zs; //min heap

for (const T x : xs) {
if (ys.empty() && zs.empty()) {
ys.push(x);
} else {
if (x < ys.top()) {
ys.push(x);
} else {
zs.push(x);
}
}

if (::abs(ys.size()-zs.size()) > 1) {
if (ys.size() > zs.size()) {
T y = ys.top();
zs.push(y);
ys.pop();
} else {
T z = zs.top();
ys.push(z);
zs.pop();
}
}
}

double res;
// If odd length, return top element of larger heap
// Else average top elements
if (xs.size()%2 == 1) {
res = ys.size() > zs.size() ? ys.top() : zs.top();
} else {
res = 0.5*ys.top()+0.5*zs.top();
}
return res;
}

double median(int[] a)
{
if(a.length == 2) return cast(double) (a[0] + a[1]) / 2;
if(a.length == 1) return a[0];

return median(a[1..$-1]);
}

unittest
{
assert(median([2, 12, 19, 20]) == 15.50);
assert(median([9, 10, 12, 12, 12]) == 12);
}

Can we assume the input array is pre-sorted?

no

The input is not an array and you cannot assume that

Well shit.

just sort it, brah

>med(19, 18, 18, 20, 20)
> 20
Try again fag

def median(*args):
if len(args) == 0:
print("No arguments")
else:
try:
for a in args:
args = [int(a) for a in args]
except ValueError:
print("Non-Number Value Found")
return None
args.sort()
if len(args) % 2 == 0:
c = (len(args)/2)
return (args[int(c)] +args[int(c-1)])/2
else:
c, d = divmod(len(args),2)
return args[c]

print(median(2,12,19,20))
print(median(9,10,12,12,12))
--
>15.5
>12

hahaha what the fuck i'm doing

oh shit i just realized
for a in args:
args = [int(a) for a in args]
that for a in args: was not mean to be there

>typename = typename std::enable_if::type>
wow that's a lot of text to type every time, m8

in the name of "safety" sepples fags just fuck themselves in the ass more and more

def median(*args):
if not args:
raise ValueError("No arguments")
nums = sorted(list(args))
n = len(nums)
mid = n // 2
if n % 2 == 0:
return (nums[mid] + nums[mid + 1]) / 2
else:
return nums[mid]


or simply

from statistics import median

let med = (...a) => (a.sort()[Math.floor(a.length/2)]+a.sort()[Math.floor(a.length/2)-1+(a.length%2)])/2

> med(1,1,1,20,20,20,10)
10
> med(1,1,1,20,20,20,10,11)
10.5

This gives incorrect results if you provide a number of floats. int(a) will work perfectly fine here

>Thread is still alive
Sup Forums never ceased to surprise me.

Oh yeah, I forgot to sort the list beforehand. Here goes the revised solution. I posted that because I wanted to bump the thread. I should have revised
package main

import (
"fmt"
"sort"
)

func med(nums ...int) float64 {
sort.Ints(nums)
n := len(nums)
if n%2 == 0 {
return (float64(nums[n/2]) + float64(nums[(n/2)-1])) / 2
} //else
return float64(nums[(n+1)/2])

}

func main() {
fmt.Println(med(2, 12, 19, 20))
fmt.Println(med(9, 10, 12, 12, 12))
}

what does anime have to do with programming?

Why does it bother you?

Could you explain me why IDEs don't show line numbers by default?

What IDE is that?

who said it bothers me?

Eclipse, IDEA, IDLE, Visual Studio. Im not sure about NetBeans.

i was gonna write something in C with va_args and a pushdown stack but I said nah

my bad def median(*args):
args = list(args)
if len(args) == 0:
print("No arguments")
else:
try:
k = [int(a) for a in args]
except ValueError:
there it's fixed

org 0x100
use16

main:
finit

push 12
push 19
push 2
push 20
mov cx, 4
call find_median
shl cx, 1
add sp, cx
call print_st0

push 12
push 12
push 10
push 9
push 12
mov cx, 5
call find_median
shl cx, 1
add sp, cx
call print_st0

mov ax, 0x4c00
int 0x21

; print value in st(0)
; 2 decimal places
; not stripping zeroes because i'm lazy
print_st0:
push 100
mov si, sp
fimul word [si]
fistp word [si]
fwait
pop ax
mov bx, 10
push 0
push 0x0a
push 0x0d
xor cx, cx
cc: xor dx, dx
div bx
or dl, 0x30
push dx
inc cx
cmp cx, 2
jne @f
push 0x2e
@@: test ax, ax
jnz cc
mov ah, 2
@@: pop dx
test dx, dx
jz @f
int 0x21
jmp @b
@@: ret

1/2

; simplest in-place sorting thing I could come up with
; ds:si = array location
; cx = array length
sort_shit:
push cx
push si
shl cx, 1
mov di, si
add si, cx
sub si, 2
aa: xor bx, bx
mov ax, [di]
bb: cmp ax, [di+bx]
jbe @f
xchg ax, [di+bx]
mov [di], ax
@@: add bx, 2
cmp bx, cx
jne bb
add di, 2
sub cx, 2
cmp di, si
jne aa
pop si
pop cx
ret

; takes an array of words on stack
; cx = array length
; returns median in st(0)
find_median:
mov si, sp
add si, 2
call sort_shit
mov bx, cx
test cx, 1
jz @f
lea si, [si+bx-1]
fild word [si]
ret
@@: lea si, [si+bx-2]
fild word [si]
fiadd word [si+2]
push 2
mov si, sp
fild word [si]
fdivp
add sp, 2
ret

first time writing 8087 so I have no idea what I'm doing

Still trying to think of a normal way to turn an 80-bit float into ascii and print it. can't wrap my head around it and even google is clueless. anyone know how that's done?

sourceware.org/git/?p=glibc.git;a=blob;f=stdio-common/printf_fp.c

sheeeesh.
I don't think I even want to wrap my head around that.

Took me about 5 minutes + looking up what median is :^) + failproofing a median()

nice syntax highlight