Skip to content

Instantly share code, notes, and snippets.

View GuanshanLiu's full-sized avatar

Guanshan Liu GuanshanLiu

View GitHub Profile
extension Heap {
static func sort(_ elements: [Element], sort: @escaping (Element, Element) -> Bool) -> [Element] {
var heap = Heap(sort: sort)
for e in elements {
heap.insert(e)
}
var result = [Element]()
while !heap.isEmpty {
result.append(heap.remove()!)
}
/// Complexity: O(log n)
public mutating func remove() -> Element? {
guard !isEmpty else { return nil }
elements.swapAt(0, count - 1)
defer {
shiftDown(from: 0)
}
return elements.removeLast()
}
/// Complexity: O(log n)
public mutating func insert(_ element: Element) {
elements.append(element)
shiftUp(from: count - 1)
}
private mutating func shiftUp(from index: Int) {
var child = index
var parent = parentIndex(forChildAt: child)
while child > 0 && sort(elements[child], elements[parent]) {
public var isEmpty: Bool {
return elements.isEmpty
}
public var count: Int {
return elements.count
}
public func leftChildIndex(forParentAt index: Int) -> Int {
return 2 * index + 1
@GuanshanLiu
GuanshanLiu / 1.swift
Last active September 29, 2018 12:21
public struct Heap<Element: Equatable> {
private var elements = [Element]()
private let sort: (Element, Element) -> Bool
public init(sort: @escaping (Element, Element) -> Bool) {
self.sort = sort
}
}
import Cocoa
//typealias Parser<Token, A> = (Tokens) -> (A, Tokens)?
struct Parser<Tokens, A> {
let parse: (Tokens) -> (A, Tokens)?
}
typealias Stream<A> = Parser<String.CharacterView, A>
@GuanshanLiu
GuanshanLiu / gist:de4c4c92db031a3b765ccf10186ceb36
Last active August 26, 2016 02:29 — forked from casademora/gist:c4b19d8503767479c0e05a836de4aa4c
Animation behaviors demo from Shanghai Cocoaheads
//
// ViewController.swift
// BehaviorsDemo
//
// Created by Saul Mora on 8/25/16.
// Copyright © 2016 Magical Panda. All rights reserved.
//
import UIKit
@GuanshanLiu
GuanshanLiu / 1.swift
Created May 10, 2016 05:59
Project Euler in Swift #1 for Medium
let filtered = (1..<1000).filter {
$0 % 3 == 0 || $0 % 5 == 0
}
filtered.reduce(0, combine: +)
@GuanshanLiu
GuanshanLiu / test-create-playlist.js
Last active August 29, 2015 14:14
As I learn UI Automation with TTPod, the project I work on at Alibaba Inc.
try {
UIALogger.logStart("Testing creating a new playlist")
var target = UIATarget.localTarget()
var app = target.frontMostApp()
var window = app.mainWindow()
UIALogger.logMessage("Ensure we are at Mine section by ...")

Keybase proof

I hereby claim:

  • I am guanshanliu on github.
  • I am guanshanliu (https://keybase.io/guanshanliu) on keybase.
  • I have a public key whose fingerprint is 4D2A 8562 7939 E41E 6A32 EFE8 D823 7440 5617 4DC7

To claim this, I am signing this object: