如何总结"任何三个元素"在F#中的元组

时间:2015-09-24 14:20:33

标签: f#

我最近开始学习如何使用F#进行编程,并且我的作业给了我一些严重的麻烦。

我必须创建一个带有两个参数的函数,一个整数和一个五元素的整数元组,如果元组的任何三个元素的总和大于第一个参数,则返回true,否则返回false。

我开始以这种方式设计我的代码

{
let t3 = (1, 2, 3, 4, 5)
let intVal = 1
let check intVal t3 = 
for t3
    if (*sum of any three elements*) > intVal then true
    else false
}

但此时我陷入困境,不知道如何继续。

3 个答案:

答案 0 :(得分:6)

简单的方法定义 - 对元组的元素进行排序,并与最后三个元素(升序排序)进行比较:

let inline isAnyThreeGreaterThan2 limit (x1, x2, x3, x4, x5) = 
    [x1;x2;x3;x4;x5] |> List.sort |> Seq.skip 2 |> Seq.sum > limit

示例:

isAnyThreeGreaterThan2 15 (1, 2, 5, 5, 5) |> printfn "%A"
isAnyThreeGreaterThan2 14 (1, 2, 5, 5, 5) |> printfn "%A"
isAnyThreeGreaterThan2 15 (1, 2, 5, 5, 6) |> printfn "%A"
isAnyThreeGreaterThan2 15 (1, 2, 3, 4, 5) |> printfn "%A"
isAnyThreeGreaterThan2 12 (1, 2, 3, 4, 5) |> printfn "%A"
isAnyThreeGreaterThan2 11 (1, 2, 3, 4, 5) |> printfn "%A"

打印:

false
true
true
false
false
true

链接:

https://dotnetfiddle.net/7XR1ZA

答案 1 :(得分:4)

可以通过将元组转换为数组,从中获取可能的组合,对这些组合求和,然后验证任何总和是否大于参数来解决

(1,2,3,4,5) 
|> Microsoft.FSharp.Reflection.FSharpValue.GetTupleFields 
|> Array.toList 
//Implementing this is left as and exercise to the reader
|> combinations 3 
//converts the obj list as a int list and then sums the elements
|> List.map (fun x -> x |> List.map unbox<int> |> List.sum) 
//Verifies if any sum is greater than intVal
|> List.exists (fun x -> x > intVal)

答案 2 :(得分:1)

这样的事情应该这样做:

let cross3 l1 l2 l3 =
    [
        for x in l1 do
            for y in l2 do
                for z in l3 do
                yield x, y, z ]

module Tuple3 =
    let distinct (x, y, z) =
        let l = [x; y; z]
        l |> List.distinct |> List.length = l.Length

    let snd (x, y, z) = snd x, snd y, snd z

    let inline sum (x, y, z) = x + y + z

let inline isAnyThreeGreaterThan limit (x1, x2, x3, x4, x5) =
    let l = [x1; x2; x3; x4; x5] |> List.indexed
    let legalCombinations =
        cross3 l l l
        |> List.filter Tuple3.distinct
        |> List.map Tuple3.snd
    legalCombinations |> List.exists (fun t3 -> Tuple3.sum t3 > limit)

由于这是一项任务,我会将其作为练习来理解正在发生的事情,但这是一个示例FSI会话:

> isAnyThreeGreaterThan 15 (1, 2, 5, 5, 5);;
val it : bool = false
> isAnyThreeGreaterThan 14 (1, 2, 5, 5, 5);;
val it : bool = true
> isAnyThreeGreaterThan 15 (1, 2, 5, 5, 6);;
val it : bool = true
> isAnyThreeGreaterThan 15 (1, 2, 3, 4, 5);;
val it : bool = false
> isAnyThreeGreaterThan 12 (1, 2, 3, 4, 5);;
val it : bool = false
> isAnyThreeGreaterThan 11 (1, 2, 3, 4, 5);;
val it : bool = true