Averages/Median: Difference between revisions
→{{header|C sharp|C#}}
(Initial FutureBasic task solution added) |
RandomTask (talk | contribs) |
||
(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.
<syntaxhighlight lang="bracmat">( ( median
= begin decimals end int list
, med med1 med2 num number
. ( convertToRational
& (
& (ufp..export)$(Q.V)
& 0:?list
& whl
' (
&
& (!rationalnumber.)+!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"
)
)
& out$(median$(1 5 3 2 4))
& out$(median$(1 5 3 6 4 2))
);</syntaxhighlight>
Output:
<pre>4.0999999999999996E+00
4.4500000000000002E+00
3.0000000000000000E+00
3.5000000000000000E+00</pre>
=={{header|C}}==
Line 2,053 ⟶ 2,109:
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|10+}}
<syntaxhighlight lang="csharp">
double median(double[] arr)
{
var sorted = arr.OrderBy(x => x).ToList();
var mid = arr.Length / 2;
return arr.Length % 2 == 0
? (sorted[mid] + sorted[mid-1]) / 2
: sorted[mid];
}
var write = (double[] x) =>
Console.WriteLine($"[{string.Join(", ", x)}]: {median(x)}");
write(new double[] { 1, 5, 3, 6, 4, 2 }); //even
write(new double[] { 1, 5, 3, 6, 4, 2, 7 }); //odd
write(new double[] { 5 }); //single
</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]
.
left = 1
while left < right
partition
left = right
res = list[k]
.
proc median . list[] res .
h = len list[] div 2 + 1
if len list[] mod 2 = 0
res = (res + h) / 2
.
.
test[] = [ 4.1 5.6 7.2 1.7 9.3 4.4 3.2 ]
print med
test[] = [ 4.1 7.2 1.7 9.3 4.4 3.2 ]
print med
</syntaxhighlight>
Line 2,551 ⟶ 2,596:
=={{header|Elena}}==
ELENA
<syntaxhighlight lang="elena">import system'routines;
import system'math;
Line 2,570 ⟶ 2,615:
{
var middleIndex := len / 2;
if (len.mod
{
^ (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="
import "./math" for Nums
import "./queue" for PriorityQueue
var lists = [
|