File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments