简体   繁体   中英

I need to compare two strings (or arrays) and return their % of similarity regardless of their order

I'm currently trying to make a module on which you can study vocabulary for ancient languages, and for that I need a tool to check wether or not the user's answer matches with the one in the database.

The way I would want to implement this (if you have a more efficient solution, please let me know) is to count the characters (they will all be lower case strings or arrays without punctuation) and check their percent of similarity.

Is there any way how to do this?

I tried to do something with .match() but unfortunately that didn't work out too well.

// these are the variables

let p = 'The lazy dog jumps over the quick brown fox. It barked.';
p = p.toLowerCase();
p = p.replace(/\s/g, '');
p = p.replace('.', '');
p = p.replace('.', '');

let a = 'The quick brown fox jumps over the lazy dog. It barked.';
a = a.toLowerCase();
a = a.replace(/\s/g, '');
a = a.replace('.', '');
a = a.replace('.', '');

let c = 'The quick black ostrich jumps over the lazy dog. It barked.';
c = c.toLowerCase();
c = c.replace(/\s/g, '');
c = c.replace('.', '');
c = c.replace('.', '');

// this is what should happen: 

compare(p,a); // should return 100%
compare(p,c); // should return 72% (if my math is correct)

You could count the same characters, for the first with an incremeent and for the second by decremeenting each count add take the absolute value for the sum.

Then return the similarity.

 function compare(a, b) { var count = {}, delta; a = clean(a); b = clean(b); getCount(a, count, 1); getCount(b, count, -1); delta = Object.values(count).reduce((s, v) => s + Math.abs(v), 0); return (b.length - delta) / a.length; } function getCount(string, count = {}, inc = 1) { Array.from(string).forEach(c => count[c] = (count[c] || 0) + inc); return count; } const clean = s => s.toLowerCase().replace(/[\\s.,]+/g, ''); var p = 'The lazy dog jumps over the quick brown fox. It barked.', a = 'The quick brown fox jumps over the lazy dog. It barked.', c = 'The quick black ostrich jumps over the lazy dog. It barked.'; console.log(compare(p, a)); console.log(compare(p, c));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM