Dynamically stores additive values and get arbitrary sub-range sums in O(log(n)) time.

Overview

SegmentQuery

Eonil, 2019.

Build Status

Dynamically stores additive values and get arbitrary sub-range sums in O(log(n)) time.

This is an implementation of something called "segment-tree" or "interval-tree". You insert/remove lengths of consecutive segments and query positions on it. I'm not sure which one is correct name.

How to Use

Add dependency.

.package(url: "https://github.com/eonil/swift-segment-query", .branch("master")),

And use.

import SegmentQuery

var x = SegmentQuery<Int>()

/// Append segment lengths.
x.append(contentsOf: [111,222,333])

/// Get subrange sum.
let s = x[1..<3].sum
assert(s == 222+333)

/// Get start/end offsets of a segment 1.
let a = x[..<1].sum
let b = x[...1].sum
let c = a..<b

/// Get index of segment and in-segment-offset from an offset.
let (a,b) = x.location(at: 230)
assert(a == 1)
assert(b == 8)

Requirements

  • Swift 5.x.
  • Swift Package Manager.

Complexity

  • O(log(n)) for element query/insert/update/remove and sub-sum query.

Performance

I couldn't find other segment query library written in Swift for comparison. Instead, I performed insert/remove performance comparison with well-known B-Tree library written by Lőrentey. This is one-by-one random Int number insert/remove at random location on 64-bit macOS,

With list of 128K values,

  • 4x faster than Swift.Array.
  • Very close speed to BTree.List.

With list of 1 million values,

  • 4x faster than BTree.List.

Run SegmentQueryBenchmark to get numbers on your machine.

Implementation

  • B-Tree based with no key stored.
  • Only values are stored.
  • Values are stored only on leafs.
  • Buffer sizes are optimized for ordered list behavior with dynamic automatic sum.

Missing Features

  • Balancing after remove. (Now only insertion is balanced by B-Tree insertion algorithm)
  • Bulk insert/remove implementation.
  • Sequential element iteration in O(n) time. Now it's O(n log n).
  • Sub-sum indexing in each node. We can store sub-sum for each branch/leaf node children to perform binary search to get an item. There is a trade-off, but I didn't try due to lack of time.

Credit & License

Copyright(C) Eonil 2019. All rights reserved. Using of this code is licensed under "MIT License".

You might also like...
A customisable view for entering arbitrary length pins, codes or passwords in iOS. Supports iOS 12 one time codes.
A customisable view for entering arbitrary length pins, codes or passwords in iOS. Supports iOS 12 one time codes.

CBPinEntryView CBPinEntryView is a view written in Swift to allow easy and slick entry of pins, codes or passwords. It allows backspacing, dismissal o

A TimeZonePicker UIViewController similar to the iOS Settings app. Search and select from a range of cities and countries to find your most suitable time zone.
A TimeZonePicker UIViewController similar to the iOS Settings app. Search and select from a range of cities and countries to find your most suitable time zone.

TimeZonePicker A TimeZonePicker UIViewController similar to the iOS Settings app. Search and select from a range of cities and countries to find your

Allows users to pull in new song releases from their favorite artists and provides users with important metrics like their top tracks, top artists, and recently played tracks, queryable by time range.

Spotify Radar Spotify Radar is an iOS application that allows users to pull in new song releases from their favorite artists and provides users with i

CryptoWatch is an application to fetch the currency datas from an api and show their updated values to user. User is able to get the coin datas without an extra effort.
CryptoWatch is an application to fetch the currency datas from an api and show their updated values to user. User is able to get the coin datas without an extra effort.

CryptoTracker In order to combine my work and studies, I made a small project that keeps the user's registration datas in memory, checks them when nee

Simple Design for Swift bridge with Javascript. Also can get javascript console.log.
Simple Design for Swift bridge with Javascript. Also can get javascript console.log.

SDBridgeOC is here. If your h5 partner confused about how to deal with iOS and Android. This Demo maybe help. YouTube video is here. bilibili Video is

‪‪An app that stores and displays the information entered by the user‬‬

To do list :‬‬ ‪‪An app that stores and displays the information entered by the user‬‬ ‪‪The user can : Add, delete one or clear all , Edit, Show the

Date Formatter Pool - is a small utility that creates and stores your Date Formatter for simpler reuse
Date Formatter Pool - is a small utility that creates and stores your Date Formatter for simpler reuse

Date Formatter Pool Date Formatter Pool - is a small utility that creates and stores your Date Formatter for simpler reuse Installation is available i

