Skip to content

Instantly share code, notes, and snippets.

extension Sequence {
func min(_ n: Int, by areInIncreasingOrder: (Element, Element) -> Bool) -> [Element] {
var iterator = makeIterator()
guard let first = iterator.next() else { return [] }
return withoutActuallyEscaping(areInIncreasingOrder) { areInIncreasingOrder in
var heap = NonEmptyMaxHeap(root: first, by: areInIncreasingOrder)
var heapSize = 1
while heapSize < n, let element = iterator.next() {
@timvermeulen
timvermeulen / vec_entry.rs
Created September 15, 2020 22:05
Vec entry
use std::cmp::Ordering;
pub trait VecExt {
type T;
fn find_entry<F>(&mut self, f: F) -> Entry<'_, Self::T>
where
F: FnMut(&Self::T) -> bool;
fn first_entry_where<F>(&mut self, f: F) -> Entry<'_, Self::T>
@timvermeulen
timvermeulen / SplitBetween.swift
Created August 23, 2020 15:37
Collection.split(between:)
extension Collection {
func split(between predicate: (Element, Element) throws -> Bool) rethrows -> [SubSequence] {
guard !isEmpty else { return [] }
var remainder = self[...]
var slices: [SubSequence] = []
for ((_, left), (index, right)) in indexed().pairs() {
if try predicate(left, right) {
slices.append(remainder.remove(upTo: index))
func product<A: Collection, B: Collection>(_ a: A, _ b: B) -> CartesianProductCollection<A, B> {
return CartesianProductCollection(a, b)
}
struct CartesianProductCollection<A: Collection, B: Collection> {
let a: A
let b: B
init(_ a: A, _ b: B) {
self.a = a
struct RotatedCollection<Base: Collection> {
let base: Base
let index: Base.Index
init(base: Base, shiftingToStart index: Base.Index) {
self.base = base
self.index = index
}
}
import Foundation
func measure<T>(_ block: () -> T) -> T {
let start = Date()
let result = block()
print("elapsed time: \(-start.timeIntervalSinceNow)")
return result
}
extension Sequence {
use std::mem::ManuallyDrop;
use std::ops::{Deref, DerefMut};
use std::ptr;
struct NonEmptyBinaryHeap<T> {
data: Vec<T>,
}
impl<T: Ord> NonEmptyBinaryHeap<T> {
fn with_root_and_capacity(root: T, capacity: usize) -> Self {
struct NonEmptyMaxHeap<Element: Comparable> {
private(set) var elements: [Element]
init(root: Element) {
self.elements = [root]
}
}
extension NonEmptyMaxHeap {
mutating func insert(_ element: Element) {
extension ClosedRange where Bound == Int {
init(_ string: Substring) {
if let range = string.range(of: "..") {
let x = Int(string.prefix(through: range.lowerBound).dropLast())!
let y = Int(string.suffix(from: range.upperBound))!
self = x...y
} else {
let x = Int(string)!
self = x...x
let totalSize = 300
func powerLevel(x: Int, y: Int, serialNumber: Int) -> Int {
let rackID = x + 10
return ((rackID * y + serialNumber) * rackID / 100) % 10 - 5
}
func part2(serialNumber: Int) -> String {
let grid = (1...totalSize).map { y in
(1...totalSize).map { x in