Skip to content

Commit

Permalink
Merge pull request #4 from geniussportsgroup/develop
Browse files Browse the repository at this point in the history
Added removeByPos operation
  • Loading branch information
lrleon authored Oct 9, 2020
2 parents 8db92bf + 9c83df5 commit 0ec844b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
30 changes: 30 additions & 0 deletions treaps.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,36 @@ func (tree *Treap) Remove(key interface{}) interface{} {
return retVal.key
}

func __removePos(rootPtr **Node, i int) *Node {

root := *rootPtr
var retVal *Node
if i == root.llink.count {
retVal = root
*rootPtr = __joinExclusive(&(*rootPtr).llink, &(*rootPtr).rlink)
retVal.reset()
return retVal
} else if i < root.llink.count {
retVal = __removePos(&(*rootPtr).llink, i)
} else {
retVal = __removePos(&(*rootPtr).rlink, i-(root.llink.count+1))
}

root.count--

return retVal
}

func (tree *Treap) RemoveByPos(i int) interface{} {

if i >= tree.Size() {
panic(fmt.Sprintf("Invalid position %d", i))
}

retVal := __removePos(tree.rootPtr, i)
return retVal.key
}

// Return the smallest item contained in the tree
func (tree *Treap) Min() interface{} {

Expand Down
11 changes: 11 additions & 0 deletions treaps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -584,3 +584,14 @@ func TestTreap_lexicographicCmp(t *testing.T) {

assert.Equal(t, 1, t5.lexicographicCmp(t1))
}

func TestTreap_RemoveByPos(t *testing.T) {

tree := NewTreap(cmpInt, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)

assert.Equal(t, 0, tree.RemoveByPos(0))
assert.True(t, tree.check())

assert.Equal(t, 17, tree.RemoveByPos(16))
assert.True(t, tree.check())
}

0 comments on commit 0ec844b

Please sign in to comment.