查找局部分钟在一个数组数组、在一、局部

2023-09-11 05:43:57 作者:各路角色

有没有一种简单的方法来确定值的数组的地方分钟,马克塞斯。例如

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|]

将确定

mins  = [|4;5|]

maxs  = [|7;10|]

有可能是一个列表或序列以及阵列。两个问题

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

有F#中的任何faciliities这是适合这种任务 有一个共同的算法来确定任一分钟或MAXS或两者兼而有之? 如果从头开始编写它应该在功能或命令走近?

THX

推荐答案

这看起来像一个工作的...的 Seq.windowed ! <提示超人音乐>

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]
*)