Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for finding characters in the same positions in a list of strings?

Suppose I have:

  1. Toby
  2. Tiny
  3. Tory
  4. Tily

Is there an algorithm that can easily create a list of common characters in the same positions in all these strings? (in this case the common characters are 'T' at position 0 and 'y' at position 3)

I tried looking at some of the algorithms used for DNA sequence matching but it seems most of them are just used for finding common substrings regardless of their positions.

like image 843
ilitirit Avatar asked Nov 17 '25 21:11

ilitirit


2 Answers

Finding a list of characters that are common in ALL strings at a certain position is trivially simple. Just iterate on each string for each character position 1 character position at a time. If any string's character is not the match of it's closest neighbor string's character, then the position does not contain a common character.

For any i = 0 to length -1... Once you find Si[x] != Si+1[x] you can skip to the next position x+1.

Where Si is the ith string in the list. And [x] is the character at position x.

like image 65
Brian R. Bondy Avatar answered Nov 20 '25 11:11

Brian R. Bondy


Some generic code that has pretty poor performance O(n^2)

str[] = { "Toby", "Tiny", "Tory", "Tily" };
result = null;
largestString = str.getLargestString(); // Made up function
str.remove(largestString)
for (i = 0; i < largestString.length; i++) {
   hits = 0;
   foreach (str as value) {
      if (i < value.length) {
         if (value.charAt(i) == largestString.charAt(i))
            hits++;
      }
   }
   if (hits == str.length)
      result += largestString.charAt(i);
}
print(str.items);
like image 31
Josh Smeaton Avatar answered Nov 20 '25 11:11

Josh Smeaton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!