查找局部分钟在一个数组 [英] Finding local mins in an array

查看:120
本文介绍了查找局部分钟在一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

这篇关于查找局部分钟在一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