Skip to content

Instantly share code, notes, and snippets.

@sirupsen
Created August 22, 2009 20:45
Show Gist options
  • Save sirupsen/172979 to your computer and use it in GitHub Desktop.
Save sirupsen/172979 to your computer and use it in GitHub Desktop.
Which language is best at taking all the integer paraments and get the average? Look for yourself!
def average(*numbers)
((numbers.inject {|sum, element| sum + element}) / numbers.length).to_f
end
#include <stdarg.h>
double average(int count, ...)
{
va_list ap;
int j;
double tot = 0;
va_start(ap, count);
for(j=0; j<count; j++)
tot+=va_arg(ap, double);
va_end(ap);
return tot/count;
}
double Avg(params double[] a)
{
return a.Sum() / a.Length;
}
function average(){
numbers=average.arguments;
sum=0;
for(var i=0; i<numbers.length; i++){
sum+=numbers[i]
};
return sum/numbers.length;
}
public static double average(int... numbers) {
// Needs Java 1.5
double count = 0;
double sum = 0;
for(int num: numbers) {
count++;
sum += num;
}
return sum / count;
}
(defun average (&rest numbers)
(/ (apply #'+ numbers)(length numbers)))
function average (...)
sum = 0
for _,n in ipairs({...}) do sum = sum + n end
return sum / #{...}
end
# Perl
sub Average
{
return sum(@_)/scalar(@_);
}
# ASM x86
average:
pop cl
mov ax, 0
mov ch, cl
.addnext:
cmp cl, 0
je .div
pop bx
add ax, bx
dec cl
jmp .addnext
.div:
div ax, ch
push ax
ret
<?php
function average() {
return floatval(array_sum(func_get_args())/func_num_args());
}
def average(*numbers):
return float(sum(numbers))/len(numbers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment