Gabe Rogan Gabe Rogan - 5 months ago 16
Javascript Question

How to write a character matching algorithm in JavaScript?

Given this input

s1 = "dadxx"
s2 = "ddxx"
I'd expect the output to contain a bunch of
a,b
pairs wherever each character in
s1
matched a character in
s2
and vice versa (duplicates allowed). Among those pairs would be
0,0
because
s1[0]
and
s2[0]
are both equal to
d
.

The problem is that my output doesn't contain
2,1
even though
s1[2]
and
s2[1]
are both equal to
d
.

Can someone fix my algorithm or make a better one?

Here's a JSFiddle if it helps.

Here's my code:

// For each char, see if other string contains it
s1 = 'dadxx'
s2 = 'ddxx'

matchChars(s1,s2)
matchChars(s2,s1)

function matchChars(a,b) {
for (i = 0; i < a.length; i++) {
found = b.indexOf(a[i])
if (found >= 0) {
if (a===s1) console.log(i,found)
else console.log(found,i)
}
}
}

Answer Source

I believe the problem you're having is that you're only checking for a single match for s1[i] in s2 by using indexOf. That will find the first index of a matched value, not every index.

If you instead iterate through both strings and compare every character, you get the result I think you're trying to achieve.

// Define strings
s1 = 'dadxx'
s2 = 'ddxx'

matchChars(s1,s2)
matchChars(s2,s1)

function matchChars(a,b) {
  // Convert strings to lower case for case insensitive matching
  // Remove if case sensitive matching required
  a = a.toLowerCase();
  b = b.toLowerCase();

  // Iterate through every letter in s1
  for (i = 0; i < a.length; i++) {
    // Iterate through every letter in s2
    for (j = 0; j < b.length; j++) {
      // Check if the letter in s1 matches letter in s2
      if (a[i] === b[j]) {
        // Changed per request of OP
        (a === s1) ? console.log(i, j) : console.log(j, i);
        // console.log([i, j]);
      }
    }
  }
}

Working JSBin example: https://jsbin.com/wecijopohi/edit?js,console