Skip to content

Instantly share code, notes, and snippets.

@joanromano
joanromano / Monoqueue.swift
Created September 15, 2019 07:27
An array based implementation of a Monoqueue
struct Monoqueue<T: Comparable> {
var array = [(value: T, count: Int)]()
var max: T {
return array.first!.value
}
mutating func push(_ value: T) {
var count = 0
while !array.isEmpty, array.last!.value < value {
@joanromano
joanromano / SegmentTree.swift
Created September 8, 2019 10:18
An array based implementation of a segment tree
extension Int {
fileprivate func nextPowerOf2() -> Int {
guard self != 0 else {
return 1
}
return 1 << (bitWidth - (self - 1).leadingZeroBitCount)
}
}
struct SegmentTree<T: Comparable> {
@joanromano
joanromano / PriorityQueue.swift
Created September 8, 2019 10:17
An array based implementation of a PriorityQueue
struct PriorityQueue<T> {
private var array: [T] = []
private let priority: (T, T) -> Bool
var count: Int { return array.count }
var isEmpty: Bool { return array.isEmpty }
var top: T? { return array.first }
init(_ values: [T], priority: @escaping (T, T) -> Bool) {
@joanromano
joanromano / Trie.swift
Created September 8, 2019 10:15
A basic trie implementation in Swift supporting prefix and pattern searches
class TrieNode {
var hash: [Character:TrieNode] = [:]
var endOfWord: Bool = false
}
class Trie {
var root = TrieNode()
init() {}
@joanromano
joanromano / Bisect.swift
Created September 8, 2019 10:10
Bisection searching algorithms
extension Array where Element: Comparable {
// This implementations are inspired in https://github.com/python/cpython/blob/master/Lib/bisect.py
/// Return the index where to insert value in the receiver, assuming the receiver is sorted
///
/// - Parameters:
/// - value: The position of the text in current context
/// - min: The lower bound where to perform the search
/// - max: The upper bound where to perform the search
/// - Returns: An index such that all elements in self[:i] have element < value, and all elements in
@beldaz
beldaz / PDFTableStripper.java
Created October 14, 2017 22:09
Class to extract tabular PDF text using PDFBox
/*
* Copyright 2017 Beldaz (https://github.com/beldaz)
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
struct HeightedUnion {
typealias QuickUnionRootHeight = (root: Int, height: Int)
private var ids: [Int]
// Complexity: O(n)
init(_ N: Int) {
ids = Array(0..<N)
}