Skip to content

Instantly share code, notes, and snippets.

@mrzasa
Last active January 19, 2019 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrzasa/b8436b36d4db70fffc3e14eca2dc2ff5 to your computer and use it in GitHub Desktop.
Save mrzasa/b8436b36d4db70fffc3e14eca2dc2ff5 to your computer and use it in GitHub Desktop.
Find intersection of arrays
# arrays
result = []
# initial data
values = arrays.map{|a| a.next}
while true
maximal_value = values.max
for i 0...values.size do
while values[i] < maximal_value do
values[i] = arrays[i].next
break unless values[i] # assuming that #next returns nil if there is no more elements
end
end
break if values.any{|v| v.nil? } # one of the arrays is finished
if values.all?{|v| v == maximal_value}
result << maximal_value
end
end
result
@stulentsev
Copy link

stulentsev commented Jan 19, 2019

func MergeIndexEnumerators4(enums []aindex.Enumerator, limit int) []uint32 {

	// if no enums, return empty intersection
	if len(enums) == 0 {
		return []uint32{}
	}
	// if any enumerators are nil, entire intersection will be empty
	for _, e := range enums {
		if e == nil {
			return []uint32{}
		}
	}

	// result buffer
	result := make([]uint32, 0, limit)

	// initialize "current values"
	heads := make([]uint32, len(enums))
	for idx, e := range enums {
		elem, _ := e.Next()
		heads[idx] = elem
	}

	for {
		min := MinUint32(heads) // point to advance all heads to
		shouldBreak := false
		for i, head := range heads {
			var err error
			for head > min {
				head, err = enums[i].Next()
				if err == io.EOF {
					shouldBreak = true // we exhausted this enum. Fast-track to completion
					break
				} else {
					heads[i] = head
				}
			}

		}
		if shouldBreak { break }

		if AllEqualUint32(heads, min) {
			result = append(result, min)
			if len(result) >= limit {
				return result
			}
			// advance all heads at once
			for idx, e := range enums {
				v, err := e.Next()
				if err == io.EOF {
					return result
				}
				heads[idx] = v
			}
		}
	}
	return result
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment