: f+! ( f addr -- ) dup [email protected] f+ f! ;
: ,f0s ( n -- ) falign 0 do 0e f, loop ;

: period @ ;
: used cell+ ;
: head 2 cells + ;
: sum  3 cells + faligned ;
: ring ( addr -- faddr )
  dup sum float+ swap head @ floats + ;

: update ( fvalue addr -- addr )
       dup ring [email protected] fnegate dup sum f+!
  fdup dup ring f!         dup sum f+!
  dup head @ 1+  over period mod  over head ! ;

: moving-average
  create ( period -- ) dup , 0 , 0 , 1+ ,f0s
  does>  ( fvalue -- avg )
    update
    dup used @ over period < if 1 over used +! then
    dup sum [email protected] used @ 0 d>f f/ ;

3 moving-average sma
1e sma f.  \ 1.
2e sma f.  \ 1.5
3e sma f.  \ 2.
4e sma f.  \ 3.


program Movavg
  implicit none

  integer :: i

  write (*, "(a)") "SIMPLE MOVING AVERAGE: PERIOD = 3"

  do i = 1, 5
    write (*, "(a, i2, a, f8.6)") "Next number:", i, "   sma = ", sma(real(i))
  end do
  do i = 5, 1, -1
    write (*, "(a, i2, a, f8.6)") "Next number:", i, "   sma = ", sma(real(i))
  end do

contains

function sma(n)
  real :: sma
  real, intent(in) :: n
  real, save :: a(3) = 0
  integer, save :: count = 0

  if (count < 3) then
    count = count + 1
    a(count) = n
  else
    a = eoshift(a, 1, n)
  end if

  sma = sum(a(1:count)) / real(count)
end function

end program Movavg


' FB 1.05.0 Win64

Type FuncType As Function(As Double) As Double

' These 'shared' variables are available to all functions defined below
Dim Shared p As UInteger
Dim Shared list() As Double

Function sma(n As Double) As Double
  Redim Preserve list(0 To UBound(list) + 1)
  list(UBound(list)) = n
  Dim start As Integer = 0
  Dim length As Integer = UBound(list) + 1
  If length > p Then
    start = UBound(list) - p + 1
    length = p
  End If
  Dim sum As Double = 0.0
  For i As Integer = start To UBound(list)
    sum += list(i)
  Next
  Return sum / length
End Function

Function initSma(period As Uinteger) As FuncType
  p = period
  Erase list '' ensure the array is empty on each initialization
  Return @sma
End Function

Dim As FuncType ma = initSma(3)
Print "Period = "; p
Print
For i As Integer = 0 To 9
  Print "Add"; i; " => moving average ="; ma(i)
Next
Print
ma = initSma(5)
Print "Period = "; p
Print
For i As Integer = 9 To 0 Step -1
  Print "Add"; i; " => moving average ="; ma(i)
Next
Print
Print "Press any key to quit"
Sleep


MovingAverage := function(n)
  local sma, buffer, pos, sum, len;
  buffer := List([1 .. n], i -> 0);
  pos := 0;
  len := 0;
  sum := 0;
  sma := function(x)
    pos := RemInt(pos, n) + 1;
    sum := sum + x - buffer[pos];
    buffer[pos] := x;
    len := Minimum(len + 1, n);
    return sum/len;
  end;
  return sma;
end;

f := MovingAverage(3);
f(1);  #  1
f(2);  #  3/2
f(3);  #  2
f(4);  #  3
f(5);  #  4
f(5);  #  14/3
f(4);  #  14/3
f(3);  #  4
f(2);  #  3
f(1);  #  2


package main

import "fmt"

func sma(period int) func(float64) float64 {
    var i int
    var sum float64
    var storage = make([]float64, 0, period)

    return func(input float64) (avrg float64) {
        if len(storage) < period {
            sum += input
            storage = append(storage, input)
        }

	sum += input - storage[i]
        storage[i], i = input, (i+1)%period
	avrg = sum / float64(len(storage))

	return
    }
}

func main() {
    sma3 := sma(3)
    sma5 := sma(5)
    fmt.Println("x       sma3   sma5")
    for _, x := range []float64{1, 2, 3, 4, 5, 5, 4, 3, 2, 1} {
        fmt.Printf("%5.3f  %5.3f  %5.3f\n", x, sma3(x), sma5(x))
    }
}


def simple_moving_average = { size ->
    def nums = []
    double total = 0.0
    return { newElement ->
        nums += newElement
        oldestElement = nums.size() > size ? nums.remove(0) : 0
        total += newElement - oldestElement
        total / nums.size()
    }
}

ma5 = simple_moving_average(5)

(1..5).each{ printf( "%1.1f ", ma5(it)) }
(5..1).each{ printf( "%1.1f ", ma5(it)) }


