Skip to content

Instantly share code, notes, and snippets.

@sumew
sumew / window.scala
Last active November 26, 2020 06:33
A window that can expand to the right and contract from the left
case class Window(l: Int, r: Int) {
def size = r - l
def ||->(i: Int): Window = this.copy(r = r + i) //widen by moving right edge right
def |->|(i: Int): Window = this.copy(l = l + i) //shrink by moving left edge right
}
@sumew
sumew / state.scala
Created November 26, 2020 05:57
The state, holds the current window and the optimum (so far) window
case class State[Container](current: Window, best: Window, contained: Container) {
def lastIndex(): Int = current.r
def firstIndex(): Int = current.l
override def toString =
s"current: [${current.l}, ${current.r}], best: [${best.l}, ${best.r}], excess: ${contained}"
}
trait Container[T, F[_]]
@sumew
sumew / slidingwindow.scala
Last active November 26, 2020 07:15
A generic representation of a sliding window problem
def lengthOfLongestSubstring(in: String): Int = {
//A type alias to simplify the syntax
type CounterContainer[T] = Map[T, Int]
//The elements are Chars and our container, a map with the Char as key and the frequence as value holds the elements within the current window
val longest = new SlidingWindow[Char, CounterContainer[Char]] {
override val input: Seq[Char] = in