OOP_IO-2x_2023-mirror/Java/lab_5/Text.kt

83 lines
2.8 KiB
Kotlin
Raw Normal View History

2023-06-05 19:05:22 +03:00
package OOP.Java.lab_5
2023-06-07 15:38:48 +03:00
/**
* A class representing the entire text.
*
* @property textArray a [Pair] of [Array]s of [Sentence] and [Punctuation] objects that make up a text.
*
* @constructor a primary constructor accepts a [Pair] of [Array]s of [Sentence] and [Punctuation] objects, a secondary one accepts a string representing the entire text.
*/
class Text(var textArray: Pair<Array<Sentence>, Array<Punctuation>>) {
2023-06-05 19:05:22 +03:00
2023-06-07 15:38:48 +03:00
constructor(
textString: String
) : this(
Pair(
textString.split("[.!?] ?".toRegex()).filter { it.isNotEmpty() }.map { sentence -> Sentence(sentence) }.toTypedArray(),
textString.split("(?<=[.!?]) ?".toRegex()).filter { it.isNotEmpty() }.map { sentence -> Punctuation(sentence.last().toString()) }.toTypedArray()
)
)
2023-06-05 19:05:22 +03:00
2023-06-07 15:38:48 +03:00
/**
* Returns an array of all [Letter] objects in a sentence.
*/
private fun getAllLetters(): Array<Letter> {
var allLetters = arrayOf<Letter>()
this.textArray.first.forEach { allLetters += it.getAllLetters() }
return allLetters
2023-06-05 19:05:22 +03:00
}
2023-06-07 15:38:48 +03:00
/**
* Searches for the longest palindromic substring in a given text.
*
* @return the longest palindromic substring found.
*/
fun palindromeSearch(): String {
2023-06-07 15:38:48 +03:00
var result = " "
val letters = this.getAllLetters()
2023-06-07 15:38:48 +03:00
for (leftBoundary in letters.indices) {
for (rightBoundary in letters.lastIndex downTo leftBoundary + 1) {
val subToC = letters.sliceArray(leftBoundary..rightBoundary)
2023-06-07 15:38:48 +03:00
if (subToC.first().letterEquals(subToC.last(), true) && this.checkReverse(subToC) && subToC.size > result.length) {
result = subToC.joinToString("")
}
}
}
2023-06-07 15:38:48 +03:00
return result
}
2023-06-07 15:38:48 +03:00
/**
* Checks if a given substring is a palindrome.
*
* Is not case-sensitive.
*
* @param substring an [Array] of [Letter] objects representing a substring.
*
* @return "true" is a substring given is a palindrome, "false" if it isn't.
*/
private fun checkReverse(substring: Array<Letter>): Boolean {
var leftBoundary = 0
var rightBoundary = substring.lastIndex
var result = false
2023-06-07 15:38:48 +03:00
val correction = substring.size % 2
while (leftBoundary < substring.size / 2 && rightBoundary >= substring.size / 2 + correction) {
leftBoundary++
rightBoundary--
2023-06-07 15:38:48 +03:00
result = substring[leftBoundary].letterEquals(substring[rightBoundary], true)
}
return result
}
2023-06-05 19:05:22 +03:00
override fun toString(): String {
var text = arrayOf<String>()
2023-06-07 15:38:48 +03:00
this.textArray.first.indices.forEach { text += this.textArray.first[it].toString() + this.textArray.second[it].toString() }
2023-06-05 19:05:22 +03:00
return text.joinToString(" ")
}
}