查找阵列中的本地分钟

aka*_*nom 6 algorithm f#

有没有一种简单的方法来确定值数组的局部最小值和最大值.例如

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    
Run Code Online (Sandbox Code Playgroud)

所以定义的数组如下:

let arr = [|1;3;5;6;7;5;4;6;9;10;8;7;5;10|]
Run Code Online (Sandbox Code Playgroud)

会识别

mins  = [|4;5|]
Run Code Online (Sandbox Code Playgroud)

maxs  = [|7;10|]
Run Code Online (Sandbox Code Playgroud)

它可以是列表或序列以及数组.两个问题

  1. F#中是否有任何有助于完成此任务的设施
  2. 是否有一个通用的算法来确定分钟或最大值或两者?
  3. 如果从头开始写作是应该在功能上还是在命令式上进行?

谢谢

Bri*_*ian 11

这看起来像是... 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]
*)
Run Code Online (Sandbox Code Playgroud)


Jos*_*shD 1

我认为写起来很简单

for x from 0 to size-2:
if (a[x] > a[x+1] && a[x+1] < a[x+2]) // also, there should be bound checking
    //a[x+1] is a min!
    minima.cram(x+1)
if (a[x] < a[x+1] && a[x+1] > a[x+2]) // also, there should be bound checking
    //a[x+1] is a max!
    maxima.cram(x+1)
Run Code Online (Sandbox Code Playgroud)

还是我过于简单化了?