Skip to content

Instantly share code, notes, and snippets.

@NoahPeeters
NoahPeeters / threeNPlusOne.swift
Created May 14, 2017 10:42
A simple swift sequence/iterator for the 3n+1 problem
class threeNPlusOne: Sequence, IteratorProtocol {
var n: UInt
init(withStartNumber startN: UInt) {
n = startN * 2 // multiply by 2 so that n is a even number and will be devided by two in the first next() call
}
func next() -> UInt? {
if n % 2 == 0 { // even
n /= 2
extension Sequence {
public func filterMap<T>(map: (Self.Iterator.Element) throws -> (Bool, T)) rethrows -> [T] {
var array : [T] = []
for element in self {
do {
let (result, value) = try map(element)
if result {
array.append(value)
}
}
@NoahPeeters
NoahPeeters / restrict.swift
Last active July 3, 2017 22:27
Restrict the value of any comparable type using easy-to-use functions
/// Returns value if it's contained in range; otherwise the returned value is limited to the range's bounds.
///
/// - Parameters:
/// - value: The value to restrict.
/// - range: The range used to restict the value.
/// - Returns: The resticted value.
func restrict<T>(_ value: T, between range: ClosedRange<T>) -> T {
return min(range.upperBound, max(range.lowerBound, value))
}
@NoahPeeters
NoahPeeters / QuantumBogoSort.swift
Created November 26, 2017 15:10
The awesome quantum logo sort
import Foundation
extension MutableCollection {
/// Shuffles the contents of this collection.
mutating func shuffle() {
let c = count
guard c > 1 else { return }
for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
@NoahPeeters
NoahPeeters / keybase.md
Created February 11, 2018 17:24
keybase.md

Keybase proof

I hereby claim:

  • I am noahpeeters on github.
  • I am noahpeeters (https://keybase.io/noahpeeters) on keybase.
  • I have a public key ASDehL9DdQ3y3-Bxbq8XceFF7LFjD9mPG0Mz8aVBSiGDxgo

To claim this, I am signing this object:

@NoahPeeters
NoahPeeters / devnull.swift
Created May 4, 2018 20:53
Simple struct to send all assignments to the void.
import Foundation
public class Dev<Value> {
public static var null: Value {
get {
fatalError("You are not allowed to read from dev/null of \(self)")
}
set {}
}
original_filename="lekciju_saraksts.ics"
filename=translated_$original_filename
cp $original_filename $filename
translate () {
sed -i '.bak' "s/$1/$2/g" $filename
}
translate 'Adaptīvas datu apstrādes sistēmas' 'Adaptive Data Processing Systems'
public typealias Predicate<Value> = (Value) -> Bool
public func && <Value>(lhs: @escaping Predicate<Value>, rhs: @escaping Predicate<Value>) -> Predicate<Value> {
{ lhs($0) && rhs($0) }
}
public func || <Value>(lhs: @escaping Predicate<Value>, rhs: @escaping Predicate<Value>) -> Predicate<Value> {
{ lhs($0) || rhs($0) }
}