How to find the shortest identical consecutive subslice in a slice with Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func shortest_identical_consecutive_subarray(slice []int) []int {
    if len(slice) == 0 {
        return []int{}
    }

    bestStart := 0
    bestLen := len(slice)

    currentStart := 0
    currentLen := 1

    for i := 1; i < len(slice); i++ {
        if slice[i] == slice[i - 1] {
            currentLen++
        } else {
            if currentLen < bestLen {
                bestLen = currentLen
                bestStart = currentStart
            }
            currentStart = i
            currentLen = 1
        }
    }

    if currentLen < bestLen {
        bestLen = currentLen
        bestStart = currentStart
    }

    result := make([]int, bestLen)
    copy(result, slice[bestStart:bestStart+bestLen])

    return result
}

func main() {
    slice := []int{
            3, 3, 3,
            7, 7, 7, 7, 7,
            2, 2,
            5, 5, 5, 5,
            9, 9, 9, 9, 9, 9,
    }

    resultslice := shortest_identical_consecutive_subarray(slice)

    fmt.Print("Slice result: ")
    for _, x := range resultslice {
        fmt.Printf("%d ", x)
    }
}


/*
run:

Slice result: 2 2 

*/

 



answered Feb 9 by avibootz

Related questions

...