cielux
10/3/2018 - 6:44 PM

## Word Count

Implement a method that accepts an arbitrarily long string and a count c that returns the first word in the string to appear at least c times.

Twist 1: Return the first word that appears exactly c times in the string. Twist 2: Return the last word to appear exactly c times. Twist 3: Given an additional parameter n, returns the nth word that occurs exactly c times.

``````/*
Implement a method that accepts an arbitrarily long string and a count c that returns the first
word in the string to appear at least c times.

Examples:
Input: "This boring sentence is very short and very boring", 2
Output: "very"

Input: “apple banana apple lemon pear banana apple”, 3
Output: “apple

Twist 1: Return the first word that appears exactly c times in the string.
Example:
input "banana lemon pear banana lemon lime pear banana", 2
output: "lemon"

Twist 2: Return the last word to appear exactly c times.
Example:
input "banana lemon pear banana lemon lime pear banana", 2
output: "pear"

Twist 3: Given an additional parameter n, returns the nth word that occurs exactly c times.
Example:
input: "apple banana apple lemon pear banana apple lemon lime pear banana pear", 3, 3
output: “pear” (the third word to appear three times)

*/

function getRepeatedWord(input, count, chosen) {
if (input === "" || count < 1) return "";
const words = input.split(" ");
let countMap = {};
let countMatches = [];

for (let i = 0; i < words.length; i++) {
countMap[words[i]] = countMap[words[i]] ? countMap[words[i]] : 0;
countMap[words[i]]++;
//console.log("countMap", countMap);
if (countMap[words[i]] === count) {
countMatches.push(words[i]);
} else {
let idx = countMatches.indexOf(words[i]);
if (idx > -1) {
countMatches.splice(idx, 1);
}
}
console.log("countMatches", countMatches);
}
return countMatches[chosen-1];
}

//console.log(getRepeatedWord("This boring sentence is very short and very boring", 2) === "very");
//console.log(getRepeatedWord("apple banana apple lemon pear banana apple", 3) === "apple");

//console.log(getRepeatedWord("", 3) === "");
//console.log(getRepeatedWord("test test run", 0) === "");

//console.log(getRepeatedWord("banana lemon pear banana lemon lime pear banana", 2) === "lemon");
//console.log(getRepeatedWord("banana lemon pear banana lemon lime pear banana", 2) === "pear");
console.log(getRepeatedWord("apple banana apple lemon pear banana apple lemon lime pear banana pear", 3, 3) === "pear");``````