{-# LANGUAGE BangPatterns #-}

import Control.Monad
import Data.List
import Data.IORef

data Pair a b = Pair !a !b

mean :: Fractional a => [a] -> a
mean = divl . foldl' (\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0)
  where divl (_,0) = 0.0
        divl (s,l) = s / fromIntegral l

series = [1,2,3,4,5,5,4,3,2,1]

mkSMA :: Int -> IO (Double -> IO Double)
mkSMA period = avgr <$> newIORef []
  where avgr nsref x = readIORef nsref >>= (\ns ->
            let xs = take period (x:ns)
            in writeIORef nsref xs $> mean xs)

main = mkSMA 3 >>= (\sma3 -> mkSMA 5 >>= (\sma5 ->
    mapM_ (str <$> pure n <*> sma3 <*> sma5) series))
  where str n mm3 mm5 =
    concat ["Next number = ",show n,", SMA_3 = ",show mm3,", SMA_5 = ",show mm5]


REAL :: n=10, nums(n)

nums = (1,2,3,4,5, 5,4,3,2,1)
DO i = 1, n
   WRITE() "num=", i, "SMA3=", SMA(3,nums(i)), "SMA5=",SMA(5,nums(i))
ENDDO

END ! of "main"

FUNCTION SMA(period, num) ! maxID independent streams
 REAL :: maxID=10, now(maxID), Periods(maxID), Offsets(maxID), Pool(1000)

   ID = INDEX(Periods, period)
   IF( ID == 0) THEN ! initialization
     IDs = IDs + 1
     ID = IDs
     Offsets(ID) = SUM(Periods) + 1
     Periods(ID) = period
   ENDIF

   now(ID) = now(ID) + 1
   ALIAS(Pool,Offsets(ID),   Past,Periods(ID)) ! renames relevant part of data pool
   Past = Past($+1) ! shift left
   Past(Periods(ID)) = num
   SMA = SUM(Past) / MIN( now(ID), Periods(ID) )
 END


procedure main(A)
    sma := buildSMA(3)  # Use better name than "I".
    every write(sma(!A))
end

procedure buildSMA(P)
    local stream
    c := create {
        stream := []
        while n := (avg@&source)[1] do {
           put(stream, n)
           if *stream > P then pop(stream)
           every (avg := 0.0) +:= !stream
           avg := avg/*stream
           }
        }
    return (@c, c)
end


import java.util.LinkedList;
import java.util.Queue;

public class MovingAverage {
    private final Queue<Double> window = new LinkedList<Double>();
    private final int period;
    private double sum;

    public MovingAverage(int period) {
        assert period > 0 : "Period must be a positive integer";
        this.period = period;
    }

    public void newNum(double num) {
        sum += num;
        window.add(num);
        if (window.size() > period) {
            sum -= window.remove();
        }
    }

    public double getAvg() {
        if (window.isEmpty()) return 0.0; // technically the average is undefined
        return sum / window.size();
    }

    public static void main(String[] args) {
        double[] testData = {1, 2, 3, 4, 5, 5, 4, 3, 2, 1};
        int[] windowSizes = {3, 5};
        for (int windSize : windowSizes) {
            MovingAverage ma = new MovingAverage(windSize);
            for (double x : testData) {
                ma.newNum(x);
                System.out.println("Next number = " + x + ", SMA = " + ma.getAvg());
            }
            System.out.println();
        }
    }
}


function simple_moving_averager(period) {
    var nums = [];
    return function(num) {
        nums.push(num);
        if (nums.length > period)
            nums.splice(0,1);  // remove the first element of the array
        var sum = 0;
        for (var i in nums)
            sum += nums[i];
        var n = period;
        if (nums.length < period)
            n = nums.length;
        return(sum/n);
    }
}

var sma3 = simple_moving_averager(3);
var sma5 = simple_moving_averager(5);
var data = [1,2,3,4,5,5,4,3,2,1];
for (var i in data) {
    var n = data[i];
    // using WSH
    WScript.Echo("Next number = " + n + ", SMA_3 = " + sma3(n) + ", SMA_5 = " + sma5(n));
}


// version 1.0.6

fun initMovingAverage(p: Int): (Double) -> Double {
    if (p < 1) throw IllegalArgumentException("Period must be a positive integer")
    val list = mutableListOf<Double>()
    return {
        list.add(it)
        if (list.size > p) list.removeAt(0)
        list.average()
    }
}

fun main(args: Array<String>) {
    val sma4 = initMovingAverage(4)
    val sma5 = initMovingAverage(5)
    val numbers = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 4.0, 3.0, 2.0, 1.0)
    println("num\tsma4\tsma5\n")
    for (number in numbers) println("${number}\t${sma4(number)}\t${sma5(number)}")
}


define simple_moving_average(a::array,s::integer)::decimal => {
	#a->size == 0 ? return 0.00
	#s == 0 ? return 0.00
	#a->size == 1 ? return decimal(#a->first)
	#s == 1 ? return decimal(#a->last)
	local(na = array)
	if(#a->size <= #s) => {
		#na = #a
	else
		local(ar = #a->ascopy)
		#ar->reverse
		loop(#s) => { #na->insert(#ar->get(loop_count)) }
	}
	#s > #na->size ? #s = #na->size
	return (with e in #na sum #e) / decimal(#s)
}
// tests:
'SMA 3 on array(1,2,3,4,5,5,4,3,2,1): '
simple_moving_average(array(1,2,3,4,5,5,4,3,2,1),3)

'\rSMA 5 on array(1,2,3,4,5,5,4,3,2,1): '
simple_moving_average(array(1,2,3,4,5,5,4,3,2,1),5)

'\r\rFurther example: \r'
local(mynumbers = array, sma_num = 5)
loop(10) => {^
	#mynumbers->insert(integer_random(1,100))
	#mynumbers->size + ' numbers: ' + #mynumbers
	 ' SMA3 is: ' + simple_moving_average(#mynumbers,3)
	 ', SMA5 is: ' + simple_moving_average(#mynumbers,5)
	'\r'
^}


    dim v$( 100)                                                            '   Each array term stores a particular SMA of period p in p*10 bytes

    nomainwin

    WindowWidth  =1080
    WindowHeight = 780

    graphicbox #w.gb1,   20,   20, 1000,  700

    open "Running averages to smooth data" for window as #w

    #w "trapclose quit"

    #w.gb1 "down"

    old.x         =  0
    old.y.orig    =500  '   black
    old.y.3.SMA   =350  '     red
    old.y.20.SMA  =300  '   green

    for i =0 to 999 step 1
        scan
        v       =1.1 +sin( i /1000 *2 *3.14159265) + 0.2 *rnd( 1)               '   sin wave with added random noise
        x       =i /6.28318 *1000
        y.orig  =500 -v /2.5 *500

        #w.gb1 "color black ; down ; line "; i-1; " "; old.y.orig;  " "; i; " "; y.orig;         " ; up"

        y.3.SMA =500 -SMA( 1, v,  3) /2.5 *500                                  '   SMA given ID of 1 is to do 3-term  running average
        #w.gb1 "color red   ; down ; line "; i-1; " "; old.y.3.SMA +50;  " "; i; " "; y.3.SMA  +50;  " ; up"

        y.20.SMA =500 -SMA( 2, v, 20) /2.5 *500                                 '   SMA given ID of 2 is to do 20-term running average
        #w.gb1 "color green ; down ; line "; i-1; " "; old.y.20.SMA +100; " "; i; " "; y.20.SMA +100; " ; up"

        'print "Supplied with "; v; ", so SMAs are now "; using( "###.###", SMA( 1, v, 3)); " over 3 terms or "; using( "###.###", SMA( 2, v, 5)) ; " over 5 terms."  '   ID, latest data, period

        old.y.orig    =y.orig
        old.y.3.SMA   =y.3.SMA
        old.y.20.SMA  =y.20.SMA
    next i

    wait

sub quit j$
    close #w
    end
end sub

function SMA( ID, Number, Period)
    v$( ID) =right$( "          " +str$( Number), 10) +v$( ID)              '   add new number at left, lose last number on right
    v$( ID) =left$( v$( ID), Period *10)
    'print "{"; v$( ID); "}",

    k      =0   '   number of terms read
    total  =0   '   sum of terms read

    do
        p$     =mid$( v$( ID), 1 +k *10, 10)
        if p$ ="" then exit do
        vv     =val( p$)
        total  =total +vv
        k      =k +1
    loop until p$ =""

    if k <Period then SMA =total / k else  SMA =total /Period
end function


to average :l
  output quotient apply "sum :l count :l
end

to make.sma :name :period
  localmake "qn word :name ".queue
  make :qn []
  define :name `[ [n]              ; parameter list
    [if equal? count :,:qn ,:period [ignore dequeue ",:qn]]
    [queue ",:qn :n]
    [output average :,:qn]
  ]
end

make.sma "avg3 3

show map "avg3 [1 2 3 4 5]     ; [1 1.5 2 3 4]

show text "avg3     ; examine what substitutions took place
[[n] [if equal? count :avg3.queue 3 [ignore dequeue "avg3.queue]] [queue "avg3.queue :n] [output average :avg3.queue]]

; the internal queue is in the global namespace, easy to inspect
show :avg3.queue    ; [3 4 5]


function sma(period)
	local t = {}
	function sum(a, ...)
		if a then return a+sum(...) else return 0 end
	end
	function average(n)
		if #t == period then table.remove(t, 1) end
		t[#t + 1] = n
		return sum(unpack(t)) / #t
	end
	return average
end

sma5 = sma(5)
sma10 = sma(10)
print("SMA 5")
for v=1,15 do print(sma5(v)) end
print("\nSMA 10")
for v=1,15 do print(sma10(v)) end


MA[x_List, r_] := Join[Table[Mean[x[[1;;y]]],{y,r-1}], MovingAverage[x,r]]


    % state(period, list of floats from [newest, ..., oldest])
:- type state ---> state(int, list(float)).

:- func init(int) = state.
init(Period) = state(Period, []).

:- pred sma(float::in, float::out, state::in, state::out) is det.
sma(N, Average, state(P, L0), state(P, L)) :-
        take_upto(P, [N|L0], L),
        Average = foldl((+), L, 0.0) / float(length(L)).


SMA = {}
SMA.P = 5  // (a default; may be overridden)
SMA.buffer = null
SMA.next = function(n)
    if self.buffer == null then self.buffer = []
    self.buffer.push n
    if self.buffer.len > self.P then self.buffer.pull
    return self.buffer.sum / self.buffer.len
end function

sma3 = new SMA
sma3.P = 3
sma5 = new SMA

for i in range(10)
    num = round(rnd*100)
    print "num: " + num + "  sma3: " + sma3.next(num) + "  sma5: " + sma5.next(num)
end for


/* NetRexx */
options replace format comments java crossref symbols nobinary

numeric digits 20

class RAvgSimpleMoving public

  properties private
    window = java.util.Queue
    period
    sum

  properties constant
    exMsg = 'Period must be a positive integer'

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method RAvgSimpleMoving(period_) public
    if \period_.datatype('w') then signal RuntimeException(exMsg)
    if period_ <= 0           then signal RuntimeException(exMsg)
    window = LinkedList()
    period = period_
    sum    = 0
    return

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method newNum(num) public
    sum = sum + num
    window.add(num)
    if window.size() > period then do
      rmv = (Rexx window.remove())
      sum = sum - rmv
      end
    return

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method getAvg() public returns Rexx
    if window.isEmpty() then do
      avg = 0
      end
    else do
      avg = sum / window.size()
      end
    return avg

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method run_samples(args = String[]) public static
    testData = [Rexx 1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
    windowSizes = [Rexx 3, 5]
    loop windSize over windowSizes
      ma = RAvgSimpleMoving(windSize)
      loop xVal over testData
        ma.newNum(xVal)
        say 'Next number =' xVal.right(5)', SMA =' ma.getAvg().format(10, 9)
        end xVal
      say
      end windSize

    return

  -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  method main(args = String[]) public static
    run_samples(args)
    return


import deques

proc simplemovingaverage(period: int): auto =
  assert period > 0

  var
    summ, n = 0.0
    values: Deque[float]
  for i in 1..period:
    values.addLast(0)

  proc sma(x: float): float =
    values.addLast(x)
    summ += x - values.popFirst()
    n = min(n+1, float(period))
    result = summ / n

  return sma

var sma = simplemovingaverage(3)
for i in 1..5: echo sma(float(i))
for i in countdown(5,1): echo sma(float(i))

echo ""

var sma2 = simplemovingaverage(5)
for i in 1..5: echo sma2(float(i))
for i in countdown(5,1): echo sma2(float(i))


use Collection;

class MovingAverage {
  @window : FloatQueue;
  @period : Int;
  @sum : Float;

  New(period : Int) {
    @window := FloatQueue->New();
    @period := period;
  }

  method : NewNum(num : Float) ~ Nil {
    @sum += num;
    @window->Add(num);
    if(@window->Size() > @period) {
      @sum -= @window->Remove();
    };
  }

  method : GetAvg() ~ Float {
    if(@window->IsEmpty()) {
      return 0; # technically the average is undefined
    };

    return @sum / @window->Size();
  }

  function : Main(args : String[]) ~ Nil {
    testData := [1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 4.0, 3.0, 2.0, 1.0];
    windowSizes := [3.0, 5.0];

    each(i : windowSizes) {
      windSize := windowSizes[i];
      ma := MovingAverage->New(windSize);
      each(j : testData) {
        x := testData[j];
        ma->NewNum(x);
        avg := ma->GetAvg();
        "Next number = {$x}, SMA = {$avg}"->PrintLine();
      };
      IO.Console->PrintLine();
    };
  }
}


#import <Foundation/Foundation.h>

@interface MovingAverage : NSObject {
	unsigned int period;
	NSMutableArray *window;
	double sum;
}
- (instancetype)initWithPeriod:(unsigned int)thePeriod;
@end

@implementation MovingAverage

// init with default period
- (instancetype)init {
	self = [super init];
	if(self) {
		period = 10;
		window = [[NSMutableArray alloc] init];
		sum = 0.0;
	}
	return self;
}

// init with specified period
- (instancetype)initWithPeriod:(unsigned int)thePeriod {
	self = [super init];
	if(self) {
		period = thePeriod;
		window = [[NSMutableArray alloc] init];
		sum = 0.0;
	}
	return self;
}

// add a new number to the window
- (void)add:(double)val {
	sum += val;
	[window addObject:@(val)];
	if([window count] > period) {
		NSNumber *n = window[0];
		sum -= [n doubleValue];
		[window removeObjectAtIndex:0];
	}
}

// get the average value
- (double)avg {
	if([window count] == 0) {
		return 0; // technically the average is undefined
	}
	return sum / [window count];
}

// set the period, resizes current window
- (void)setPeriod:(unsigned int)thePeriod {
	// make smaller?
	if(thePeriod < [window count]) {
		for(int i = 0; i < thePeriod; ++i) {
			NSNumber *n = window[0];
			sum -= [n doubleValue];
			[window removeObjectAtIndex:0];
		}
	}
	period = thePeriod;
}

// get the period (window size)
- (unsigned int)period {
	return period;
}

// clear the window and current sum
- (void)clear {
	[window removeAllObjects];
	sum = 0;
}

@end

int main (int argc, const char * argv[]) {
	@autoreleasepool {
		double testData[10] = {1,2,3,4,5,5,4,3,2,1};
		int periods[2] = {3,5};
		for(int i = 0; i < 2; ++i) {
			MovingAverage *ma = [[MovingAverage alloc] initWithPeriod:periods[i]];
			for(int j = 0; j < 10; ++j) {
				[ma add:testData[j]];
				NSLog(@"Next number = %f, SMA = %f", testData[j], [ma avg]);
			}
			NSLog(@"\n");
		}
	}
	return 0;
}


let sma (n, s, q) x =
  let l = Queue.length q and s = s +. x in
  Queue.push x q;
  if l < n then
    (n, s, q), s /. float (l + 1)
  else (
    let s = s -. Queue.pop q in
    (n, s, q), s /. float l
  )

let _ =
  let periodLst = [ 3; 5 ] in
  let series = [ 1.; 2.; 3.; 4.; 5.; 5.; 4.; 3.; 2.; 1. ] in

  List.iter (fun d ->
    Printf.printf "SIMPLE MOVING AVERAGE: PERIOD = %d\n" d;
    ignore (
      List.fold_left (fun o x ->
	let o, m = sma o x in
	Printf.printf "Next number = %-2g, SMA = %g\n" x m;
	o
      ) (d, 0., Queue.create ()) series;
    );
    print_newline ();
  ) periodLst


import: parallel

: createSMA(period)
| ch |
   Channel new [ ] over send drop ->ch
   #[ ch receive + left(period) dup avg swap ch send drop ] ;


testdata = .array~of(1, 2, 3, 4, 5, 5, 4, 3, 2, 1)

-- run with different period sizes
loop period over .array~of(3, 5)
    say "Period size =" period
    say
    movingaverage = .movingaverage~new(period)
    loop number over testdata
        average = movingaverage~addnumber(number)
        say "   Next number =" number", moving average =" average
    end
    say
end

::class movingaverage
::method init
  expose period queue sum
  use strict arg period
  sum = 0
  -- the circular queue makes this easy
  queue = .circularqueue~new(period)

-- add a number to the average set
::method addNumber
  expose queue sum
  use strict arg number
  sum += number
  -- add this to the queue
  old = queue~queue(number)
  -- if we pushed an element off the end of the queue,
  -- subtract this from our sum
  if old \= .nil then sum -= old
  -- and return the current item
  return sum / queue~items

-- extra method to retrieve current average
::method average
  expose queue sum
  -- undefined really, but just return 0
  if queue~isempty then return 0
  -- return current queue
  return sum / queue~items


def max 1000

Class MovingAverage
'==================

indexbase 1
double average,invperiod,mdata[max]
sys    index,period

method Setup(double a,p)
sys i
Period=p
invPeriod=1/p
index=0
average=a
for i=1 to period
  mdata[i]=a
next
end method

method Data(double v) as double
sys i
index++
if index>period then index=1 'recycle
i=index+1 'for oldest data
if i>period then i=1 'recycle
mdata[index]=v
average=average+invperiod*(v-mdata[i])
end method

end class

'TEST
'====

MovingAverage A

A.Setup 100,10 'initial value and period

A.data 50
'...
print A.average 'reult 95


declare

  fun {CreateSMA Period}
     Xs = {NewCell nil}
  in
     fun {$ X}
        Xs := {List.take X|@Xs Period}

        {FoldL @Xs Number.'+' 0.0}
        /
        {Int.toFloat {Min Period {Length @Xs}}}
     end
  end

in

  for Period in [3 5] do
     SMA = {CreateSMA Period}
  in
     {System.showInfo "\nSTART PERIOD "#Period}
     for I in 1..5 do
        {System.showInfo "  Number = "#I#" , SMA = "#{SMA {Int.toFloat I}}}
     end
     for I in 5..1;~1 do
        {System.showInfo "  Number = "#I#" , SMA = "#{SMA {Int.toFloat I}}}
     end
  end


sma_per(n)={
  sma_v=vector(n);
  sma_i = 0;
  n->if(sma_i++>#sma_v,sma_v[sma_i=1]=n;0,sma_v[sma_i]=n;0)+sum(i=1,#sma_v,sma_v[i])/#sma_v
};


program sma;
type
  tsma = record
            smaValue : array of double;
            smaAverage,
            smaSumOld,
            smaSumNew,
            smaRezActLength : double;
            smaActLength,
            smaLength,
            smaPos   :NativeInt;
            smaIsntFull: boolean;
         end;

procedure smaInit(var sma:tsma;p: NativeUint);
Begin
  with sma do
  Begin
    setlength(smaValue,0);
    setlength(smaValue,p);
    smaLength:= p;
    smaActLength := 0;
    smaAverage:= 0.0;
    smaSumOld := 0.0;
    smaSumNew := 0.0;
    smaPos := p-1;
    smaIsntFull := true
    end;
end;

function smaAddValue(var sma:tsma;v: double):double;
Begin
  with sma do
  Begin
    IF smaIsntFull then
    Begin
      inc(smaActLength);
      smaRezActLength := 1/smaActLength;
      smaIsntFull :=  smaActLength < smaLength ;
    end;
    smaSumOld := smaSumOld+v-smaValue[smaPos];
    smaValue[smaPos] := v;
    smaSumNew := smaSumNew+v;

    smaPos := smaPos-1;
    if smaPos < 0 then
    begin
      smaSumOld:= smaSumNew;
      smaSumNew:= 0.0;
      smaPos := smaLength-1;
    end;
    smaAverage := smaSumOld *smaRezActLength;
    smaAddValue:= smaAverage;
  end;
end;

var
 sma3,sma5:tsma;
 i : LongInt;
begin
  smaInit(sma3,3);
  smaInit(sma5,5);
  For i := 1 to 5 do
  Begin
    write('Inserting ',i,' into sma3 ',smaAddValue(sma3,i):0:4);
    writeln(' Inserting ',i,' into sma5 ',smaAddValue(sma5,i):0:4);
  end;
  For i := 5 downto 1 do
  Begin
    write('Inserting ',i,' into sma3 ',smaAddValue(sma3,i):0:4);
    writeln(' Inserting ',i,' into sma5 ',smaAddValue(sma5,i):0:4);
  end;
  //speed test
  smaInit(sma3,3);
  For i := 1 to 100000000 do
    smaAddValue(sma3,i);
  writeln('100''000''000 insertions ',sma3.smaAverage:0:4);
end.


sub sma_generator {
    my $period = shift;
    my (@list, $sum);

    return sub {
        my $number = shift;
        push @list, $number;
        $sum += $number;
        $sum -= shift @list if @list > $period;
        return $sum / @list;
    }
}

# Usage:
my $sma = sma_generator(3);
for (1, 2, 3, 2, 7) {
    printf "append $_ --> sma = %.2f  (with period 3)\n", $sma->($_);
}


with javascript_semantics
sequence sma = {}       -- ((period,history,circnxt))  (private to sma.e)
integer sma_free = 0

global function new_sma(integer period)
integer res
    if sma_free then
        res = sma_free
        sma_free = sma[sma_free]
        sma[res] = {period,{},0}
    else
        sma = append(sma,{period,{},0})
        res = length(sma)
    end if
    return res
end function

global procedure add_sma(integer sidx, atom val)
integer period, circnxt
sequence history
    {period,history,circnxt} = sma[sidx]
    sma[sidx][2] = 0 -- (kill refcount)
    if length(history)<period then
        history = append(history,val)
    else
        circnxt += 1
        if circnxt>period then
            circnxt = 1
        end if
        sma[sidx][3] = circnxt
        history[circnxt] = val
    end if
    sma[sidx][2] = history
end procedure

global function get_sma_average(integer sidx)
sequence history = sma[sidx][2]
integer l = length(history)
    if l=0 then return 0 end if
    return sum(history)/l
end function

global function moving_average(integer sidx, atom val)
    add_sma(sidx,val)
    return get_sma_average(sidx)
end function

global procedure free_sma(integer sidx)
    sma[sidx] = sma_free
    sma_free = sidx
end procedure


main =>
  L=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
  Map3 = new_map([p=3]),
  Map5 = new_map([p=5]),
  foreach(N in L)
    printf("n: %-2d sma3: %-17w sma5: %-17w\n",N, sma(N,Map3), sma(N,Map5))
  end.

sma(N,Map) = Average =>
  Stream = Map.get(stream,[]) ++ [N],
  if Stream.len > Map.get(p) then
    Stream := Stream.tail
  end,
  Average = cond(Stream.len == 0,
                 0,
                sum(Stream) / Stream.len),
  Map.put(stream,Stream).


(de sma (@Len)
   (curry (@Len (Data)) (N)
      (push 'Data N)
      (and (nth Data @Len) (con @))  # Truncate
      (*/ (apply + Data) (length Data)) ) )


SMA: procedure (N) returns (float byaddr);
   declare N fixed;
   declare A(*) fixed controlled,
           (p, q) fixed binary static initial (0);

   if allocation(A) = 0 then signal error;

   p = p + 1; if q < 20 then q = q + 1;
   if p > hbound(A, 1) then p = 1;
   A(p) = N;
   return (sum(float(A))/q);

I: ENTRY (Period);
   declare Period fixed binary;

   if allocation(A) > 0 then FREE A;
   allocate A(Period);
   A = 0;
   p = 0;
end SMA;


class MovingAverage
  let period: USize
  let _arr: Array[I32] // circular buffer
  var _curr: USize  // index of pointer position
  var _total: I32   // cache the total so far

  new create(period': USize) =>
    period = period'
    _arr = Array[I32](period) // preallocate space
    _curr = 0
    _total = 0

  fun ref apply(n: I32): F32 =>
    _total = _total + n
    if _arr.size() < period then
      _arr.push(n)
    else
      try
        let prev = _arr.update(_curr, n)?
        _total = _total - prev
        _curr = (_curr + 1) % period
      end
    end
    _total.f32() / _arr.size().f32()

// ---- TESTING -----
actor Main
  new create(env: Env) =>
    let foo = MovingAverage(3)
    let bar = MovingAverage(5)
    let data: Array[I32] = [1; 2; 3; 4; 5; 5; 4; 3; 2; 1]
    for v in data.values() do
      env.out.print("Foo: " + foo(v).string())
    end
    for v in data.values() do
      env.out.print("Bar: " + bar(v).string())
    end


#This version allows a user to enter numbers one at a time to figure this into the SMA calculations

$inputs = @() #Create an array to hold all inputs as they are entered.
$period1 = 3 #Define the periods you want to utilize
$period2 = 5

Write-host "Enter numbers to observe their moving averages." -ForegroundColor Green

function getSMA ($inputs, [int]$period) #Function takes a array of entered values and a period (3 and 5 in this case)
{
    if($inputs.Count -lt $period){$period = $inputs.Count} #Makes sure that if there's less numbers than the designated period (3 in this case), the number of availble values is used as the period instead.

    for($count = 0; $count -lt $period; $count++) #Loop sums the latest available values
    {
        $result += $inputs[($inputs.Count) - $count - 1]
    }

    return ($result | ForEach-Object -begin {$sum=0 }-process {$sum+=$_} -end {$sum/$period}) #Gets the average for a given period
}

while($true) #Infinite loop so the user can keep entering numbers
{
    try{$inputs += [decimal] (Read-Host)}catch{Write-Host "Enter only numbers" -ForegroundColor Red} #Enter the numbers. Error checking to help mitigate bad inputs (non-number values)

    "Added " + $inputs[(($inputs.Count) - 1)] + ", sma($period1) = " + (getSMA $inputs $Period1) + ", sma($period2) = " + (getSMA $inputs $period2)
}


Procedure.d SMA(Number, Period=0)
  Static P
  Static NewList L()
  Protected Sum=0
  If Period<>0
    P=Period
  EndIf
  LastElement(L())
  AddElement(L())
  L()=Number
  While ListSize(L())>P
    FirstElement(L())
    DeleteElement(L(),1)
  Wend
  ForEach L()
    sum+L()
  Next
  ProcedureReturn sum/ListSize(L())
EndProcedure


from collections import deque

def simplemovingaverage(period):
    assert period == int(period) and period > 0, "Period must be an integer >0"

    summ = n = 0.0
    values = deque([0.0] * period)     # old value queue

    def sma(x):
        nonlocal summ, n

        values.append(x)
        summ += x - values.popleft()
        n = min(n+1, period)
        return summ / n

    return sma


  [ $ "bigrat.qky" loadfile ] now!

  [ over size -
    space swap of
    join ]                 is pad      ( $ n --> $ )

  [ ' [ stack [ ] ]
    copy nested
    ' [ tuck take swap join
       dup size ] join
    swap join
    ' [ > if
          [ 1 split nip ]
        tuck swap put
        0 over witheach +
        swap size
        dip n->v n->v v/ ]
    join copy ]            is make-sma (   n --> [ )
                                  ( behaviour of [ is: n --> n/d )

  [ stack ]                is sma-3    (     --> s )
  3 make-sma sma-3 put

  [ stack ]                is sma-5    (     --> s )
  5 make-sma sma-5 put

  say "n sma-3      sma-5" cr cr
  ' [ 1 2 3 4 5 5 4 3 2 1 ]
  witheach
    [ dup echo sp
      dup sma-3 share do
      7 point$ 10 pad echo$ sp
      sma-5 share do
      7 point$ 10 pad echo$ cr ]


#concat concatenates the new values to the existing vector of values, then discards any values that are too old.
lastvalues <- local(
{
   values <- c();
   function(x, len)
   {
      values <<- c(values, x);
      lenv <- length(values);
      if(lenv > len) values <<- values[(len-lenv):-1]
      values
   }
})

#moving.average accepts a numeric scalars input (and optionally a length, i.e. the number of values to retain) and calculates the stateful moving average.
moving.average <- function(latestvalue, len=3)
{
   #Check that all inputs are numeric scalars
   is.numeric.scalar <- function(x) is.numeric(x) && length(x)==1L
   if(!is.numeric.scalar(latestvalue) || !is.numeric.scalar(len))
   {
      stop("all arguments must be numeric scalars")
   }

   #Calculate mean of variables so far
   mean(lastvalues(latestvalue, len))
}
moving.average(5)  # 5
moving.average(1)  # 3
moving.average(-3) # 1
moving.average(8)  # 2
moving.average(7)  # 4


#lang racket

(require data/queue)

(define (simple-moving-average period)
  (define queue (make-queue))
  (define sum 0.0)

  (lambda (x)
    (enqueue! queue x)
    (set! sum (+ sum x))
    (when (> (queue-length queue) period)
      (set! sum (- sum (dequeue! queue))))
    (/ sum (queue-length queue))))

;; Tests
(define sma3 (simple-moving-average 3))
(define sma5 (simple-moving-average 5))
(for/lists (lst1 lst2)
           ([i '(1 2 3 4 5 5 4 3 2 1)])
  (values (sma3 i) (sma5 i)))


sub sma-generator (Int $P where * > 0) {
    sub ($x) {
        state @a = 0 xx $P;
        @a.push($x).shift;
        @a.sum / $P;
    }
}

# Usage:
my &sma = sma-generator 3;

for 1, 2, 3, 2, 7 {
    printf "append $_ --> sma = %.2f  (with period 3)\n", sma $_;
}


/*REXX program illustrates and displays a simple moving average using a constructed list*/
parse arg p q n .                                /*obtain optional arguments from the CL*/
if p=='' | p==","  then p=  3                    /*Not specified?  Then use the default.*/
if q=='' | q==","  then q=  5                    /* "      "         "   "   "     "    */
if n=='' | n==","  then n= 10                    /* "      "         "   "   "     "    */
@.= 0                                            /*default value, only needed for odd N.*/
      do j=1    for n%2;       @.j= j            /*build 1st half of list, increasing #s*/
      end   /*j*/

      do k=n%2  by -1  to 1;   @.j= k;   j= j+1  /*  "   2nd   "   "   "   decreasing " */
      end   /*k*/
                      say '  number  '     " SMA with period" p' '   " SMA with period" q
                      say ' ──────── '     "───────────────────"     '───────────────────'
                                           pad='     '
      do m=1  for n;  say center(@.m, 10)  pad left(SMA(p, m), 19)     left(SMA(q, m), 19)
      end   /*m*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
SMA: procedure expose @.;  parse arg p,j;                          i= 0    ;    $= 0
                 do k=max(1, j-p+1)  to j+p  for p  while k<=j;    i= i + 1;    $= $ + @.k
                 end   /*k*/
     return $/i                                  /*SMA   ≡   simple moving average.     */


load "stdlib.ring"
decimals(8)
maxperiod = 20
nums = newlist(maxperiod,maxperiod)
accum = list(maxperiod)
index = list(maxperiod)
window = list(maxperiod)
for i = 1 to maxperiod
    index[i] = 1
    accum[i] = 0
    window[i] = 0
next
for i = 1 to maxperiod
    for j = 1 to maxperiod
        nums[i][j] = 0
    next
next
for n = 1 to 5
    see "number = " + n + "  sma3 = " + left((string(sma(n,3)) + "        "),9) + "  sma5 = " + sma(n,5) + nl
next
for n = 5 to 1 step -1
    see "number = " + n + "  sma3 = " + left((string(sma(n,3)) + "        "),9) + "  sma5 = " + sma(n,5) + nl
next
see nl

func sma number, period
     accum[period] += number - nums[period][index[period]]
     nums[period][index[period]] = number
     index[period]= (index[period] + 1) % period + 1
     if window[period]<period window[period] += 1 ok
     return (accum[period] / window[period])


def simple_moving_average(size)
  nums = []
  sum = 0.0
  lambda do |hello|
    nums << hello
    goodbye = nums.length > size ? nums.shift : 0
    sum += hello - goodbye
    sum / nums.length
  end
end

ma3 = simple_moving_average(3)
ma5 = simple_moving_average(5)

(1.upto(5).to_a + 5.downto(1).to_a).each do |num|
  printf "Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n",
    num, ma3.call(num), ma5.call(num)
end


data 1,2,3,4,5,5,4,3,2,1
dim sd(10)                          ' series data
global sd                           ' make it global so we all see it
for i = 1 to 10:read sd(i): next i

x = sma(3)                          ' simple moving average for 3 periods
x = sma(5)                          ' simple moving average for 5 periods

function sma(p)                     ' the simple moving average function
print "----- SMA:";p;" -----"
  for i = 1 to 10
    sumSd = 0
    for j = max((i - p) + 1,1) to i
      sumSd = sumSd + sd(j)         ' sum series data for the period
    next j
  if p > i then p1 = i else p1 = p
  print  sd(i);" sma:";p;" ";sumSd / p1
  next i
end function


struct SimpleMovingAverage {
    period: usize,
    numbers: Vec<usize>
}

impl SimpleMovingAverage {
    fn new(p: usize) -> SimpleMovingAverage {
        SimpleMovingAverage {
            period: p,
            numbers: Vec::new()
        }
    }

    fn add_number(&mut self, number: usize) -> f64 {
        self.numbers.push(number);

        if self.numbers.len() > self.period {
            self.numbers.remove(0);
        }

        if self.numbers.is_empty() {
            return 0f64;
        }else {
            let sum = self.numbers.iter().fold(0, |acc, x| acc+x);
            return sum as f64 / self.numbers.len() as f64;
        }
    }
}

fn main() {
    for period in [3, 5].iter() {
        println!("Moving average with period {}", period);

        let mut sma = SimpleMovingAverage::new(*period);
        for i in [1, 2, 3, 4, 5, 5, 4, 3, 2, 1].iter() {
            println!("Number: {} | Average: {}", i, sma.add_number(*i));
        }
    }
}


class MovingAverage(period: Int) {
  private var queue = new scala.collection.mutable.Queue[Double]()
  def apply(n: Double) = {
    queue.enqueue(n)
    if (queue.size > period)
      queue.dequeue
    queue.sum / queue.size
  }
  override def toString = queue.mkString("(", ", ", ")")+", period "+period+", average "+(queue.sum / queue.size)
  def clear = queue.clear
}


(define ((simple-moving-averager size . nums) num)
  (set! nums (cons num (if (= (length nums) size) (reverse (cdr (reverse nums))) nums)))
  (/ (apply + nums) (length nums)))

(define av (simple-moving-averager 3))
(map av '(1 2 3 4 5 5 4 3 2 1))


func simple_moving_average(period) {

    var list = []
    var sum = 0

    func (number) {
        list.append(number)
        sum += number
        if (list.len > period) {
            sum -= list.shift
        }
        (sum / list.length)
    }
}

var ma3 = simple_moving_average(3)
var ma5 = simple_moving_average(5)

for num (1..5, flip(1..5)) {
  printf("Next number = %d, SMA_3 = %.3f, SMA_5 = %.1f\n",
    num, ma3.call(num), ma5.call(num))
}


Object subclass: MovingAverage [
    |valueCollection period collectedNumber sum|
    MovingAverage class >> newWithPeriod: thePeriod [
	|r|
	r := super basicNew.
	^ r initWithPeriod: thePeriod
    ]
    initWithPeriod: thePeriod [
    	valueCollection := OrderedCollection new: thePeriod.
	period := thePeriod.
	collectedNumber := 0.
	sum := 0
    ]
    sma [   collectedNumber < period
            ifTrue: [ ^ sum / collectedNumber ]
            ifFalse: [ ^ sum / period ] ]
    add: value [
        collectedNumber < period
   	ifTrue: [
	   sum := sum + value.
	   valueCollection add: value.
	   collectedNumber := collectedNumber + 1.
	]
	ifFalse: [
	   sum := sum - (valueCollection removeFirst).
	   sum := sum + value.
	   valueCollection add: value
	].
	^ self sma
    ]
].


struct SimpleMovingAverage {
  var period: Int
  var numbers = [Double]()

  mutating func addNumber(_ n: Double) -> Double {
    numbers.append(n)

    if numbers.count > period {
      numbers.removeFirst()
    }

    guard !numbers.isEmpty else {
      return 0
    }

    return numbers.reduce(0, +) / Double(numbers.count)
  }
}

for period in [3, 5] {
  print("Moving average with period \(period)")

  var averager = SimpleMovingAverage(period: period)

  for n in [1.0, 2, 3, 4, 5, 5, 4, 3, 2, 1] {
    print("n: \(n); average \(averager.addNumber(n))")
  }
}


oo::class create SimpleMovingAverage {
    variable vals idx
    constructor {{period 3}} {
        set idx end-[expr {$period-1}]
        set vals {}
    }
    method val x {
        set vals [lrange [list {*}$vals $x] $idx end]
        expr {[tcl::mathop::+ {*}$vals]/double([llength $vals])}
    }
}


:1->C
:While 1
:Prompt I
:C->dim(L1)
:I->L1(C)
:Disp mean(L1)
:1+C->C
:End


movinavg(list,p)
Func
  Local r, i, z

  For i,1,dim(list)
    max(i-p,0)→z
    sum(mid(list,z+1,i-z))/(i-z)→r[i]
  EndFor
  r
EndFunc


Class sma
'to be stored in a class module with name "sma"
Private n As Integer 'period
Private arr() As Double 'circular list
Private index As Integer 'pointer into arr
Private oldsma As Double

Public Sub init(size As Integer)
    n = size
    ReDim arr(n - 1)
    index = 0
End Sub

Public Function sma(number As Double) As Double
    sma = oldsma + (-arr(index) + number) / n
    oldsma = sma
    arr(index) = number
    index = (index + 1) Mod n
End Function

Normal module
Public Sub main()
    s = [{1,2,3,4,5,5,4,3,2,1}]
    Dim sma3 As New sma
    Dim sma5 As New sma
    sma3.init 3
    sma5.init 5
    For i = 1 To UBound(s)
        Debug.Print i, Format(sma3.sma(CDbl(s(i))), "0.00000"),
        Debug.Print Format(sma5.sma(CDbl(s(i))), "0.00000")
    Next i
End Sub


data = "1,2,3,4,5,5,4,3,2,1"
token = Split(data,",")
stream = ""
WScript.StdOut.WriteLine "Number" & vbTab & "SMA3" & vbTab & "SMA5"
For j = LBound(token) To UBound(token)
	If Len(stream) = 0 Then
		stream = token(j)
	Else
		stream = stream & "," & token(j)
	End If
	WScript.StdOut.WriteLine token(j) & vbTab & Round(SMA(stream,3),2) & vbTab & Round(SMA(stream,5),2)
Next

Function SMA(s,p)
	If Len(s) = 0 Then
		SMA = 0
		Exit Function
	End If
	d = Split(s,",")
	sum = 0
	If UBound(d) + 1 >= p Then
		c = 0
		For i = UBound(d) To LBound(d) Step -1
			sum = sum + Int(d(i))
			c = c + 1
			If c = p Then
				Exit For
			End If
		Next
		SMA = sum / p
	Else
		For i = UBound(d) To LBound(d) Step -1
			sum = sum + Int(d(i))
		Next
		SMA = sum / (UBound(d) + 1)
	End If
End Function


fn sma(period int) fn(f64) f64 {
    mut i := int(0)
    mut sum := f64(0)
    mut storage := []f64{len: 0, cap:period}

    return fn[mut storage, mut sum, mut i, period](input f64) f64 {
        if storage.len < period {
            sum += input
            storage << input
        }

        sum += input - storage[i]
        storage[i], i = input, (i+1)%period
        return sum / f64(storage.len)
    }
}

fn main() {
    sma3 := sma(3)
    sma5 := sma(5)
    println("x       sma3   sma5")
    for x in [f64(1), 2, 3, 4, 5, 5, 4, 3, 2, 1] {
        println("${x:5.3f}  ${sma3(x):5.3f}  ${sma5(x):5.3f}")
    }
}


import "/fmt" for Fmt

var sma = Fn.new { |period|
    var i = 0
    var sum = 0
    var storage = []
    return Fn.new { |input|
        if (storage.count < period) {
            sum = sum + input
            storage.add(input)
        }
        sum = sum + input - storage[i]
        storage[i] = input
        i = (i+1) % period
        return sum/storage.count
    }
}

var sma3 = sma.call(3)
var sma5 = sma.call(5)
System.print("  x     sma3   sma5")
for (x in [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) {
    Fmt.precision = 3
    System.print("%(Fmt.f(5, x))  %(Fmt.f(5, sma3.call(x)))  %(Fmt.f(5, sma5.call(x)))")
}


fcn SMA(P){
   fcn(n,ns,P){
      sz:=ns.append(n.toFloat()).len();
      if(P>sz) return(0.0);
      if(P<sz) ns.del(0);
      ns.sum(0.0)/P;
   }.fp1(List.createLong(P+1),P)  // pre-allocate a list of length P+1
}


F modes(values)
   DefaultDict[Int, Int] count
   L(v) values
      count[v]++
   V best = max(count.values())
   R count.filter(kv -> kv[1] == @best).map(kv -> kv[0])

print(modes([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]))
print(modes([1, 1, 2, 4, 4]))


DEFINE MAX="100"
INT ARRAY keys(MAX)
INT ARRAY values(MAX)
BYTE count

PROC PrintArray(INT ARRAY a INT size)
  INT i

  Put('[)
  FOR i=0 TO size-1
  DO
    IF i>0 THEN Put(' ) FI
    PrintI(a(i))
  OD
  Put(']) PutE()
RETURN

PROC ClearMap()
  count=0
RETURN

PROC AddToMap(INT a)
  INT i,index

  index=-1
  IF count>0 THEN
    FOR i=0 TO count-1
    DO
      IF keys(i)=a THEN
        index=i EXIT
      FI
    OD
  FI
  IF index=-1 THEN
    keys(count)=a
    values(count)=1
    count==+1
  ELSE
    values(index)==+1
  FI
RETURN

PROC Mode(INT ARRAY a INT aSize INT ARRAY m INT POINTER mSize)
  INT i,mx

  ClearMap()
  FOR i=0 TO aSize-1
  DO
    AddToMap(a(i))
  OD

  mx=0
  FOR i=0 TO count-1
  DO
    IF values(i)>mx THEN
      mx=values(i)
    FI
  OD

  mSize^=0
  FOR i=0 TO count-1
  DO
    IF values(i)=mx THEN
      m(mSize^)=keys(i)
      mSize^==+1
    FI
  OD
RETURN

PROC Test(INT ARRAY a INT size)
  INT ARRAY m(MAX)
  INT mSize

  PrintE("Array:") PrintArray(a,size)
  Mode(a,size,m,@mSize)
  PrintE("Mode:") PrintArray(m,mSize)
  PutE()
RETURN

PROC Main()
  INT ARRAY a=[1 3 5 7 3 1 3 7 7 3 3]
  INT ARRAY b=[7 13 5 13 7 2 7 10 13]
  INT ARRAY c=[5]

  Test(a,11)
  Test(b,9)
  Test(c,1)
RETURN


function Mode(arr:Array):Array {
	//Create an associative array to count how many times each element occurs,
	//an array to contain the modes, and a variable to store how many times each mode appears.
	var count:Array = new Array();
	var modeList:Array;
	var maxCount:uint=0;
	for (var i:String in arr) {
		//Record how many times an element has occurred. Note that each element in the cuont array
		//has to be initialized explicitly, since it is an associative array.
		if (count[arr[i]]==undefined) {
			count[arr[i]]=1;
		} else {
			count[arr[i]]++;
		}
		//If this is now the most common element, clear the list of modes, and add this element.
		if(count[arr[i]] > maxCount)
		{
			maxCount=count[arr[i]];
			modeList = new Array();
			modeList.push(arr[i]);
		}
		//If this is a mode, add it to the list.
		else if(count[arr[i]] == maxCount){
			modeList.push(arr[i]);
		}
	}
	return modeList;
}


generic
   type Element_Type is private;
   type Element_Array is array (Positive range <>) of Element_Type;
package Mode is

   function Get_Mode (Set : Element_Array) return Element_Array;

end Mode;


mode←{{s←⌈/⍵[;2]⋄⊃¨(↓⍵)∩{⍵,s}¨⍵[;1]}{⍺,≢⍵}⌸⍵}


use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later (for these 'use' commands).
use sorter : script "Shell sort" -- https://www.rosettacode.org/wiki/Sorting_algorithms/Shell_sort#AppleScript

on modeOf(listOrRecord)
    -- Extract and sort numbers and text separately, then concatenate the results to get a single list of values.
    set theNumbers to listOrRecord's numbers
    tell sorter to sort(theNumbers, 1, -1)
    set theTexts to listOrRecord's text
    tell sorter to sort(theTexts, 1, -1)
    script o
        property values : theNumbers & theTexts
        property mode : {}
    end script

    -- Identify the most frequently occurring value(s).
    if (o's values is not {}) then
        set i to 1
        set currentValue to beginning of o's values
        set maxCount to 1
        repeat with j from 2 to (count o's values)
            set thisValue to item j of o's values
            if (thisValue is not currentValue) then
                set thisCount to j - i
                if (thisCount > maxCount) then
                    set o's mode to {currentValue}
                    set maxCount to thisCount
                else if (thisCount = maxCount) then
                    set end of o's mode to currentValue
                end if
                set i to j
                set currentValue to thisValue
            end if
        end repeat
        if (j + 1 - i > maxCount) then
            set o's mode to {currentValue}
        else if (j + 1 - i = maxCount) then
            set end of o's mode to currentValue
        end if
    end if

    return o's mode
end modeOf

-- Test code:
-- With a list:
modeOf({12, 4, "rhubarb", 88, "rhubarb", 17, "custard", 4.0, 4, 88, "rhubarb"})
--> {4, "rhubarb"}

-- With a record:
modeOf({a:12, b:4, c:"rhubarb", d:88, e:"rhubarb", f:17, g:"custard", h:4.0, i:4, j:88})
--> {4}


getMode: function [arr][
    freqs: new #[]
    loop arr 'i [
        k: to :string i
        if not? key? freqs k -> set freqs k 0
        freqs\[k]: (freqs\[k]) + 1
    ]
    maximum: max values freqs
    select keys freqs 'i -> maximum = freqs\[i]
]

print getMode [1 3 6 6 6 6 7 7 12 12 17]
print getMode [1 1 2 4 4]


MsgBox % Mode("1 2 3")
MsgBox % Mode("1 2 0 3 0.0")
MsgBox % Mode("0.1 2.2 -0.1 0.22e1 2.20 0.1")

Mode(a, d=" ") { ; the number that occurs most frequently in a list delimited by d (space)
   Sort a, ND%d%
   Loop Parse, a, %d%
      If (V != A_LoopField) {
         If (Ct > MxCt)
            MxV := V, MxCt := Ct
         V := A_LoopField, Ct := 1
      }
      Else Ct++
   Return Ct>MxCt ? V : MxV
}


#!/usr/bin/gawk -f
{
	# compute histogram
	histo[$1] += 1;
};

function mode(HIS) {
    # Computes the mode from Histogram A
    max = 0;
    n = 0;
    for (k in HIS) {
	val = HIS[k];
	if (HIS[k] > max) {
	    max = HIS[k];
            n = 1;
	    List[n] = k;
	} else if (HIS[k] == max)	{
		List[++n] = k;
	}
    }

    for (k=1; k<=n; k++) {
        o = o""OFS""List[k];
    }
    return o;
}

END {
    print mode(histo);
};


      DIM a(10), b(4)
      a() = 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17
      b() = 1, 2, 4, 4, 1

      DIM modes(10)
      PRINT "Mode(s) of a() = " ;
      FOR i% = 1 TO FNmodes(a(), modes())
        PRINT ; modes(i%) " " ;
      NEXT
      PRINT
      PRINT "Mode(s) of b() = " ;
      FOR i% = 1 TO FNmodes(b(), modes())
        PRINT ; modes(i%) " " ;
      NEXT
      PRINT
      END

      DEF FNmodes(a(), m())
      LOCAL I%, J%, N%, c%(), max%
      N% = DIM(a(),1)
      IF N% = 0 THEN m(1) = a(0) : = 1
      DIM c%(N%)
      FOR I% = 0 TO N%-1
        FOR J% = I%+1 TO N%
          IF a(I%) = a(J%) c%(I%) += 1
        NEXT
        IF c%(I%) > max% max% = c%(I%)
      NEXT I%
      J% = 0
      FOR I% = 0 TO N%
        IF c%(I%) = max% J% += 1 : m(J%) = a(I%)
      NEXT
      = J%


Mode1 ← ⌈´⊸=∘⊒⊸/
Mode2 ← ⊏∘⊑˘·(⌈´⊸=≠¨)⊸/⊐⊸⊔

arr ← 1‿1‿1‿1‿2‿2‿2‿3‿3‿3‿3‿4‿4‿3‿2‿4‿4‿4‿5‿5‿5‿5‿5
•Show Mode1 arr
•Show Mode2 arr


#include <stdio.h>
#include <stdlib.h>

typedef struct { double v; int c; } vcount;

int cmp_dbl(const void *a, const void *b)
{
	double x = *(const double*)a - *(const double*)b;
	return x < 0 ? -1 : x > 0;
}

int vc_cmp(const void *a, const void *b)
{
	return ((const vcount*)b)->c - ((const vcount*)a)->c;
}

int get_mode(double* x, int len, vcount **list)
{
	int i, j;
	vcount *vc;

	/* sort values */
	qsort(x, len, sizeof(double), cmp_dbl);

	/* count occurence of each value */
	for (i = 0, j = 1; i < len - 1; i++, j += (x[i] != x[i + 1]));

	*list = vc = malloc(sizeof(vcount) * j);
	vc[0].v = x[0];
	vc[0].c = 1;

	/* generate list value-count pairs */
	for (i = j = 0; i < len - 1; i++, vc[j].c++)
		if (x[i] != x[i + 1]) vc[++j].v = x[i + 1];

	/* sort that by count in descending order */
	qsort(vc, j + 1, sizeof(vcount), vc_cmp);

	/* the number of entries with same count as the highest */
	for (i = 0; i <= j && vc[i].c == vc[0].c; i++);

	return i;
}

int main()
{
	double values[] = { 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17 };
#	define len sizeof(values)/sizeof(double)
	vcount *vc;

	int i, n_modes = get_mode(values, len, &vc);

	printf("got %d modes:\n", n_modes);
	for (i = 0; i < n_modes; i++)
		printf("\tvalue = %g, count = %d\n", vc[i].v, vc[i].c);

	free(vc);
	return 0;
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Test
{
    class Program
    {

        static void Main(string[] args)
        {
            /*
             * We Use Linq To Determine The Mode
             */
            List<int> myList = new List<int>() { 1, 1, 2, 4, 4 };

            var query =     from numbers in myList //select the numbers
                            group numbers by numbers //group them together so we can get the count
                            into groupedNumbers
                            select new { Number = groupedNumbers.Key, Count = groupedNumbers.Count() }; //so we got a query
            //find the max of the occurence of the mode
            int max = query.Max(g => g.Count);
            IEnumerable<int> modes = query.Where(x => x.Count == max).Select(x => x.Number);//match the frequence and select the number
            foreach (var item in modes)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }

    }

}


#include <iterator>
#include <utility>
#include <algorithm>
#include <list>
#include <iostream>

// helper struct
template<typename T> struct referring
{
  referring(T const& t): value(t) {}
  template<typename Iter>
   bool operator()(std::pair<Iter, int> const& p) const
  {
    return *p.first == value;
  }
  T const& value;
};

// requires:
// FwdIterator is a ForwardIterator
// The value_type of FwdIterator is EqualityComparable
// OutIterator is an output iterator
// the value_type of FwdIterator is convertible to the value_type of OutIterator
// [first, last) is a valid range
// provides:
// the mode is written to result
template<typename FwdIterator, typename OutIterator>
 void mode(FwdIterator first, FwdIterator last, OutIterator result)
{
  typedef typename std::iterator_traits<FwdIterator>::value_type value_type;
  typedef std::list<std::pair<FwdIterator, int> > count_type;
  typedef typename count_type::iterator count_iterator;

  // count elements
  count_type counts;

  while (first != last)
  {
    count_iterator element = std::find_if(counts.begin(), counts.end(),
                                          referring<value_type>(*first));
    if (element == counts.end())
      counts.push_back(std::make_pair(first, 1));
    else
      ++element->second;
    ++first;
  }

  // find maximum
  int max = 0;
  for (count_iterator i = counts.begin(); i != counts.end(); ++i)
    if (i->second > max)
      max = i->second;

  // copy corresponding elements to output sequence
  for (count_iterator i = counts.begin(); i != counts.end(); ++i)
    if (i->second == max)
      *result++ = *i->first;
}

// example usage
int main()
{
  int values[] = { 1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6 };
  median(values, values + sizeof(values)/sizeof(int),
         std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;
  return 0;
}


(defn modes [coll]
  (let [distrib (frequencies coll)
        [value freq] [first second] ; name the key/value pairs in the distrib (map) entries
        sorted (sort-by (comp - freq) distrib)
        maxfq (freq (first sorted))]
    (map value (take-while #(= maxfq (freq %)) sorted))))


mode = (arr) ->
  # returns an array with the modes of arr, i.e. the
  # elements that appear most often in arr
  counts = {}
  for elem in arr
    counts[elem] ||= 0
    counts[elem] += 1
  max = 0
  for key, cnt of counts
    max = cnt if cnt > max
  (key for key, cnt of counts when cnt == max)

console.log mode [1, 2, 2, 2, 3, 3, 3, 4, 4]


(defun mode (sequence &rest hash-table-options)
  (let ((frequencies (apply #'make-hash-table hash-table-options)))
    (map nil (lambda (element)
               (incf (gethash element frequencies 0)))
         sequence)
    (let ((modes '())
          (hifreq 0 ))
      (maphash (lambda (element frequency)
                 (cond ((> frequency hifreq)
                        (setf hifreq frequency
                              modes  (list element)))
                       ((= frequency hifreq)
                        (push element modes))))
               frequencies)
      (values modes hifreq))))


import std.stdio, std.algorithm, std.array;

auto mode(T)(T[] items) pure /*nothrow @safe*/ {
    int[T] aa;
    foreach (item; items)
        aa[item]++;
    immutable m = aa.byValue.reduce!max;
    return aa.byKey.filter!(k => aa[k] == m);
}

void main() /*@safe*/ {
    auto data = [1, 2, 3, 1, 2, 4, 2, 5, 3, 3, 1, 3, 6];
    writeln("Mode: ", data.mode);

    data ~= 2;
    writeln("Mode: ", data.mode);
}


program AveragesMode;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.Generics.Collections,
  System.Generics.Defaults;

type
  TCounts = TDictionary<Integer, Integer>;

  TPair = record
    value, count: Integer;
    constructor Create(value, count: Integer);
  end;

  TPairs = TArray<TPair>;

var
  dict: TCounts;
  Pairs: TPairs;
  list: TArray<Integer>;
  i, key, max: Integer;
  p: TPair;

{ TPair }

constructor TPair.Create(value, count: Integer);
begin
  self.value := value;
  self.count := count;
end;

function SortByCount(const left, right: TPair): Integer;
begin
  Result := right.count - left.count;
end;

begin
  list := [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17];
  dict := TCounts.Create;

  for i in list do
  begin
    if dict.ContainsKey(i) then
      dict[i] := dict[i] + 1
    else
    begin
      dict.Add(i, 1);
    end;
  end;

  SetLength(Pairs, dict.Count);
  i := 0;
  for key in dict.Keys do
  begin
    Pairs[i] := TPair.Create(key, dict[key]);
    inc(i);
  end;

  TArray.Sort<TPair>(Pairs, TComparer<TPair>.Construct(SortByCount));

  Writeln('Modes:');
  max := Pairs[0].count;
  for p in Pairs do
    if p.count = max then
      Writeln('   Value: ', p.value, ', Count: ', p.count);

  dict.Free;
  Readln;
end.


pragma.enable("accumulator")
def mode(values) {
    def counts := [].asMap().diverge()
    var maxCount := 0
    for v in values {
        maxCount max= (counts[v] := counts.fetch(v, fn{0}) + 1)
    }
    return accum [].asSet() for v => ==maxCount in counts { _.with(v) }
}


(define (modes L)
	(define G (group* L)) ;; sorts and group equal items
	(define cardmax (for/max [(g G)] (length g)))
	(map first (filter (lambda(g) (= cardmax (length g))) G)))

(modes '( a b c a d e f))
    → (a)
(modes (iota 6))
    → (0 1 2 3 4 5)
(modes '(x))
    → (x)
(modes '(🎾 🏉 ☕ 🎾 🎲 🎯 🎺 ☕ 🎲 🎸 🎻 🏆 ☕ 🏁 🎾 🎲 🎻 🏉 ))
    → (🎾 ☕ 🎲)

(modes '())
😖 error: group : expected list : null 🔎 'modes'


import system'routines;
import system'collections;
import extensions;

extension op
{
    get Mode()
    {
        var countMap := Dictionary.new(0);
        self.forEach:(item)
        {
            countMap[item] := countMap[item] + 1
        };

        countMap := countMap.Values.sort:(p,n => p > n);

        var max := countMap.FirstMember;

        ^ countMap
            .filterBy:(kv => max.equal(kv.Value))
            .selectBy:(kv => kv.Key)
            .toArray()
    }
}

public program()
{
    var array1 := new int[]{1, 1, 2, 4, 4};
    var array2 := new int[]{1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17};
    var array3 := new object[]{1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"};

    console
        .printLine("mode of (",array1.asEnumerable(),") is (",array1.Mode,")")
        .printLine("mode of (",array2.asEnumerable(),") is (",array2.Mode,")")
        .printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")")
        .readChar()
}


defmodule Average do
  def mode(list) do
    gb = Enum.group_by(list, &(&1))
    max = Enum.map(gb, fn {_,val} -> length(val) end) |> Enum.max
    for {key,val} <- gb, length(val)==max, do: key
  end
end

lists = [[3,1,4,1,5,9,2,6,5,3,5,8,9],
         [1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"]]
Enum.each(lists, fn list ->
  IO.puts "mode: #{inspect list}"
  IO.puts "   => #{inspect Average.mode(list)}"
end)


-module( mode ).
-export( [example/0, values/1] ).

example() ->
	Set = [1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"],
	io:fwrite( "In ~p the mode(s) is(are): ~p~n", [Set, values(Set)] ).

values( Set ) ->
	Dict = lists:foldl( fun values_count/2, dict:new(), Set ),
	[X || {X, _Y} <- dict:fold( fun keep_maxs/3, [{0, 0}], Dict )].

keep_maxs( Key, Value, [{_Max_key, Max_value} | _] ) when Value > Max_value ->
	[{Key, Value}];
keep_maxs( Key, Value, [{_Max_key, Max_value} | _]=Maxs ) when Value =:= Max_value ->
	[{Key, Value} | Maxs];
keep_maxs( _Key, _Value, Maxs ) ->
	Maxs.

values_count( Value, Dict ) -> dict:update_counter( Value, 1, Dict ).


PROGRAM MODE_AVG

!$INTEGER

DIM A[10],B[10],Z[10]

PROCEDURE SORT(Z[],P->Z[])
   LOCAL N,FLIPS
   FLIPS=TRUE
   WHILE FLIPS DO
      FLIPS=FALSE
      FOR N=0 TO P-1 DO
        IF Z[N]>Z[N+1] THEN SWAP(Z[N],Z[N+1]) FLIPS=TRUE
      END FOR
   END WHILE
END PROCEDURE

PROCEDURE CALC_MODE(Z[],P->MODES$)
   LOCAL I,OCCURRENCE,MAXOCCURRENCE,OLDVAL
   SORT(Z[],P->Z[])
   OCCURENCE=1
   MAXOCCURENCE=0
   OLDVAL=Z[0]
   MODES$=""
   FOR I=1 TO P DO
       IF Z[I]=OLDVAL THEN
           OCCURENCE=OCCURENCE+1
         ELSE
           IF OCCURENCE>MAXOCCURENCE THEN
                MAXOCCURENCE=OCCURENCE
                MODES$=STR$(OLDVAL)
             ELSIF OCCURENCE=MAXOCCURENCE THEN
                MODES$=MODES$+STR$(OLDVAL)
             ELSE
                !$NULL
           END IF
           OCCURENCE=1
       END IF
       OLDVAL=Z[I]
   END FOR
   !check after loop
   IF OCCURENCE>MAXOCCURENCE THEN
       MAXOCCURENCE=OCCURENCE
       MODES$=STR$(OLDVAL)
   ELSIF OCCURENCE=MAXOCCURENCE THEN
        MODES$=MODES$+STR$(OLDVAL)
   ELSE
       !$NULL
   END IF
END PROCEDURE

BEGIN
   A[]=(1,3,6,6,6,6,7,7,12,12,17)
   B[]=(1,2,4,4,1)
   PRINT("Modes for array A (1,3,6,6,6,6,7,7,12,12,17)";)
   CALC_MODE(A[],10->MODES$)
   PRINT(MODES$)
   PRINT("Modes for array B (1,2,4,4,1)";)
   CALC_MODE(B[],4->MODES$)
   PRINT(MODES$)
END PROGRAM


include misc.e

function mode(sequence s)
    sequence uniques, counts, modes
    integer j,max
    uniques = {}
    counts = {}
    for i = 1 to length(s) do
        j = find(s[i], uniques)
        if j then
            counts[j] += 1
        else
            uniques = append(uniques, s[i])
            counts  = append(counts, 1)
        end if
    end for

    max = counts[1]
    for i = 2 to length(counts) do
        if counts[i] > max then
            max = counts[i]
        end if
    end for

    j = 1
    modes = {}
    while j <= length(s) do
        j = find_from(max, counts, j)
        if j = 0 then
            exit
        end if
        modes = append(modes, uniques[j])
        j += 1
    end while
    return modes
end function

constant s = { 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" }
pretty_print(1,mode(s),{3})


let mode (l:'a seq) =
    l
    |> Seq.countBy (fun item -> item)               // Count individual items
    |> Seq.fold                                     // Find max counts
        (fun (cp, lst) (item, c) ->                 // State is (count, list of items with that count)
            if c > cp then (c, [item])              // New max - keep count and a list of the single item
            elif c = cp then (c, item :: lst)       // New element with max count - prepend it to the list
            else (cp,lst))                          // else just keep old count/list
        (0, [Unchecked.defaultof<'a>])              // Start with a count of 0 and a dummy item
    |> snd                                          // From (count, list) we just want the second item (the list)


program mode_test
  use Qsort_Module only Qsort => sort
  implicit none

  integer, parameter    :: S = 10
  integer, dimension(S) :: a1 = (/ -1, 7, 7, 2, 2, 2, -1, 7, -3, -3 /)
  integer, dimension(S) :: a2 = (/  1, 1, 1, 1, 1, 0, 2, 2, 2, 2 /)
  integer, dimension(S) :: a3 = (/  0, 0, -1, -1, 9, 9, 3, 3, 7, 7 /)

  integer, dimension(S) :: o
  integer               :: l, trash

  print *, stat_mode(a1)

  trash = stat_mode(a1, o, l)
  print *, o(1:l)
  trash = stat_mode(a2, o, l)
  print *, o(1:l)
  trash = stat_mode(a3, o, l)
  print *, o(1:l)

contains

  ! stat_mode returns the lowest (if not unique) mode
  ! others can hold other modes, if the mode is not unique
  ! if others is provided, otherslen should be provided too, and
  ! it says how many other modes are there.
  ! ok can be used to know if the return value has a meaning
  ! or the mode can't be found (void arrays)
  integer function stat_mode(a, others, otherslen, ok)
    integer, dimension(:), intent(in) :: a
    logical, optional, intent(out)    :: ok
    integer, dimension(size(a,1)), optional, intent(out) :: others
    integer, optional, intent(out)    :: otherslen

    ! ta is a copy of a, we sort ta modifying it, freq
    ! holds the frequencies and idx the index (for ta) so that
    ! the value appearing freq(i)-time is ta(idx(i))
    integer, dimension(size(a, 1)) :: ta, freq, idx
    integer                        :: rs, i, tm, ml, tf

    if ( present(ok) ) ok = .false.

    select case ( size(a, 1) )
    case (0)  ! no mode... ok is false
       return
    case (1)
       if ( present(ok) ) ok = .true.
       stat_mode = a(1)
       return
    case default
       if ( present(ok) ) ok = .true.
       ta = a         ! copy the array
       call sort(ta)  ! sort it in place (cfr. sort algos on RC)
       freq = 1
       idx = 0
       rs = 1         ! rs will be the number of different values

       do i = 2, size(ta, 1)
          if ( ta(i-1) == ta(i) ) then
             freq(rs) = freq(rs) + 1
          else
             idx(rs) = i-1
             rs = rs + 1
          end if
       end do
       idx(rs) = i-1

       ml = maxloc(freq(1:rs), 1)  ! index of the max value of freq
       tf = freq(ml)               ! the max frequency
       tm = ta(idx(ml))            ! the value with that freq

       ! if we want all the possible modes, we provide others
       if ( present(others) ) then
          i = 1
          others(1) = tm
          do
             freq(ml) = 0
             ml = maxloc(freq(1:rs), 1)
             if ( tf == freq(ml) ) then ! the same freq
                i = i + 1               ! as the max one
                others(i) = ta(idx(ml))
             else
                exit
             end if
          end do

          if ( present(otherslen) ) then
             otherslen = i
          end if

       end if
       stat_mode = tm
    end select

  end function stat_mode

end program mode_test


' FB 1.05.0 Win64

Sub quicksort(a() As Integer, first As Integer, last As Integer)
  Dim As Integer length = last - first + 1
  If length < 2 Then Return
  Dim pivot As Integer = a(first + length\ 2)
  Dim lft As Integer = first
  Dim rgt As Integer = last
  While lft <= rgt
    While a(lft) < pivot
      lft +=1
    Wend
    While a(rgt) > pivot
      rgt -= 1
    Wend
    If lft <= rgt Then
       Swap a(lft), a(rgt)
       lft += 1
       rgt -= 1
    End If
  Wend
  quicksort(a(), first, rgt)
  quicksort(a(), lft, last)
End Sub

' The modal value(s) is/are stored in 'm'.
' The function returns the modal count.
Function mode(a() As Integer, m() As Integer, sorted As Boolean = false) As Integer
  Dim lb As Integer = LBound(a)
  Dim ub As Integer = UBound(a)
  If ub = -1 Then Return 0 '' empty array
  If Not sorted Then quicksort(a(), lb, ub)
  Dim cValue As Integer = a(lb)
  Dim cCount As Integer = 1
  Dim cMax As Integer = 0
  '' We iterate to the end of the array plus 1 to ensure the
  '' final value is dealt with properly
  For i As Integer = lb + 1 To ub + 1
    If i <= ub AndAlso a(i) = cValue Then
      cCount += 1
    Else
      If cCount > cMax Then
        Erase m
        Redim m(1 To 1)
        m(1) = cValue
        cMax = cCount
      ElseIf cCount = cMax Then
        Redim Preserve m(1 To UBound(m) + 1)
        m(UBound(m)) = cValue
      End If
      If i = ub + 1 Then Exit For
      cValue = a(i)
      cCount = 1
    End If
  Next
  Return cMax
End Function

Dim a(1 To 14) As Integer  = {1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6}
Dim m() As Integer '' to store the mode(s)
Dim mCount As Integer = mode(a(), m())
Print "The following are the modes which occur"; mCount; " times : "
For i As Integer = LBound(m) To UBound(m) : Print m(i); " "; : Next
Print
Print "Press any key to quit"
Sleep


mode := function(v)
  local c, m;
  c := Collected(SortedList(v));
  m := Maximum(List(c, x -> x[2]));
  return List(Filtered(c, x -> x[2] = m), y -> y[1]);
end;

mode([ 7, 5, 6, 1, 5, 5, 7, 12, 17, 6, 6, 5, 12, 3, 6 ]);
# [ 5, 6 ]


package main

import "fmt"

func main() {
    fmt.Println(mode([]int{2, 7, 1, 8, 2}))
    fmt.Println(mode([]int{2, 7, 1, 8, 2, 8}))
}

func mode(a []int) []int {
    m := make(map[int]int)
    for _, v := range a {
        m[v]++
    }
    var mode []int
    var n int
    for k, v := range m {
        switch {
        case v < n:
        case v > n:
            n = v
            mode = append(mode[:0], k)
        default:
            mode = append(mode, k)
        }
    }
    return mode
}


def mode(Iterable col) {
    assert col
    def m = [:]
    col.each {
        m[it] = m[it] == null ? 1 : m[it] + 1
    }
    def keys = m.keySet().sort { -m[it] }
    keys.findAll { m[it] == m[keys[0]] }
}


import Prelude (foldr, maximum, (==), (+))
import Data.Map (insertWith', empty, filter, elems, keys)

mode :: (Ord a) => [a] -> [a]
mode xs = keys (filter (== maximum (elems counts)) counts)
  where counts = foldr (\x -> insertWith' (+) x 1) empty xs


procedure main(args)
    every write(!mode(args))
end

procedure mode(A)
    hist := table(0)
    every hist[!A] +:= 1
    hist := sort(hist, 2)
    modeCnt := hist[*hist][2]
    every modeP := hist[*hist to 1 by -1] do {
        if modeCnt = modeP[2] then suspend modeP[1]
        else fail
        }
end


import java.util.*;

public class Mode {
    public static <T> List<T> mode(List<? extends T> coll) {
        Map<T, Integer> seen = new HashMap<T, Integer>();
        int max = 0;
        List<T> maxElems = new ArrayList<T>();
        for (T value : coll) {
            if (seen.containsKey(value))
                seen.put(value, seen.get(value) + 1);
            else
                seen.put(value, 1);
            if (seen.get(value) > max) {
                max = seen.get(value);
                maxElems.clear();
                maxElems.add(value);
            } else if (seen.get(value) == max) {
                maxElems.add(value);
            }
        }
        return maxElems;
    }

    public static void main(String[] args) {
        System.out.println(mode(Arrays.asList(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17))); // prints [6]
        System.out.println(mode(Arrays.asList(1, 1, 2, 4, 4))); // prints [1, 4]
    }
}


function mode(ary) {
    var counter = {};
    var mode = [];
    var max = 0;
    for (var i in ary) {
        if (!(ary[i] in counter))
            counter[ary[i]] = 0;
        counter[ary[i]]++;

        if (counter[ary[i]] == max)
            mode.push(ary[i]);
        else if (counter[ary[i]] > max) {
            max = counter[ary[i]];
            mode = [ary[i]];
        }
    }
    return mode;
}

mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]);  // [6]
mode([1, 2, 4, 4, 1]);  // [1,4]


# modes/0 produces an array of [value, count]
# in increasing order of count:
def modes:
  sort | reduce .[] as $i ([];
    # state variable is an array of [value, count]
    if length == 0 then [ [$i, 1] ]
    elif .[-1][0] == $i then setpath([-1,1]; .[-1][1] + 1)
    else . + [[$i,1]]
    end )
    | sort_by( .[1] );

# mode/0 outputs a stream of the modal values;
# if the input array is empty, the output stream is also empty.
def mode:
  if length == 0 then empty
  else modes as $modes
       | $modes[-1][1] as $count
       | $modes[] | select( .[1] == $count) | .[0]
   end;


function modes(values)
    dict = Dict() # Values => Number of repetitions
    modesArray = typeof(values[1])[] # Array of the modes so far
    max = 0 # Max of repetitions so far

    for v in values
        # Add one to the dict[v] entry (create one if none)
        if v in keys(dict)
            dict[v] += 1
        else
            dict[v] = 1
        end

        # Update modesArray if the number of repetitions
        # of v reaches or surpasses the max value
        if dict[v] >= max
            if dict[v] > max
                empty!(modesArray)
                max += 1
            end
            append!(modesArray, [v])
        end
    end

    return modesArray
end

println(modes([1,3,6,6,6,6,7,7,12,12,17]))
println(modes((1,1,2,4,4)))


fun <T> modeOf(a: Array<T>) {
    val sortedByFreq = a.groupBy { it }.entries.sortedByDescending { it.value.size }
    val maxFreq = sortedByFreq.first().value.size
    val modes = sortedByFreq.takeWhile { it.value.size == maxFreq }
    if (modes.size == 1)
       println("The mode of the collection is ${modes.first().key} which has a frequency of $maxFreq")
    else {
       print("There are ${modes.size} modes with a frequency of $maxFreq, namely : ")
       println(modes.map { it.key }.joinToString(", "))
    }
}

fun main(args: Array<String>) {
    val a = arrayOf(7, 1, 1, 6, 2, 4, 2, 4, 2, 1, 5)
    println("[" + a.joinToString(", ") + "]")
    modeOf(a)
    println()
    val b = arrayOf(true, false, true, false, true, true)
    println("[" + b.joinToString(", ") + "]")
    modeOf(b)
}


define getmode(a::array)::array => {
	local(mmap = map, maxv = 0, modes = array)
	// store counts
	with e in #a do => { #mmap->keys >> #e ? #mmap->find(#e) += 1 | #mmap->insert(#e = 1) }
	// get max value
	with e in #mmap->keys do => { #mmap->find(#e) > #maxv ? #maxv = #mmap->find(#e) }
	// get modes with max value
	with e in #mmap->keys where #mmap->find(#e) == #maxv do => { #modes->insert(#e) }
	return #modes
}
getmode(array(1,3,6,6,6,6,7,7,12,12,17))
getmode(array(1,3,6,3,4,8,9,1,2,3,2,2))


a$ = "1 3 6 6 6 6 7 7 12 12 17"
b$ = "1 2 4 4 1"

print "Modes for ";a$
print modes$(a$)
print "Modes for ";b$
print modes$(b$)

function modes$(a$)
'get array size
    n=0
    t$ = "*"
    while t$<>""
        n=n+1
        t$=word$(a$, n)
        'print n, t$
    wend
    n=n-1
    'print "n=", n
'dim array
'read in array
    redim a(n)
    for i = 1 to n
        a(i)=val(word$(a$, i))
        'print i, a(i)
    next
'sort
    sort a(), 1, n
'get the modes
    occurence = 1
    maxOccurence = 0
    oldVal = a(1)
    modes$ = ""
    for i = 2 to n
        'print i, a(i)
        if a(i) = oldVal then
            occurence = occurence + 1
        else
            select case
            case occurence >  maxOccurence
                 maxOccurence = occurence
                 modes$ = oldVal; " "
            case occurence = maxOccurence
                modes$ =  modes$; oldVal; " "
            end select
            occurence = 1
        end if
         oldVal = a(i)
    next
    'check after loop
    select case
    case occurence >  maxOccurence
        maxOccurence = occurence
        modes$ = oldVal; " "
    case occurence = maxOccurence
        modes$ =  modes$; oldVal; " "
    end select
end function


function mode(tbl) -- returns table of modes and count
	assert(type(tbl) == 'table')
	local counts = { }
	for _, val in pairs(tbl) do
		-- see http://lua-users.org/wiki/TernaryOperator
		counts[val] = counts[val] and counts[val] + 1 or 1
	end
	local modes = { }
	local modeCount = 0
	for key, val in pairs(counts) do
		if val > modeCount then
			modeCount = val
			modes = {key}
		elseif val == modeCount then
			table.insert(modes, key)
		end
	end
	return modes, modeCount
end

modes, count = mode({1,3,6,6,6,6,7,7,12,12,17})
for _, val in pairs(modes) do io.write(val..' ') end
print("occur(s) ", count, " times")

modes, count = mode({'a', 'a', 'b', 'd', 'd'})
for _, val in pairs(modes) do io.write(val..' ') end
print("occur(s) ", count, " times")


Module Checkit {
      \\ find mode
      Function GetMode {
            Inventory  N
            Inventory ALLMODES
            m=1
            While not empty {
                 if islet then  {
                       Read A$
                        if Exist(N, A$) then  {
                             k=Eval(N)
                             k++
                             if m=k then  {
                                  Append ALLMODES, A$
                             }
                             if m<k then  m=k : Clear ALLMODES : Append ALLMODES, A$
                             return N, A$:=k
                        }  Else Append N, A$:=1 : if m=1 then Append ALLMODES, A$

                  } else {
                        Read A
                        if Exist(N, A) then  {
                             k=Eval(N)
                             k++
                             if m=k then  {
                                  Append ALLMODES, A
                             }
                             if m<k then  m=k : Clear ALLMODES : Append ALLMODES, A
                             return N, A:=k
                        }  Else Append N, A:=1 : if m=1 then Append ALLMODES, A
                  }
             }
             =ALLMODES
      }
      Print GetMode(1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6) ' print 2 3
      Dim A()
      A()=(1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6)
      \\ get a pointer from A
      m=A()
      Print GetMode(!m) ' print 2 3
      z=stack:=1, 2,"B", 3, 1, 2, "B", 4, 2, 5,"B", 2, 3, 3, 1, 3, 6, "B"
      Print GetMode(!z)   ' print 2 3 B
}
Checkit


function modeValue = findmode(setOfValues)
   modeValue = mode(setOfValues);
end


MODE(X)
 ;X is assumed to be a list of numbers separated by "^"
 ;I is a loop index
 ;L is the length of X
 ;Y is a new array
 ;ML is the list of modes
 ;LOC is a placeholder to shorten the statement
 Q:'$DATA(X) "No data"
 Q:X="" "Empty Set"
 NEW Y,I,L,LOC
 SET L=$LENGTH(X,"^"),ML=""
 FOR I=1:1:L SET LOC=+$P(X,"^",I),Y(LOC)=$S($DATA(Y(LOC)):Y(LOC)+1,1:1)
 SET I="",I=$O(Y(I)),ML=I ;Prime the pump, rather than test for no data
 FOR  S I=$O(Y(I)) Q:I=""  S ML=$SELECT(Y($P(ML,"^"))>Y(I):ML,Y($P(ML,"^"))<Y(I):I,Y($P(ML,"^"))=Y(I):ML_"^"_I)
 QUIT ML


/* NetRexx */
options replace format comments java crossref symbols nobinary

run_samples()
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method mode(lvector = java.util.List) public static returns java.util.List
  seen    = 0
  modes   = ''
  modeMax = 0
  loop v_ = 0 to lvector.size() - 1
    mv = Rexx lvector.get(v_)
    seen[mv] = seen[mv] + 1
    select
      when seen[mv] > modeMax then do
        modeMax = seen[mv]
        modes = ''
        nx = 1
        modes[0]  = nx
        modes[nx] = mv
        end
      when seen[mv] = modeMax then do
        nx = modes[0] + 1
        modes[0]  = nx
        modes[nx] = mv
        end
      otherwise do
        nop
        end
      end
    end v_

  modeList = ArrayList(modes[0])
  loop v_ = 1 to modes[0]
    val = modes[v_]
    modeList.add(val)
    end v_

  return modeList

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method mode(rvector = Rexx[]) public static returns java.util.List
  return mode(ArrayList(Arrays.asList(rvector)))

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method show_mode(lvector = java.util.List) public static returns java.util.List
  modes = mode(lvector)
  say 'Vector:' (Rexx lvector).space(0)', Mode(s):' (Rexx modes).space(0)
  return modes

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method show_mode(rvector = Rexx[]) public static returns java.util.List
  return show_mode(ArrayList(Arrays.asList(rvector)))

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method run_samples() public static
  show_mode([Rexx 10, 9, 8, 7, 6, 5, 4, 3, 2, 1])                                   -- 10 9 8 7 6 5 4 3 2 1
  show_mode([Rexx 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11])                 -- 0
  show_mode([Rexx 30, 10, 20, 30, 40, 50, -100, 4.7, -11e+2])                       -- 30
  show_mode([Rexx 30, 10, 20, 30, 40, 50, -100, 4.7, -11e+2, -11e+2])               -- 30 -11e2
  show_mode([Rexx 1, 8, 6, 0, 1, 9, 4, 6, 1, 9, 9, 9])                              -- 9
  show_mode([Rexx 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])                               -- 1 2 3 4 5 6 7 8 9 10 11
  show_mode([Rexx 8, 8, 8, 2, 2, 2])                                                -- 8 2
  show_mode([Rexx 'cat', 'kat', 'Cat', 'emu', 'emu', 'Kat'])                        -- emu
  show_mode([Rexx 0, 1, 2, 3, 3, 3, 4, 4, 4, 4, 1, 0])                              -- 4
  show_mode([Rexx 2, 7, 1, 8, 2])                                                   -- 2
  show_mode([Rexx 2, 7, 1, 8, 2, 8])                                                -- 8 2
  show_mode([Rexx 'E', 'n', 'z', 'y', 'k', 'l', 'o', 'p', 'ä', 'd', 'i', 'e'])      -- E n z y k l o p ä d i e
  show_mode([Rexx 'E', 'n', 'z', 'y', 'k', 'l', 'o', 'p', 'ä', 'd', 'i', 'e', 'ä']) -- ä
  show_mode([Rexx 3, 1, 4, 1, 5, 9, 7, 6])                                          -- 1
  show_mode([Rexx 3, 1, 4, 1, 5, 9, 7, 6, 3])                                       -- 3, 1
  show_mode([Rexx 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])                              -- 6
  show_mode([Rexx 1, 1, 2, 4, 4])                                                   -- 4 1
  return


import tables

proc modes[T](xs: openArray[T]): T =
  var count = initCountTable[T]()
  for x in xs:
    count.inc(x)
  largest(count).key

echo modes(@[1,3,6,6,6,6,7,7,12,12,17])
echo modes(@[1,1,2,4,4])


MODULE Mode;
IMPORT
  Object:Boxed,
  ADT:Dictionary,
  ADT:LinkedList,
  Out := NPCT:Console;

TYPE
  Key = Boxed.LongInt;
  Val = Boxed.LongInt;

VAR
  x: ARRAY 11 OF LONGINT;
  y: ARRAY 5 OF LONGINT;
  z: ARRAY 8 OF LONGINT;

  PROCEDURE Show(ll: LinkedList.LinkedList(Key));
  VAR
    iter: LinkedList.Iterator(Key);
    i: LONGINT;
    k: Key;
  BEGIN
    iter := ll.GetIterator(NIL);
    FOR i := 0 TO ll.Size() - 1 DO;
      k := iter.Next();
      Out.Int(k.value,0);Out.Ln;
    END;
  END Show;

  PROCEDURE Mode(x: ARRAY OF LONGINT): LinkedList.LinkedList(Key);
  VAR
    d: Dictionary.Dictionary(Key,Val);
    i: LONGINT;
    k: Key; v: Val;
    iter: Dictionary.IterKeys(Key,Val);
    resp: LinkedList.LinkedList(Key);
    max: Boxed.LongInt;
  BEGIN
    d := NEW(Dictionary.Dictionary(Key,Val));
    FOR i := 0 TO LEN(x) - 1 DO
      k := NEW(Key,x[i]);
      IF d.Lookup(k,v) THEN
        d.Set(k,NEW(Val,v.value + 1));
      ELSE
        d.Set(k,NEW(Val,1))
      END
    END;

    max := NEW(Boxed.LongInt,0);
    resp := NEW(LinkedList.LinkedList(Key));
    iter := d.IterKeys();
    WHILE (iter.Next(k)) DO
      v := d.Get(k);
      IF v.Cmp(max) > 0 THEN
        resp.Clear();
        resp.Append(k);max := v
      ELSIF v.Cmp(max) = 0 THEN
        resp.Append(k);max := v
      END
    END;

    RETURN resp

  END Mode;

BEGIN
  x[0] := 1; x[1] := 3; x[2] := 6; x[3] := 6;
  x[4] := 6; x[5] := 6; x[6] := 7; x[7] := 7;
  x[8] := 12; x[9] := 12; x[10] := 17;
  Show(Mode(x));Out.Ln;
  y[0] := 1; y[1] := 2; y[2] := 4; y[3] := 4; y[4] := 1;
  Show(Mode(y));Out.Ln;
  z[0] := 1; z[1] := 2; z[2] := 4; z[3] := 4; z[4] := 1; z[5] := 5; z[6] := 5; z[7] := 5;
  Show(Mode(z));Out.Ln;
END Mode.


use Collection;

class Mode {
  function : Main(args : String[]) ~ Nil {
    Print(Mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]));
    Print(Mode([1, 2, 4, 4, 1]));
  }

  function : Mode(coll : Int[]) ~ IntVector {
    seen := IntMap->New();
    max := 0;
    maxElems := IntVector->New();

    each(i : coll) {
      value := coll[i];

      featched := seen->Find(value)->As(IntHolder);
      if(featched <> Nil) {
        seen->Remove(value);
        seen->Insert(value, IntHolder->New(featched->Get() + 1));
      }
      else {
        seen->Insert(value, IntHolder->New(1));
      };

      featched := seen->Find(value)->As(IntHolder);
      if(featched->Get() > max) {
        max := featched->Get();
        maxElems->Empty();
        maxElems->AddBack(value);
      }
      else if(featched->Get() = max) {
        maxElems->AddBack(value);
      };
    };

    return maxElems;
  }

  function : Print(out : IntVector) ~ Nil {
    '['->Print();
    each(i : out) {
      out->Get(i)->Print();
      if(i + 1 < out->Size()) {
        ", "->Print();
      };
    };
    ']'->PrintLine();
  }
}


#import <Foundation/Foundation.h>

@interface NSArray (Mode)
- (NSArray *)mode;
@end

@implementation NSArray (Mode)
- (NSArray *)mode {
    NSCountedSet *seen = [NSCountedSet setWithArray:self];
    int max = 0;
    NSMutableArray *maxElems = [NSMutableArray array];
    for ( obj in seen ) {
        int count = [seen countForObject:obj];
        if (count > max) {
            max = count;
            [maxElems removeAllObjects];
            [maxElems addObject:obj];
        } else if (count == max) {
            [maxElems addObject:obj];
        }
    }
    return maxElems;
}
@end


let mode lst =
  let seen = Hashtbl.create 42 in
    List.iter (fun x ->
                 let old = if Hashtbl.mem seen x then
                   Hashtbl.find seen x
                 else 0 in
                   Hashtbl.replace seen x (old + 1))
      lst;
    let best = Hashtbl.fold (fun _ -> max) seen 0 in
      Hashtbl.fold (fun k v acc ->
                      if v = best then k :: acc
                      else acc)
        seen []


function m = mode2(v)
  sv = sort(v);
  % build two vectors, vals and c, so that
  % c(i) holds how many times vals(i) appears
  i = 1; c = []; vals = [];
  while (i <= numel(v) )
    tc = sum(sv==sv(i)); % it would be faster to count
                         % them "by hand", since sv is sorted...
    c = [c, tc];
    vals = [vals, sv(i)];
    i += tc;
  endwhile
  % stack vals and c building a 2-rows matrix x
  x = cat(1,vals,c);
  % sort the second row (frequencies) into t (most frequent
  % first) and take the "original indices" i ...
  [t, i] = sort(x(2,:), "descend");
  % ... so that we can use them to sort columns according
  % to frequencies
  nv = x(1,i);
  % at last, collect into m (the result) all the values
  % having the same bigger frequency
  r = t(1); i = 1;
  m = [];
  while ( t(i) == r )
    m = [m, nv(i)];
    i++;
  endwhile
endfunction


-- will work with just about any collection...
call testMode .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testMode .list~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testMode .queue~of(30, 10, 20, 30, 40, 50, -100, 4.7, -11e2)

::routine testMode
  use arg list
  say "list =" list~makearray~toString("l", ", ")
  say "mode =" mode(list)
  say

::routine mode
  use arg list

  -- this is a good application for a bag
  -- add all of the items to the bag
  collector = .bag~new
  collector~putAll(list)
  -- now get a list of unique items
  indexes = .set~new~~putall(collector)
  count = 0    -- this is used to keep track of the maximums
  -- now see how many of each element we ended up with
  loop index over indexes
      items = collector~allat(index)
      newCount = items~items
      if newCount > count then do
          mode = items[1]
          count = newCount
      end
  end

  return mode


declare
  fun {Mode Xs}
     Freq = {Dictionary.new}
     for X in Xs do
        Freq.X := {CondSelect Freq X 0} + 1
     end
     MaxCount = {FoldL {Dictionary.items Freq} Max 0}
  in
     for Value#Count in {Dictionary.entries Freq} collect:C do
        if Count == MaxCount then
  	 {C Value}
        end
     end
  end
in
  {Show {Mode [1 2 3 3 2 1 1]}}
  {Show {Mode [1 2 3 3 2 1]}}


mode(v)={
  my(count=1,r=1,b=v[1]);
  v=vecsort(v);
  for(i=2,#v,
    if(v[i]==v[i-1],
      count++
    ,
      if(count>r,
        r=count;
        b=v[i-1]
      );
      count=1
    )
  );
  if(count>r,v[#v],b)
};


use strict;
use List::Util qw(max);

sub mode
{
    my %c;
    foreach my $e ( @_ ) {
	$c{$e}++;
    }
    my $best = max(values %c);
    return grep { $c{$_} == $best } keys %c;
}


function mode(sequence s)
-- returns a list of the most common values, each of which occurs the same number of times
    integer nxt = 1, count = 1, maxc = 1
    sequence res = {}
    if length(s)!=0 then
        s = sort(s)
        object prev = s[1]
        for i=2 to length(s) do
            if s[i]!=prev then
                s[nxt] = {count,prev}
                nxt += 1
                prev = s[i]
                count = 1
            else
                count += 1
                if count>maxc then
                    maxc = count
                end if
            end if
        end for
        s[nxt] = {count,prev}
        res = ""
        for i=1 to nxt do
            if s[i][1]=maxc then
                res = append(res,s[i][2])
            end if
        end for
    end if
    return res
end function

?mode({1, 2, 5, -5, -9.5, 3.14159})
?mode({ 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" })
?mode({1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6})
?mode({.2, .7, .1, .8, .2})
?mode({"two", 7, 1, 8, "two", 8})
?mode("Hello there world")
?mode({})
{} = wait_key()


<?php
function mode($arr) {
    $count = array_count_values($arr);
    $best = max($count);
    return array_keys($count, $best);
}

print_r(mode(array(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
print_r(mode(array(1, 1, 2, 4, 4)));
?>


(de modes (Lst)
   (let A NIL
      (for X Lst
         (accu 'A X 1) )
      (mapcar car
         (maxi cdar
            (by cdr group A) ) ) ) )


av: procedure options (main);  /* 28 October 2013 */
   declare x(10) fixed binary static initial (1, 4, 2, 6, 2, 5, 6, 2, 4, 2);
   declare f(32767) fixed binary;
   declare (j, n, max, value) fixed binary;
   declare i fixed;

   n = hbound(x,1);

   do i = 1 to n;
      j = x(i);
      f(j) = f(j) + 1;
   end;
   max = 0;
   do i = 1 to hbound(f,1);
      if max < f(i) then do; max = f(i); value = i; end;
   end;
   put list ('The mode value is ' || value || ' occurred ' ||
             max || ' times.');

end av;


$data = @(1,1,1,2,3,4,5,5,6,7,7,7)
$groups = $data | group-object | sort-object count -Descending
$groups | ? {$_.Count -eq $groups[0].Count}


Procedure mean(Array InArray(1))

  Structure MyMean
    Value.i
    Cnt.i
  EndStructure

  Protected i, max, found
  Protected NewList MyDatas.MyMean()

  Repeat
    found=#False
    ForEach MyDatas()
      If InArray(i)=MyDatas()\Value
        MyDatas()\Cnt+1
        found=#True
        Break
      EndIf
    Next
    If Not found
      AddElement(MyDatas())
      MyDatas()\Value=InArray(i)
      MyDatas()\cnt+1
    EndIf
    If MyDatas()\Cnt>max
      max=MyDatas()\Cnt
    EndIf
    i+1
  Until i>ArraySize(InArray())

  ForEach MyDatas()
    If MyDatas()\Cnt=max
      For i=1 To max
        Print(Str(MyDatas()\Value)+" ")
      Next
    EndIf
  Next
EndProcedure


>>> from collections import defaultdict
>>> def modes(values):
	count = defaultdict(int)
	for v in values:
		count[v] +=1
	best = max(count.values())
	return [k for k,v in count.items() if v == best]

>>> modes([1,3,6,6,6,6,7,7,12,12,17])
[6]
>>> modes((1,1,2,4,4))
[1, 4]


mode:{(key x) where value x=max x} count each group @


  [ sort
    [] [] rot
    dup 0 peek temp put
    witheach
      [ dup temp share = iff
          join
        else
          [ dup temp replace
            dip [ nested join ]
            [] join ] ]
     nested join
     temp release ]                is bunch  ( [ --> [ )

  [ sortwith [ size dip size < ]
    [] swap
    dup 0 peek size temp put
    witheach
      [ dup size temp share = iff
          [ nested join ]
        else
          [ drop conclude ] ]
     temp release
     [] swap
     witheach
       [ 0 peek join ] ]          is largest ( [ --> [ )

  [ bunch largest ]               is mode    ( [ --> [ )

  ' [ 1 3 5 7 3 1 3 7 7 3 3 ] mode echo cr
  ' [ 7 13 5 13 7 2 7 10 13 ] mode echo cr
  ' [ 5 ]                     mode echo cr


statmode <- function(v) {
  a <- sort(table(v), decreasing=TRUE)
  r <- c()
  for(i in 1:length(a)) {
    if ( a[[1]] == a[[i]] ) {
      r <- c(r, as.integer(names(a)[i]))
    } else break; # since it's sorted, once we find
                  # a different value, we can stop
  }
  r
}

print(statmode(c(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)))
print(statmode(c(1, 1, 2, 4, 4)))


#lang racket

(define (mode seq)
  (define frequencies (make-hash))
  (for ([s seq])
    (hash-update! frequencies
                  s
                  (lambda (freq) (add1 freq))
                  0))
  (for/fold ([ms null]
             [freq 0])
            ([(k v) (in-hash frequencies)])
    (cond [(> v freq)
           (values (list k) v)]
          [(= v freq)
           (values (cons k ms) freq)]
          [else
           (values ms freq)])))


sub mode (*@a) {
    my %counts := @a.Bag;
    my $max = %counts.values.max;
    %counts.grep(*.value == $max).map(*.key);
}

# Testing with arrays:
say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
say mode [1, 1, 2, 4, 4];


/*REXX program finds the   mode   (most occurring element)  of a  vector.               */
/*      ════════vector═══════════      ═══show vector═══    ═════show result═════       */
      v= 1 8 6 0 1 9 4 6 1 9 9 9    ;   say 'vector='v;      say 'mode='mode(v);       say
      v= 1 2 3 4 5 6 7 8 9 11 10    ;   say 'vector='v;      say 'mode='mode(v);       say
      v= 8 8 8 2 2 2                ;   say 'vector='v;      say 'mode='mode(v);       say
      v='cat kat Cat emu emu Kat'   ;   say 'vector='v;      say 'mode='mode(v);       say
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sort: procedure expose @.;  parse arg # 1 h      /* [↓]  this is an  exchange sort.     */
           do  while h>1;                h=h%2   /*In REXX,   %    is an integer divide.*/
             do i=1  for #-h;     j=i;   k=h+i   /* [↓]  perform exchange for elements. */
               do  while @.k<@.j & h<j;  [email protected].j;   @.[email protected].k;   @.k=_;   j=j-h;  k=k-h;   end
             end   /*i*/
           end     /*while h>1*/;        return
/*──────────────────────────────────────────────────────────────────────────────────────*/
mode: procedure expose @.; parse arg x;  freq=1  /*function finds the  MODE  of a vector*/
      #=words(x)                                 /*#:  the number of elements in vector.*/
           do k=1  for #;  @.k=word(x,k);  end   /* ◄──── make an array from the vector.*/
      call Sort  #                               /*sort the elements in the array.      */
      [email protected].1                                      /*assume the first element is the mode.*/
               do j=1  for #;        _=j-freq    /*traipse through the elements in array*/
               if @.[email protected]._  then do; freq=freq+1 /*is this element the same as previous?*/
                                     [email protected].j       /*this element is the mode (···so far).*/
                                 end
               end   /*j*/
      return ?                                   /*return the mode of vector to invoker.*/


# Project : Averages/Mode

a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]
b = [1, 2, 4, 4, 1]
amodes = list(12)
see "mode(s) of a() = " + nl
for i1 = 1 to modes(a,amodes)
     see "" + amodes[i1] + " "
next
see nl
see "mode(s) of b() = " + nl
for i1 = 1 to modes(b,amodes)
     see "" + amodes [i1]  + " "
next
see nl

func modes(a,amodes)
       max = 0
       n = len(a)
       if n = 0
          amodes[1] = a[1]
          return 1
       ok
       c = list(n)
       for i = 1 to n
            for j = i+1 to n
                 if a[i] = a[j]
                    c[i] = c[i] + 1
                 ok
            next
            if c[i] > max
               max = c[i]
            ok
        next
        j = 0
        for i = 1 to n
             if c[i] = max
                j = j + 1
                amodes[j] = a[i]
             ok
        next
        return j


def mode(ary)
  seen = Hash.new(0)
  ary.each {|value| seen[value] += 1}
  max = seen.values.max
  seen.find_all {|key,value| value == max}.map {|key,value| key}
end

def mode_one_pass(ary)
  seen = Hash.new(0)
  max = 0
  max_elems = []
  ary.each do |value|
    seen[value] += 1
    if seen[value] > max
      max = seen[value]
      max_elems = [value]
    elsif seen[value] == max
      max_elems << value
    end
  end
  max_elems
end

p mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])  # => [6]
p mode([1, 1, 2, 4, 4]) # => [1, 4]
p mode_one_pass([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])  # => [6]
p mode_one_pass([1, 1, 2, 4, 4]) # => [1, 4]


use std::collections::HashMap;

fn main() {
    let mode_vec1 = mode(vec![ 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]);
    let mode_vec2 = mode(vec![ 1, 1, 2, 4, 4]);

    println!("Mode of vec1 is: {:?}", mode_vec1);
    println!("Mode of vec2 is: {:?}", mode_vec2);

    assert!( mode_vec1 == [6], "Error in mode calculation");
    assert!( (mode_vec2 == [1, 4]) || (mode_vec2 == [4,1]), "Error in mode calculation" );
}

fn mode(vs: Vec<i32>) -> Vec<i32> {
    let mut vec_mode = Vec::new();
    let mut seen_map = HashMap::new();
    let mut max_val = 0;
    for i in vs{
        let ctr = seen_map.entry(i).or_insert(0);
        *ctr += 1;
        if *ctr > max_val{
            max_val = *ctr;
        }
    }
    for (key, val) in seen_map {
        if val == max_val{
            vec_mode.push(key);
        }
    }
    vec_mode
}


private variable mx, mxkey, modedat;

define find_max(key) {
  if (modedat[key] > mx) {
    mx = modedat[key];
    mxkey = {key};
  }
  else if (modedat[key] == mx) {
    list_append(mxkey, key);
  }
}

define find_mode(indat)
{
  % reset [file/module-scope] globals:
  mx = 0, mxkey = {}, modedat = Assoc_Type[Int_Type, 0];

  foreach $1 (indat)
    modedat[string($1)]++;

  array_map(Void_Type, &find_max, assoc_get_keys(modedat));

  if (length(mxkey) > 1) {
    $2 = 0;
    () = printf("{");
    foreach $1 (mxkey) {
      () = printf("%s%s", $2 ? ", " : "", $1);
      $2 = 1;
    }
    () = printf("} each have ");
  }
  else
    () = printf("%s has ", mxkey[0], mx);
  () = printf("the most entries (%d).\n", mx);
}

find_mode({"Hungadunga", "Hungadunga", "Hungadunga", "Hungadunga", "McCormick"});

find_mode({"foo", "2.3", "bar", "foo", "foobar", "quality", 2.3, "strnen"});


import scala.collection.breakOut
import scala.collection.generic.CanBuildFrom
def mode
  [T, CC[X] <: Seq[X]](coll: CC[T])
  (implicit o: T => Ordered[T], cbf: CanBuildFrom[Nothing, T, CC[T]])
  : CC[T] = {
  val grouped = coll.groupBy(x => x).mapValues(_.size).toSeq
  val max = grouped.map(_._2).max
  grouped.filter(_._2 == max).map(_._1)(breakOut)
}


(define (mode collection)
    (define (helper collection counts)
        (if (null? collection)
            counts
            (helper (remove (car collection) collection)
                    (cons (cons (car collection)
                                (appearances (car collection) collection)) counts))))
    (map car
         (filter (lambda (x) (= (cdr x) (apply max (map cdr (helper collection '())))))
                 (helper collection '())))


$ include "seed7_05.s7i";

const proc: createModeFunction (in type: elemType) is func
  begin

    const func array elemType: mode (in array elemType: data) is func
      result
        var array elemType: maxElems is 0 times elemType.value;
      local
        var hash [elemType] integer: counts is (hash [elemType] integer).value;
        var elemType: aValue is elemType.value;
        var integer: maximum is 0;
      begin
        for aValue range data do
          if aValue in counts then
            incr(counts[aValue]);
          else
            counts @:= [aValue] 1;
          end if;
          if counts[aValue] > maximum then
            maximum := counts[aValue];
            maxElems := [] (aValue);
          elsif counts[aValue] = maximum then
            maxElems &:= aValue;
          end if;
        end for;
      end func;

    const func string: str (in array elemType: data) is func
      result
        var string: stri is "";
      local
        var elemType: anElement is elemType.value;
      begin
        for anElement range data do
          stri &:= " " & str(anElement);
        end for;
        stri := stri[2 ..];
      end func;

      enable_output(array elemType);

  end func;

createModeFunction(integer);

const proc: main is func
  begin
    writeln(mode([] (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17)));
    writeln(mode([] (1, 1, 2, 4, 4)));
  end func;


func mode(array) {
    var c = Hash.new;
    array.each{|i| c{i} := 0 ++};
    var max = c.values.max;
    c.keys.grep{|i| c{i} == max};
}


[email protected](Sequence traits) mode
[| sortedCounts |
  sortedCounts: (s as: Bag) sortedCounts.
  (sortedCounts mapSelect: [| :count :elem | sortedCounts last count = count]) valueSet
].


OrderedCollection extend [
  mode [ |s|
     s := self asBag sortedByCount.
     ^ (s select: [ :k | ((s at: 1) key) = (k key) ]) collect: [:k| k value]
  ]
].

#( 1 3 6 6 6 6 7 7 12 12 17 ) asOrderedCollection
    mode displayNl.
#( 1 1 2 4 4) asOrderedCollection
    mode displayNl.