Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding local mins in an array

Tags:

algorithm

f#

Is there a easy way to determine the local min and maxes of an array of values. For example

Element Value   Note
1         1 
2         3 
3         5 
4         6 
5         7       max
5         5 
6         4       min
7         6 
8         9 
9         10      max
10        8 
11        7 
12        5      min
13        10    

so an array that is defined like:

let arr = [|1;3;5;6;7;5;4;6;9;10;8;7;5;10|]

would identify

mins  = [|4;5|]

and

maxs  = [|7;10|]

It could be a list or Sequence as well as an array. Two questions

  1. Is there any faciliities in F# that that lend themselves to this task
  2. Is there a common algorithm for determining either the mins or maxs or both?
  3. If writing from scratch should it be approached functionally or imperatively?

Thx

like image 817
akaphenom Avatar asked Oct 06 '10 01:10

akaphenom


1 Answers

This looks like a job for... Seq.windowed! <cue superhero music>

let arr = [|1;3;5;6;7;5;4;6;9;10;8;7;5;10|] 

let _,mins,maxs = 
    arr |> Seq.windowed 3 |> Seq.fold (fun (i,mins,maxs) [|a;b;c|] -> 
    if a>b&&b<c then   (i+1, i::mins,    maxs)
    elif a<b&&b>c then (i+1,    mins, i::maxs)
    else               (i+1,    mins,    maxs)) (1,[],[])

arr |> Seq.iteri (fun i x -> printfn "%2d: %2d" i x)
printfn "mins %A" mins
printfn "maxs %A" maxs
(*
 0:  1
 1:  3
 2:  5
 3:  6
 4:  7
 5:  5
 6:  4
 7:  6
 8:  9
 9: 10
10:  8
11:  7
12:  5
13: 10
mins [12; 6]
maxs [9; 4]
*)
like image 175
Brian Avatar answered Oct 12 '22 23:10

Brian