A Swift property wrapper which stores the previous value

swift-with-previous A Swift property wrapper which stores the previous value. The previous value can be get by the projected value $propertyName. impo

Automatically generate GraphQL queries and decode results into Swift objects, and also interact with arbitrary GitHub API endpoints

GitHub API and GraphQL Client This package provides a generic GitHub API client (GithubApiClient) as well as Codable-like GitHub GraphQL querying and

Time is a Swift package that makes dealing with calendar values a natural and straight-forward process.

Time Time is a Swift package that makes dealing with calendar values a natural and straight-forward process. Working with calendars can be extremely c

Arbitrary-precision arithmetic in pure Swift
Arbitrary-precision arithmetic in pure Swift

Overview API Documentation License Requirements and Integration Implementation Notes Full-width multiplication and division primitives Why is there no

Swift type modelling the success/failure of arbitrary operations.

Result This is a Swift µframework providing ResultValue, Error. ResultValue, Error values are either successful (wrapping Value) or failed (wrappi

Swift type modelling the success/failure of arbitrary operations.

Result This is a Swift µframework providing ResultValue, Error. ResultValue, Error values are either successful (wrapping Value) or failed (wrappi

Demo App for Picture-in-Picture of Arbitrary UIView in iOS
Demo App for Picture-in-Picture of Arbitrary UIView in iOS

日本語 UIPiPDemo This is a demo app for displaying an arbitrary UIView in iOS using picture-in-picture. It can be used to display information that chan

Arbitrary precision fraction in Swift.

Fraction Arbitrary precision fraction in Swift. Usage Fraction can be converted from BinaryInteger, BinaryFloatingPoint or String. It supports nearly

reward the user for watching videos to get coins then use them to get rid of annoying admob ads
reward the user for watching videos to get coins then use them to get rid of annoying admob ads

reward the users for watching youtube videos to the end to earn coins, then use them to get rid of annoying admob ads like banners, interstitial & reward videos

This to learn such as : Add Target , NSNotification Center Send/Get Data , Observer Override , resize Data By Byte , UIImagePicker Delegate , UIAlert Handle , Top ViewController , Get pickerController

Technicalisto How to Create UIButton Class to Pick Data Image Purpose Learn this topics With exact Task Add Target NSNotification Center Send/Get Data

Open source implementation of Apple's Combine framework for processing values over time.
Open source implementation of Apple's Combine framework for processing values over time.

OpenCombine Open-source implementation of Apple's Combine framework for processing values over time. The main goal of this project is to provide a com

Owner
Eonil
Hobo.
Eonil
The most flexible and powerful way to build a form on iOS

The most flexible and powerful way to build a form on iOS. Form came out from our need to have a form that could share logic between our iOS apps and

HyperRedink 32 Aug 15, 2022
XLForm is the most flexible and powerful iOS library to create dynamic table-view forms. Fully compatible with Swift & Obj-C.

XLForm By XMARTLABS. If you are working in Swift then you should have a look at Eureka, a complete re-design of XLForm in Swift and with more features

xmartlabs 5.8k Jan 6, 2023
A framework to validate inputs of text fields and text views in a convenient way.

FormValidatorSwift The FormValidatorSwift framework allows you to validate inputs of text fields and text views in a convenient way. It has been devel

ustwo™ 500 Nov 29, 2022
Discover new programming concepts and more new SwiftUI 2 features in this section

Africa-Zoo One thing is sure, we will discover new programming concepts and more new SwiftUI 2 features in this section. TOPICS ARE COVERED: JSON with

Noye Samuel 2 Nov 8, 2022
SherlockForms - An elegant SwiftUI Form builder to create a searchable Settings and DebugMenu screens for iOS

??️‍♂️ SherlockForms What one man can invent Settings UI, another can discover i

Yasuhiro Inami 98 Dec 27, 2022
Simple and Elegant Range(A,B) to Range(P,Q) mapper in less then five lines of code.

HSRange Description HSRangeConvertor Simple and Elegant Range[A,B] to Range[P,Q] mapper in less then three lines of code. E.g. Suppose we have Range[1

Hitendra Hckr 10 Sep 29, 2021
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

Yonat Sharon 326 Dec 29, 2022
UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizontal.

MultiSlider UISlider clone with multiple thumbs and values, range highlight, optional snap intervals, optional value labels, either vertical or horizo

Yonat Sharon 326 Dec 29, 2022