Untitled

mail@pastecode.io avatar
unknown
golang
2 years ago
1.5 kB
2
Indexable
Never
import (
	"testing"
)


func compress(numbers []int) string {
    result := ""
    sort.Ints(numbers)
    i := 0
    counter := 0
    flag := false
    var iterNum,firstNum int = 0, 0
    for i< len(numbers) {
        iterNum := numbers[i]
        firstNum := iterNum
        j := i +1
        for j < len(numbers) {
            currentNum := numbers[j]
            if firstNum + 1 == currentNum{
                j +=1
                counter += 1
                firstNum = currentNum
                flag = true
            } else if counter != 0{
               result += "," + fmt.Sprintf("%d-%d", iterNum, firstNum) 
               flag = false
               break   
            } else {
               result += "," + fmt.Sprintf("%d", firstNum)
               break 
            }
        }    
        i = j
        j = 0
        counter = 0
    }
    if flag{
        result += "," + fmt.Sprintf("%d-%d", iterNum, firstNum)
    } else {
        result += "," + fmt.Sprintf("%d", firstNum)
    }
    return result
}


type testCase struct {
	numbers []int
	result  string
}

func TestCompress(t *testing.T) {
	for _, input := range []testCase{
		{[]int{1, 4, 5, 2, 3, 9, 8, 11, 0}, "0-5,8-9,11"},
		{[]int{1, 4, 3, 8, 2, 10, 9}, "1-4,8-10"},
		{[]int{1, 4, 3, 2}, "1-4"},
		{[]int{1, 4}, "1,4"},
		{[]int{1}, "1"},
		{[]int{}, ""},
	} {
		if result := compress(input.numbers); result != input.result {
			t.Errorf("%v => %q, expected %q", input.numbers, result, input.result)
		}
	}
}