Averages/Median: Difference between revisions

(Initial FutureBasic task solution added)
 
(8 intermediate revisions by 7 users not shown)
Line 815:
>: 48870
=: 0
</pre>
 
=={{header|Amazing Hopper}}==
{{trans|BaCon}}<syntaxhighlight lang="c">
#include <basico.h>
 
#proto cálculodemediana(_X_)
#synon _cálculodemediana obtenermedianade
 
algoritmo
 
decimales '2'
matrices 'a,b'
'4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2', enlistar en 'a'
'4.1, 7.2, 1.7, 9.3, 4.4, 3.2', enlistar en 'b'
arr.ordenar 'a'
arr.ordenar 'b'
"A=",a,NL,"Median: ", obtener mediana de 'a', NL
"B=",b,NL,"Median: ", obtener mediana de 'b', NL
finalmente imprime
 
terminar
 
subrutinas
 
cálculo de mediana (x)
 
dx=0
filas de 'x' ---copiar en 'dx'---
calcular si ( es par?, #( (x[ (dx/2) ]+x[ (dx/2)+1 ])/2 ),\
#( x[ dx/2+1 ] ) )
retornar
</syntaxhighlight>
{{out}}
<pre>
A=1.70,3.20,4.10,4.40,5.60,7.20,9.30
Median: 4.40
B=1.70,3.20,4.10,4.40,7.20,9.30
Median: 4.25
 
</pre>
 
Line 1,888 ⟶ 1,929:
=={{header|Bracmat}}==
 
Each number is packaged in a little structure and these structures are accumulated in a sum. Bracmat keeps sums sorted, so the median is the term in the middle of the list, or the average of the two terms in the middle of the list. Notice that the input is converted to Bracmat's internal number representation, rational numbers, before being sorted. The output is converted back to 'double' variables. That last conversion is lossy.
Bracmat has no floating point numbers, so we have to parse floating point numbers as strings and convert them to rational numbers.
Each number is packaged in a little list and these lists are accumulated in a sum. Bracmat keeps sums sorted, so the median is the term in the middle of the list, or the average of the two terms in the middle of the list.
 
<syntaxhighlight lang="bracmat">( ( median=
= begin decimals end int list
begin decimals end int list med med1 med2 num number
, med med1 med2 num number
. 0:?list
. ( convertToRational
& whl
' ( @( !arg =
: . new$(UFP,'(.$arg:?V))
((%@:~" ":~",") ?:?number)ufp
& ((" "|",") ?arg|:?argufp..go)$
& (ufp..export)$(Q.V)
& @( !number)
& 0:?list
: ( #?int "." [?begin #?decimals [?end
& whl
& !int+!decimals*10^(!begin+-1*!end):?num
' ( |!arg:%?number ?numarg
& )convertToRational$!number:?rationalnumber
& (!rationalnumber.)+!list:?list
& (!num. )+!list:?list
& !list:?+[?end
& ( !end*1/2:~/
& !list
: ?
+ [!(=1/2*!end+-1)
+ (?med1.?)
+ (?med2.?)
+ ?
& !med1*1/2+!med2*1/2:?med
| !list:?+[(div$(1/2*!end,1))+(?med.)+?
)
& (new$(UFP,'(.$med)).go)$
)
& out$(median$("4.1" 4 "1.2" "6.235" "7868.33"))
& out
$ ( median
$ ( "4.4"
"2.3"
"-1.7"
"7.5"
"6.6"
"0.0"
"1.9"
"8.2"
"9.3"
"4.5"
)
& !list:?+[?end
& ( !end*1/2:~/
& !list:?+[!(=1/2*!end+-1)+(?med1.)+(?med2.)+?
& !med1*1/2+!med2*1/2:?med
| !list:?+[(div$(1/2*!end,1))+(?med.)+?
)
& out$(median$(1 5 3 2 4))
& !med
& out$(median$(1 5 3 6 4 2))
);</syntaxhighlight>
 
Output:
<pre>4.0999999999999996E+00
<pre> median$" 4.1 4 1.2 6.235 7868.33"
4.4500000000000002E+00
41/10
3.0000000000000000E+00
 
3.5000000000000000E+00</pre>
median$"4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5"
89/20
 
median$"1, 5, 3, 2, 4"
3
 
median$"1, 5, 3, 6, 4, 2"
7/2</pre>
 
=={{header|C}}==
Line 2,053 ⟶ 2,109:
 
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|10+}}
<syntaxhighlight lang="csharp">using System;
<syntaxhighlight lang="csharp">
using System.Linq;
double median(double[] arr)
 
namespace Test
{
var sorted = arr.OrderBy(x => x).ToList();
class Program
var mid = arr.Length / 2;
{
return arr.Length % 2 == 0
static void Main()
? (sorted[mid] + sorted[mid-1]) / 2
{
: sorted[mid];
double[] myArr = new double[] { 1, 5, 3, 6, 4, 2 };
}
 
var write = (double[] x) =>
myArr = myArr.OrderBy(i => i).ToArray();
Console.WriteLine($"[{string.Join(", ", x)}]: {median(x)}");
// or Array.Sort(myArr) for in-place sort
write(new double[] { 1, 5, 3, 6, 4, 2 }); //even
 
write(new double[] { 1, 5, 3, 6, 4, 2, 7 }); //odd
int mid = myArr.Length / 2;
write(new double[] { 5 }); //single
double median;
 
if (myArr.Length % 2 == 0)
{
//we know its even
median = (myArr[mid] + myArr[mid - 1]) / 2.0;
}
else
{
//we know its odd
median = myArr[mid];
}
 
Console.WriteLine(median);
Console.ReadLine();
}
}
}
</syntaxhighlight>
{{output}}
<pre>
[1, 5, 3, 6, 4, 2]: 3.5
[1, 5, 3, 6, 4, 2, 7]: 4
[5]: 5
</pre>
 
=={{header|C++}}==
Line 2,485 ⟶ 2,530:
<syntaxhighlight lang="text">
proc quickselect k . list[] res .
#
subr partition
mid = left
for i = left + 1 to right
if list[i] < list[left]
mid += 1
swap list[i] list[mid]
.
.
swap list[left] list[mid]
.
.
swap list[left] list[mid]
left = 1
.
left right = 1len list[]
while left < right
right = len list[]
partition
while left < right
call partition if mid < k
if left = mid <+ k1
left =elif mid +> 1k
elif right = mid >- k1
right = mid - 1else
left = right
else
left = right.
.
res = list[k]
.
res = list[k]
.
proc median . list[] res .
h = len list[] div 2 + 1
call quickselect h list[] res
if len list[] mod 2 = 0
call quickselect h - 1 list[] h
res = (res + h) / 2
.
.
test[] = [ 4.1 5.6 7.2 1.7 9.3 4.4 3.2 ]
call median test[] med
print med
test[] = [ 4.1 7.2 1.7 9.3 4.4 3.2 ]
call median test[] med
print med
</syntaxhighlight>
Line 2,551 ⟶ 2,596:
 
=={{header|Elena}}==
ELENA 56.0x :
<syntaxhighlight lang="elena">import system'routines;
import system'math;
Line 2,570 ⟶ 2,615:
{
var middleIndex := len / 2;
if (len.mod:(2) == 0)
{
^ (sorted[middleIndex - 1] + sorted[middleIndex]) / 2
Line 5,194 ⟶ 5,239:
calcmedian x
display r(p50)</syntaxhighlight>
=={{header|Swift}}==
===A full implementation===
<syntaxhighlight lang="swift">
// Utility to aid easy type conversion
extension Double {
init(withNum v: any Numeric) {
switch v {
case let ii as any BinaryInteger: self.init(ii)
case let ff as any BinaryFloatingPoint: self.init(ff)
default: self.init()
}
}
}
 
extension Array where Element: Numeric & Comparable {
// Helper func for random element in range
func randomElement(within: Range<Int>) -> Element {
return self[.random(in: within)]
}
 
mutating func median() -> Double? {
switch self.count {
case 0: return nil
case 1: return Double(withNum: self[0])
case 2: return self.reduce(0, {sum,this in sum + Double(withNum: this)/2.0})
default: break
}
let pTarget: Int = self.count / 2 + 1
let resultSetLen: Int = self.count.isMultiple(of: 2) ? 2 : 1
func divideAndConquer(bottom: Int, top: Int, goal: Int) -> Int {
var (lower,upper) = (bottom,top)
while true {
let splitVal = self.randomElement(within: lower..<upper)
let partitionIndex = self.partition(subrange: lower..<upper, by: {$0 > splitVal})
switch partitionIndex {
case goal: return partitionIndex
case ..<goal: lower = partitionIndex
default: upper = partitionIndex
}
}
}
// Split just above the 'median point'
var pIndex = divideAndConquer(bottom: 0, top: self.count, goal: pTarget)
// Shove the highest 'low' values into the result slice
pIndex = divideAndConquer(bottom: 0, top: pIndex, goal: pIndex - resultSetLen)
// Average the contents of the result slice
return self[pIndex..<pIndex + resultSetLen]
.reduce(0.0, {sum,this in sum + Double(withNum: this)/Double(withNum: resultSetLen)})
}
}
</syntaxhighlight>
Usage:
<syntaxhighlight lang="swift">
var c: [Double] = (0...100).map {_ in Double.random(in: 0...100)}
print(c.median())
 
</syntaxhighlight>
 
=={{header|Tcl}}==
Line 5,346 ⟶ 5,448:
{{libheader|Wren-math}}
{{libheader|Wren-queue}}
<syntaxhighlight lang="ecmascriptwren">import "./sort" for Sort, Find
import "./math" for Nums
import "./queue" for PriorityQueue
 
var lists = [
5

edits