In: Computer Science
Write a function that counts the colors in a string using JavaScript. String "The quick brown fox jumped the blue fence and landed on red paint." This should return the number of colors. The colors you are looking for are "blue, green, brown, gray, black, brown, red, purple".
Source Code:
function count_colors(str)
{
var words=str.split(" ");
var colors=["blue","green","brown","gray","black","brown","red","purple"];
var count=0;
for(var i=0;i<words.length;i++)
{
for(j=0;j<colors.length;j++)
{
if(words[i]==colors[j])
{
count=count+1;
break;
}
}
}
return count
}
var str="The quick brown fox jumped the blue fence and landed on red paint.";
res=count_colors(str);
console.log(res);