IrCa
IrCa

Reputation: 165

How to traverse loop in Go and print out every third element

I know to traverse through a list, i would do the following:

for e := alist.Front(); e != nil; e = e.Next() {
       fmt.Println(e.Value) 
   }

However, I would like to print out every third element. In other langauges, i would increment the index like e += 3. How do I do that with Go?

Upvotes: 0

Views: 801

Answers (1)

Howard
Howard

Reputation: 3848

List is a doubly linked list which doesn't allow to seek or jump by a specific count. My workaround is this:

i := 0
for e := alist.Front(); e != nil; e = e.Next() {
    if i % 3 == 0 {
        fmt.Println(e.Value)
    }

    i++
}

Or a new function for code reuse (with @torek's comment, it becomes simpler):

func NextByCount(el *list.Element, count int) *list.Element {
    for ; el != nil && count > 0; count-- {
        el = el.Next()
    }

    return el
}

Then loop it like:

for e := alist.Front(); e != nil; e = NextByCount(e, 3) {
    fmt.Println(e.Value)
}

Upvotes: 5

Related Questions