Skip to content

Commit dd5948b

Browse files
authored
Create MostFrequentWord.lua
1 parent db41024 commit dd5948b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

strings/MostFrequentWord.lua

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
-- Author: JoshSCF
2+
-- Returns the word that appears most frequently in a string
3+
4+
function GetMostFrequentWord(String)
5+
local Words = {}
6+
local MostFrequentWord = {
7+
Word = "",
8+
Count = 0
9+
}
10+
11+
for Word in String:lower():gmatch("%S+") do -- Iterate through each word in string, ignoring case
12+
if Words[Word] then -- Check if word has appeared already
13+
Words[Word] = Words[Word] + 1 -- Add one to count
14+
else
15+
Words[Word] = 1 -- Set count to one
16+
end
17+
18+
if Words[Word] > MostFrequentWord.Count then -- If word has appeared more than the current most frequent word
19+
-- Update most frequent word and frequency count
20+
MostFrequentWord.Word = Word
21+
MostFrequentWord.Count = Words[Word]
22+
end
23+
end
24+
25+
return MostFrequentWord.Word -- Return most frequent word
26+
end
27+
28+
print(GetMostFrequentWord("apple apple car bus bus bee bee bee apple apple egg")) -- Returns apple

0 commit comments

Comments
 (0)