Created
March 11, 2022 21:13
-
-
Save anibalbastiass/ac0311e7c0c2208bf1877b2bc9a3efa4 to your computer and use it in GitHub Desktop.
MostRepeatedWord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader | |
import java.io.FileReader | |
fun main() { | |
getRepeatedCode(fileName = "data.txt") | |
} | |
private fun getRepeatedCode(fileName: String) { | |
var line: String | |
var word = "" | |
var count: Int | |
var maxCount = 0 | |
val words = ArrayList<String>() | |
val file = FileReader(fileName) | |
val br = BufferedReader(file) | |
// Reads each line | |
while (br.readLine().also { line = it } != null) { | |
val string = line.toLowerCase().split("([,.\\s]+) ".toRegex()).toTypedArray() | |
for (s in string) { | |
words.add(s) | |
} | |
} | |
//Determine the most repeated word in a file | |
for (i in words.indices) { | |
count = 1 | |
//Count each word in the file and store it in variable count | |
for (j in i + 1 until words.size) { | |
if (words[i] == words[j]) { | |
count++ | |
} | |
} | |
//If maxCount is less than count then store value of count in maxCount | |
//and corresponding word to variable word | |
if (count > maxCount) { | |
maxCount = count | |
word = words[i] | |
} | |
} | |
println("Most repeated word: $word") | |
br.close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment