MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / NewSqrtDecomposition

Function NewSqrtDecomposition

sqrt/sqrtdecomposition.go:34–59  ·  view source on GitHub ↗

Create a new SqrtDecomposition instance with the parameters as specified by SqrtDecomposition comment Assumptions: - len(elements) > 0

(
	elements []E,
	querySingleElement func(element E) Q,
	unionQ func(q1 Q, q2 Q) Q,
	updateQ func(oldQ Q, oldE E, newE E) (newQ Q),
)

Source from the content-addressed store, hash-verified

32// Assumptions:
33// - len(elements) > 0
34func NewSqrtDecomposition[E any, Q any](
35 elements []E,
36 querySingleElement func(element E) Q,
37 unionQ func(q1 Q, q2 Q) Q,
38 updateQ func(oldQ Q, oldE E, newE E) (newQ Q),
39) *SqrtDecomposition[E, Q] {
40 sqrtDec := &SqrtDecomposition[E, Q]{
41 querySingleElement: querySingleElement,
42 unionQ: unionQ,
43 updateQ: updateQ,
44 elements: elements,
45 }
46 sqrt := math.Sqrt(float64(len(sqrtDec.elements)))
47 blockSize := uint64(sqrt)
48 numBlocks := uint64(math.Ceil(float64(len(elements)) / float64(blockSize)))
49 sqrtDec.blocks = make([]Q, numBlocks)
50 for i := uint64(0); i < uint64(len(elements)); i++ {
51 if i%blockSize == 0 {
52 sqrtDec.blocks[i/blockSize] = sqrtDec.querySingleElement(elements[i])
53 } else {
54 sqrtDec.blocks[i/blockSize] = sqrtDec.unionQ(sqrtDec.blocks[i/blockSize], sqrtDec.querySingleElement(elements[i]))
55 }
56 }
57 sqrtDec.blockSize = blockSize
58 return sqrtDec
59}
60
61// Performs a query from index start to index end (non included)
62// Assumptions:

Callers 1

TestSqrtDecompositionFunction · 0.92

Calls

no outgoing calls

Tested by 1

TestSqrtDecompositionFunction · 0.74