const MAX = 26;
function
cmp(a, b) {
if
(a[0] == b[0]) {
return
a[1] - b[1];
}
return
b[0] - a[0];
}
class Node {
constructor(bul) {
this
.exist = bul;
this
.arr =
new
Array(MAX).fill(
null
);
}
}
function
add(s, trie) {
const n = s.length;
for
(let i = 0; i < n; i++) {
if
(trie.arr[s.charCodeAt(i) - 'a
'.charCodeAt()] === null) {
trie.arr[s.charCodeAt(i) - '
a
'.charCodeAt()] = new Node();
}
trie = trie.arr[s.charCodeAt(i) - '
a
'.charCodeAt()];
}
trie.exist = true;
return;
}
// Function that returns true if
// the trie contains the string s
function search(s, trie) {
// Search for a node in the trie
for (let i = 0; i < s.length; i++) {
if (trie.arr[s.charCodeAt(i) - '
a
'.charCodeAt()] === null) {
return false;
}
trie = trie.arr[s.charCodeAt(i) - '
a
'.charCodeAt()];
}
return trie.exist;
}
// Function to replace every '
_
' with a
// white space in the given string
function convert(s) {
// Convert '
_
' to spaces
return s.replace(/_/g, '
');
}
// Function to sort the array based on good words
function sortArr(good, review) {
// Extract all the good words which
// are '
_
' separated
good = convert(good);
const trie = new Node();
const words = good.split('
');
// Building the entire trie from the good words
for (let i = 0; i < words.length; i++) {
add(words[i], trie);
}
const n = review.length;
// To store the number of good words
// and the string index pairs
const rating = new Array(n).fill(null).map((_, i) => [0, i]);
for (let i = 0; i < n; i++) {
review[i] = convert(review[i]);
const words = review[i].split('
');
let k = 0;
for (let j = 0; j < words.length; j++) {
// If this word is present in the trie
// then increment its count
if (search(words[j], trie)) {
k += 1;
}
}
// Store the number of good words in the
// current string paired with its
// index in the original array
rating[i] = [k, i];
}
// Using comparator function to
// sort the array as required
rating.sort((a, b) => cmp(a, b));
// Print the sorted array
for (let i = 0; i < rating.length; i++) {
console.log(review[rating[i][1]]);
}
}
// Driver code
// Input
let S = '
geeks_for_geeks_is_great
';
let R = ['
geeks_are_geeks
', '
geeks_dont_lose
', '
geeks_for_geeks_is_love'];
sortArr(S, R);