代码之家  ›  专栏  ›  技术社区  ›  A191919

F#Codewars整数:二

f#
  •  0
  • A191919  · 技术社区  · 7 年前

    task 具有

    代码

    open System
    
    let rec distribute e = function
      | [] -> [[e]]
      | x::xs' as xs -> (e::xs)::[for xs in distribute e xs' -> x::xs]
    
    let rec permute = function
      | [] -> [[]]
      | e::xs -> List.collect (distribute e) (permute xs)
    
    let MoreRule (a: int) (b: int) (c: int) (d: int) = 
        let permutations = permute [a;b;c;d]
        let sums = permutations |> List.map(fun x -> x.[0]*x.[1] + x.[2]*x.[3])
        let diffs = permutations |> List.map(fun x -> x.[0]*x.[1] - x.[2]*x.[3])
        List.append sums diffs
        |> List.distinct
        |> List.filter(fun x -> x>0)
        |> List.sort
    
    let factor number list = [
        for i in list do 
            let t = Math.Floor(Math.Sqrt((number-Math.Pow((float)i,2.0)))) |> int
            if (List.exists ((=)t) list) then 
                yield [|i;t|]
        ]
    
    let prod2Sum (a: int) (b: int) (c: int) (d: int): int[] list = 
        let number = (float)(((a*a)+(b*b))*((c*c)+(d*d)))   
        let coefficients = MoreRule a b c d
        factor number coefficients
        |> List.map(fun arr -> if (arr.[0]>arr.[1]) then [|arr.[1];arr.[0]|] else [|arr.[0];arr.[1]|])
        |> List.distinct
    

    当点击页面上的“尝试”按钮时,我得到的响应失败,退出代码1

    prod2Sum 4 5 20 1 [[|75; 104|]; [|85; 96|]]

    主要问题是我做错了什么?如何改进此代码?非常感谢。

    0 回复  |  直到 7 年前
        1
  •  2
  •   Tomas Petricek    7 年前

    我不知道你的代码到底出了什么问题-为了帮助解决这个问题,你可能需要更多地解释它应该如何工作-但是我能够复制你的代码失败的情况。如果你跑你的车 prod2Sum

    prod2Sum 1 20 -4 -5
    

    CodeWars的预期结果是 [[|75; 104|]; [|85; 96|]] . 我没有弄清楚您的代码是如何试图解决这个问题的,但是一些实验表明,负值会被过滤掉 MoreRule 按以下行:

    |> List.filter(fun x -> x > 0)
    

    List.map abs 在本例中有效,但对其他一些输入无效。

    作为记录,找到问题所在的一个简单方法是在日志中添加一些日志 产品2

    let prod2Sum (a: int) (b: int) (c: int) (d: int): int[] list = 
        let number = (float)(((a*a)+(b*b))*((c*c)+(d*d)))   
        let coefficients = MoreRule a b c d
        let res = 
            factor number coefficients
            |> List.map(fun arr -> if (arr.[0]>arr.[1]) then [|arr.[1];arr.[0]|] else [|arr.[0];arr.[1]|])
            |> List.distinct
        if res = [] then 
            printfn "%A" (a,b,c,d) // Log inputs for which we returned wrong result
        r
    

    有了这个,您应该能够找出其他哪些测试用例失败了。