Skip to content

Instantly share code, notes, and snippets.

@bastman
Last active December 14, 2021 07:46
Show Gist options
  • Save bastman/6688baffe26d063bd6b21daff7024aac to your computer and use it in GitHub Desktop.
Save bastman/6688baffe26d063bd6b21daff7024aac to your computer and use it in GitHub Desktop.
sliding-window-algorithm-technique: examples (kotlin)
// see: https://itnext.io/sliding-window-algorithm-technique-6001d5fbe8b3
fun main() {
intro()
`Maximum sum subarray of Size k`()
//`Count Occurrences of Anagram`()
}
fun intro() {
listOf("a", "b", "c", "d", "e", "f", "g", "h")
.windowed(size = 3, step = 1, partialWindows = false) { currentWindow: List<String> ->
println("currentWindow: $currentWindow")
currentWindow
}
}
fun `Maximum sum subarray of Size k`() {
val slidingSums: List<Int> = listOf(3, 5, 2, 1, 7)
.windowed(size = 2, step = 1, partialWindows = false) { currentWindow: List<Int> ->
println("currentWindow: $currentWindow -> sum() ${currentWindow.sum()}")
currentWindow.sum()
}
val maxSum: Int? = slidingSums.maxOrNull()
println("Maximum sum subarray of Size k=2: $maxSum")
}
fun `Count Occurrences of Anagram`() {
val text = "gotxxotgxdogt"
val word = "got"
TODO()
}
private fun isAnagram(s1: String, s2: String): Boolean {
// Explanation: Words — got, otg, ogt are anagrams of got.
if (s1.length != s2.length) {
return false
}
val c1: CharArray = s1.toCharArray()
val c2: CharArray = s2.toCharArray()
return c1.sorted() == c2.sorted()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment