Skip to content

Instantly share code, notes, and snippets.

@knjname
Created November 24, 2017 11:54
Show Gist options
  • Select an option

  • Save knjname/bc1905078cbe742d3d2ae0d75ea8da50 to your computer and use it in GitHub Desktop.

Select an option

Save knjname/bc1905078cbe742d3d2ae0d75ea8da50 to your computer and use it in GitHub Desktop.
前要素と比較してぶったぎる関数
export function partitionByComparingPredecessor<T>(
list: T[], partition: (prev: T, cur: T) => boolean
): T[][] {
const result: T[][] = []
let prev: T = null
let accum: T[] = []
for (const cur of list) {
if (prev !== null) {
if (partition(prev, cur)) {
result.push(accum)
accum = []
}
}
prev = cur
accum.push(cur)
}
if (accum.length > 0) {
result.push(accum)
}
return result
}
@knjname
Copy link
Copy Markdown
Author

knjname commented Dec 19, 2017

fun <T> List<T>.partitionByComparingPredecessor(
    partition: (prev: T, cur: T) -> Boolean
): List<List<T>> {

    val result = mutableListOf<List<T>>()

    var prev: T? = null
    var accum = mutableListOf<T>()

    for (cur in this) {
        if (prev !== null) {
            if (partition(prev, cur)) {
                result.add(accum)
                accum = mutableListOf<T>()
            }
        }

        prev = cur
        accum.add(cur)
    }

    if (accum.size > 0) {
        result.add(accum)
    }

    return result
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment