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
Additional information (I hope you don't need it)
source
http://www.alcula.com/calculators/statistics/median/
How short can you write a c++ fizzbuzz
>>58894045
Take it in as an array then add up the array with a for loop then return it divided by arr.length?
>>58894140
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 likefunction 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
>>58894529
Ruby sempai always delivers.
What are you waiting for, /g/?
>>58894045
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 /g/?
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 <- getArgs
print $ median $ map (\x -> read x :: Double)x
I did this senpai
>>58895909
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)
>>58894045
Rust:fn median(list: &[i64]) -> Option<f64> {
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 /g/. But why are there so many python haters?
really makes me think
>>58895950
Haskell
>>58896175
Does it also work on unsorted input or empty lists?
Like in >>58894529 and >>58896101
Why would you ever need to sort a list to find the median?
>>58894045
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".
>>58896191
How else would you do it?
>>58896252
Doesn't work on arbitrary input. That solution requires input to be sorted and not empty.
>>58896183
thanks, I forgot
it should nowimport 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 <- getArgs
print $ median $ sort ( map (\x -> read x :: Double)x)
(defun med (&rest numbers)
(/ (apply #'+ numbers)
(length numbers)))
>>58894045
Sup /g/entoomen we need a scheme in here.#lang racket
(define (m ls)
(let loop ([sorted (sort ls <)])
(match sorted
[(list a) a]
[(list a b) (/ (+ a b) 2)]
[(list-rest a) (loop (drop-right (drop a 1) 1))])))
(module+ test
(require rackunit)
(for ([t '(((2 12 19 20) 15.5)
((9 10 12 12 12) 12)
((5 1 2 3 6 8 9 10 4 7) 5.5))])
(check-true (= (m (car t)) (cadr t)) (~a t))))
>>58896308
That's the mean, OP wanted the median.
>>58894233
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<f64> {
quantile(list, 0.5)
}
fn quantile(list: &[i64], quantile: f64) -> Option<f64> {
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
>>58894131
http://codegolf.stackexchange.com/a/58821
>>58899276
>len(nums) >> 1
That's silly.
>>58896101
git gud
>>58899575
int division by 2, also it can be len(nums) // 2 for python 3.
>>58899276
>h = len(nums) >> 1
> if len(nums) & 1:
is this python?
>>58894045def med(*x):
return __import__("numpy").median(x)
>>58900453
>def med(*x):
passing by reference?
>>58900702
arbitrary argument list
>>58894045
JS anyone?
https://jsfiddle.net/z7hvtphk/
NO ONE IN THIS THREAD KNOWS THE DIFFERENCE BETWEEN MEAN AND MEDIAN
>>58901115
http://www.bbc.co.uk/bitesize/ks2/maths/data/mode_median_mean_range/read/1/
back to lower school you go
>>58894045
Get on my efficiency level.template <typename T,
typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type>
double median(const std::vector<T>& xs)
{
std::priority_queue<T,std::vector<T> > ys; //max heap
std::priority_queue<T,std::vector<T>,std::greater<T> > 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);
}
>>58894045
Can we assume the input array is pre-sorted?
>>58901891
The input is not an array and you cannot assume that
>>58901921
>>58901913
Well shit.
>>58901960
just sort it, brah
>>58895404
>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
>>58902119
oh shit i just realizedfor a in args:
args = [int(a) for a in args]
thatfor a in args:was not mean to be there
>>58901611
>typename = typename std::enable_if<std::is_arithmetic<T>::value,T>::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 simplyfrom 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
>>58902119
This gives incorrect results if you provide a number of floats. int(a) will work perfectly fine here
>Thread is still alive
/g/ never ceased to surprise me.
>>58896270
>>58901990
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 revisedpackage 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))
}
>>58894045
>>58894070
>>58894620
>>58895404
>>58895909
>>58895950
>>58896469
what does anime have to do with programming?
>>58903115
Why does it bother you?
>>58894045
Could you explain me why IDEs don't show line numbers by default?
>>58903210
What IDE is that?
>>58903123
who said it bothers me?
>>58903261
Eclipse, IDEA, IDLE, Visual Studio. Im not sure about NetBeans.
>>58894045
i was gonna write something in C with va_args and a pushdown stack but I said nah
>>58902259
my baddef 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
>>58903653; 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
>>58903653
>>58903681
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?
>>58904377
http://sourceware.org/git/?p=glibc.git;a=blob;f=stdio-common/printf_fp.c
>>58904435
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() <- no input;; Language: Common Lisp
(defun median (&rest numbers)
;; base error case:
(when (null numbers)
(warn "No numbers provided.")
(return-from median nil))
;; here we go
(let* ((sorted-numbers
(sort numbers #'<))
(length (length sorted-numbers)))
(if (evenp length)
;; average of the center two index numbers
(/ (+ (elt sorted-numbers (1- (/ length 2))) ; of-by-one meme
(elt sorted-numbers (/ length 2)))
2.0)
(elt sorted-numbers (ceiling length 2)))))
>>58906276
nice syntax highlight