I have a problem, and can't figure out a soulution right now.
I have a string like this "abcd dfeg uyti lksh bxnm abcd uyti".
And i want to replace the duplicates with some other text (i use a function to generate random letters).
But there is a problem, that the new text is alerdy generated.
EXAMPLE INPUT "aaaa bbbb cccc bbbb cccc dddd eeee"
My output is like this "aaaa bbbb cccc aaaa eeee dddd eeee". which is wrong
But the output i want is like this "aaaa bbbb cccc ffff gggg dddd eeee"
I tried this code
function formatTEXT(text) {
let words = text.split(" ");
let replaced = new Set();
let duplicatesFound = true;
while (duplicatesFound) {
const wordCounts = {};
duplicatesFound = false;
for (let i = 0; i < words.length; i ) {
const word = words[i];
if (!wordCounts[word]) {
wordCounts[word] = 1;
} else {
wordCounts[word] ;
}
}
for (let i = 0; i < words.length; i ) {
let replacement = generateTags(lettersN);
const word = words[i];
if (!replaced.has(word) && wordCounts[word] > 1 && !wordCounts[replacement]) {
words[i] = replacement;
replaced.add(word);
duplicatesFound = true;
console.log(replacement);
}
}
}
return words.join(" ");
}
formatTEXT("aaaa bbbb cccc bbbb cccc dddd eeee");
but it still does not work, there are still some duplicates in here.
CodePudding user response:
What you could do is build a list while checking for duplicates, then join it back into a string:
function formatText(text) {
let words = text.split(" ");
var newWords = []
for (let i in words) {
if (!newWords.includes(words[i])) {
newWords.push(words[i])
}
}
return newWords.join(" ")
}
console.log(formatText("aaaa bbbb cccc bbbb cccc dddd eeee"))
Output: "aaaa bbbb cccc dddd eeee"
CodePudding user response:
function formatText(text) {
let hashMappedString = text
.split(' ')
.reduce((previousState, currentElement) => {
previousState[currentElement] = currentElement;
return previousState;
}, {});
var newWords = '';
for (let word in hashMappedString) {
newWords = ` ${word}`;
console.log(word);
}
return newWords.trim(); // to remove the space in the beginning
}
console.log(formatText('aaaa bbbb cccc bbbb cccc dddd eeee'));
// this code has the time complexity of O(n) O(n) which is O(2n) which is O(n) by ignoring the constant