Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions contest/src/main/java/com/github/contest/CustomEXT.kt
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
package com.github.contest

fun MutableMap<Int, Int>.removeIfEmptyBucket(key: Int) {
this[key] = this.getOrDefault(key, 0) - 1

fun <K, V> MutableMap<K, V>.removeIfEmptyBucket(key: K) {
if (this[key] == 0) this.remove(key)
}


fun Any.printData(label: String) {
println("$label $this")
fun <K> MutableMap<K, Int>.reduceCount(key: K) {
this[key] = this.getOrDefault(key, 0) - 1
removeIfEmptyBucket(key)
}


inline fun abs(number: Int): Int = when {
fun abs(number: Int): Int = when {
number < 0 -> number * -1
else -> number
}
46 changes: 37 additions & 9 deletions contest/src/main/java/com/github/contest/Execute.kt

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ package com.github.contest.priorityqueue

fun topKFrequentProdVariant(nums: IntArray, k: Int): IntArray {
val freq = mutableMapOf<Int, Int>()
val repeated = Array<MutableList<Int>>(nums.size + 1) {mutableListOf()}
val repeated = Array<MutableList<Int>>(nums.size + 1) { mutableListOf() }

for (num in nums) freq[num] = freq.getOrDefault(num, 0) + 1

for ((num, count) in freq) {
repeated[count].add(num)
}

return repeated.flatMap {it}.takeLast(k).toIntArray()
return repeated.flatMap { it }.takeLast(k).toIntArray()
}
Original file line number Diff line number Diff line change
Expand Up @@ -300,4 +300,23 @@ fun minimumSumSubarray(nums: List<Int>, l: Int, r: Int): Int {
return TODO("Make this method")
}

/**
* 187. Repeated DNA Sequences
*/

fun findRepeatedDnaSequences(s: String): List<String> {
if (s.length < 10) return listOf()

val dnas = s.windowed(10).map { it }.groupingBy { it }.eachCount()
val res = mutableListOf<String>()

for ((key, value) in dnas) {
if (value > 1) res.add(key)
}


return res
}



Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,17 @@ fun minimumSumSubarrayProdVariant(nums: List<Int>, l: Int, r: Int): Int = buildL
nums.windowed(window).map { it.sum() }.filter { it > 0 }.forEach { add(it) }
}
}.minOrNull() ?: -1

/**
* 187. Repeated DNA Sequences
* Prod Variant
*/

fun findRepeatedDnaSequencesProdVariant(s: String): List<String> = when {
s.length < 10 -> listOf()
else -> buildList {
s.windowed(10).map { it }.groupingBy { it }.eachCount().forEach { (key, value) ->
if (value > 1) add(key)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package com.github.contest.slidingWindow.customStructure


fun rabinKarpSearch(text: String, pattern: String): List<Int> {
val d = 256 // Размер алфавита (ASCII)
val q = 101 // Простое число для избежания переполнения
val m = pattern.length
val n = text.length
var patternHash = 0 // Хеш образца
var textHash = 0 // Хеш текущего окна в тексте
var h = 1 // Значение для "скользящего" хеша: h = d^(m-1)
val result = mutableListOf<Int>()

if (n < m || m == 0 || n == 0) return result

// Вычисляем h = d^(m-1) % q
for (i in 0 until m - 1) {
h = (h * d) % q
}

// Вычисляем начальные хеши для образца и первого окна текста
for (i in 0 until m) {
patternHash = (d * patternHash + pattern[i].code) % q
textHash = (d * textHash + text[i].code) % q
}

// Проходим по тексту
for (i in 0..n - m) {
// Если хеши совпали, проверяем символы один за другим
if (patternHash == textHash) {
var match = true
for (j in 0 until m) {
if (text[i + j] != pattern[j]) {
match = false
break
}
}
if (match) {
result.add(i)
}
}

// Вычисляем хеш для следующего окна текста
if (i < n - m) {
textHash = (d * (textHash - text[i].code * h) + text[i + m].code) % q
// Обеспечиваем положительное значение хеша
if (textHash < 0) textHash += q
}
}

return result
}

fun rabinKarpMultiPattern(text: String, patterns: List<String>): Map<String, List<Int>> {
val d = 256
val q = 101
val result = mutableMapOf<String, MutableList<Int>>()
val patternHashes = mutableMapOf<Int, MutableList<String>>()

// Предварительно вычисляем хеши всех образцов
for (pattern in patterns.distinct()) {
val m = pattern.length
if (m == 0 || m > text.length) continue

var hash = 0
for (i in 0 until m) {
hash = (d * hash + pattern[i].code) % q
}

patternHashes.getOrPut(hash) { mutableListOf() }.add(pattern)
result[pattern] = mutableListOf()
}

// Ищем все возможные длины образцов
val lengths = patterns.map { it.length }.distinct().sorted()

for (m in lengths) {
if (m == 0 || m > text.length) continue

var h = 1
for (i in 0 until m - 1) {
h = (h * d) % q
}

var textHash = 0
// Вычисляем хеш первого окна
for (i in 0 until m) {
textHash = (d * textHash + text[i].code) % q
}

// Проверяем первый хеш
patternHashes[textHash]?.forEach { pattern ->
if (pattern.length == m && text.startsWith(pattern, 0)) {
result[pattern]?.add(0)
}
}

// Скользим по тексту
for (i in 1..text.length - m) {
// Обновляем хеш
textHash = (d * (textHash - text[i - 1].code * h) + text[i + m - 1].code) % q
if (textHash < 0) textHash += q

// Проверяем совпадения
patternHashes[textHash]?.forEach { pattern ->
if (pattern.length == m && text.startsWith(pattern, i)) {
result[pattern]?.add(i)
}
}
}
}

return result
}

fun slidingWindowClassic(text: String, patterns: List<String>): List<Int> {
val res = mutableListOf<Int>()

for (pattern in patterns) {
val window = pattern.length
text.windowed(window) {
if (it == pattern) res.add(0)
}
}

return res
}