Forum Discussion

cgkas's avatar
cgkas
Icon for Helper V rankHelper V
3 years ago
Solved

How to get the Longest Common Prefix (LCP)?

Hi to all,   I have the need to get the longest common prefix between values in 2 columns. LCP is implemented in several languages in this rosettacode link, but is there a built-in function in M la...
  • ppm1's avatar
    ppm1
    3 years ago

    Here you go.

    (input1 as text, input2 as text)=>
    let
        Inputs = {input1, input2},
        SplitAndZip = List.Zip(List.Transform(Inputs, each Text.ToList(_))),
        CompareValues = List.Transform(SplitAndZip, each _{0} = _{1}),
        FindFirstFalse = List.PositionOf(CompareValues, false),
        KeepFirstCharacters = if input1=input2 then input1 else Text.Combine(List.FirstN(Text.ToList(Inputs{0}), FindFirstFalse), "")
    in
        KeepFirstCharacters

    Pat

  • ppm1's avatar
    ppm1
    3 years ago

    Here you go.

    (input1, input2)=>
    let
        Inputs = {input1, input2},
        SplitAndZip = List.Zip(List.Transform(Inputs, each try Text.ToList(_) otherwise {})),
        CompareValues = List.Transform(SplitAndZip, each _{0} = _{1}),
        FindFirstFalse = List.PositionOf(CompareValues, false),
        KeepFirstCharacters = if input1=input2 then input1 else Text.Combine(List.FirstN(Text.ToList(Inputs{0}), FindFirstFalse), "")
    in
        KeepFirstCharacters

    Pat