Comparando duas strings - otimização de código

Oct 04 2020

Quero comparar duas strings contando quantos caracteres comuns elas têm na mesma posição - mas no geral em todos os alinhamentos possíveis das duas strings.

SeedRandom[1]
str1 = RandomInteger[{1, 26}, 90] /. 
   Thread[Range[26] -> CharacterRange["A", "Z"]] // StringJoin
str2 = RandomInteger[{1, 26}, 850] /. 
   Thread[Range[26] -> CharacterRange["A", "Z"]] // StringJoin
fu[x_, y_] := 
 Module[{par = Partition[Characters[y], StringLength[x], 1, {1, 1}]},
  Count[Flatten[(Transpose[{#, Characters[x]}] & /@ par), 1], {z_, z_}]
  ]

fu[str1, str2] // Timing
(*{0.046875, 3013}*)

Isso significa que as strings str1e str2possuem 3013caracteres comuns no total em todos os alinhamentos possíveis.

Isso pode ser feito com mais eficiência, talvez sem converter strings em listas?

Respostas

Coolwater Oct 04 2020 at 02:38

Há

fu3 = Dot @@ Lookup[#, Union @@ Keys[#], 0] &[Counts@*ToCharacterCode /@ {#, #2}] &;

Last@Table[fu[str1, str2], {100}] // RepeatedTiming
Last@Table[fu3[str1, str2], {100}] // RepeatedTiming
(* {2.3, 3013} *)
(* {0.0029, 3013} *)