Forum Discussion
cgkas
Helper V
3 years agoHow 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...
- 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 KeepFirstCharactersPat
- 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 KeepFirstCharactersPat
cgkas
Helper V
3 years agoThanks so much for your help. It almost working, only detected one issue when compares 2 strings that are equal. In this case the expected output should be the same string and currently is showing blank. Please see table below. For example some comparisons below and current and expected output.
| Input1 | Input2 | Current Output | Expected Output |
| 9000 | 9999 | 9 | 9 |
| 8549000 | 8549999 | 8549 | 8549 |
| 50 | 99 | ||
| 99999 | 99999 | 99999 |
- ppm13 years ago
Solution Sage
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 KeepFirstCharactersPat
- cgkas3 years ago
Helper V
Thanks so much. This time it fits all conditions. I was trying to add in wrong place the "if else" you added. I see in your solution, the "if else" should go inside one step, not outside.