Skip to content

TreeSet: RemoveFunc not remove all matched node  #63

@zonewave

Description

@zonewave

for example, I want to remove all multiples of 3,

func ExampleTreeSet_RemoveFunc() {
	s := TreeSetFrom[int, Compare[int]](ints(20), Cmp[int])

	fmt.Println(s)

	even := func(i int) bool {
		return i%3 != 0
	}
	s.RemoveFunc(even)

	fmt.Println(s)

	// Output:
	// [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
	// [3 6 9 12 15 18 20]
}

but run test:
image

I think It is during the deletion walk, the structure of the tree changes so that some nodes cannot be visisted.

The simple way to solve the problem :

  1. first ,find all matched removeIds
  2. second, use RemoveSlice to remove
func (s *TreeSet[T, C]) RemoveFunc(f func(T) bool) bool {
   modified := false
   removeIds := make([]T, 0)
   findRemoveIds := func(item T) bool {
   	if f(item) {
   		removeIds = append(removeIds, item)
   	}
   	return true
   }
   s.ForEach(findRemoveIds)
   if len(removeIds) > 0 {
   	modified = true
   }
   s.RemoveSlice(removeIds)
   return modified
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions