Skip to content

Instantly share code, notes, and snippets.

@nuclearace
nuclearace / main.swift
Created November 21, 2019 14:14
gray code
func grayEncode(_ i: Int) -> Int {
return (i >> 1) ^ i
}
func grayDecode(_ i: Int) -> Int {
switch i {
case 0:
return 0
case _:
return i ^ grayDecode(i >> 1)
@nuclearace
nuclearace / main.swift
Created November 13, 2019 13:16
adder
typealias FourBit = (Int, Int, Int, Int)
func halfAdder(_ a: Int, _ b: Int) -> (Int, Int) {
return (a ^ b, a & b)
}
func fullAdder(_ a: Int, _ b: Int, carry: Int) -> (Int, Int) {
let (s0, c0) = halfAdder(a, b)
let (s1, c1) = halfAdder(s0, carry)
@nuclearace
nuclearace / life.swift
Last active November 12, 2019 12:17
glider gun
public struct Cell: Hashable {
public var x: Int
public var y: Int
public var neighbors: [Cell] {
[
Cell(x: x - 1, y: y - 1),
Cell(x: x, y: y - 1),
Cell(x: x + 1, y: y - 1),
Cell(x: x - 1, y: y),
@nuclearace
nuclearace / main.swift
Created November 6, 2019 12:10
chowla numbers
extension Dictionary where Key == ClosedRange<Int> {
subscript(n: Int) -> Value {
get {
guard let key = keys.first(where: { $0.contains(n) }) else {
fatalError("dict does not contain range for \(n)")
}
return self[key]!
}
import Foundation
import Playground
private let lock = DispatchSemaphore(value: 1)
private let queue = DispatchQueue(label: "worker", attributes: .concurrent)
private let nWorkers = 5
private let stopAt = 1 << 30
private var i = 33550336
private var running = nWorkers
@nuclearace
nuclearace / main.swift
Created October 23, 2019 13:17
Bankers
print("Enter the number of resources: ", terminator: "")
guard let resources = Int(readLine(strippingNewline: true)!) else {
fatalError()
}
print("Enter the number of processes: ", terminator: "")
guard let processes = Int(readLine(strippingNewline: true)!) else {
fatalError()
@nuclearace
nuclearace / main.swift
Last active October 22, 2019 09:55
text between
import Foundation
public extension String {
func textBetween(_ startDelim: String, and endDelim: String) -> String {
precondition(!startDelim.isEmpty && !endDelim.isEmpty)
let startIdx: String.Index
let endIdx: String.Index
if startDelim == "start" {
@nuclearace
nuclearace / main.swift
Created October 18, 2019 16:03
mcnugget numbers
func maxNugget(limit: Int) -> Int {
var (max, sixes, nines, twenties, i) = (0, 0, 0, 0, 0)
mainLoop: while i < limit {
sixes = 0
while sixes * 6 < i {
if sixes * 6 == i {
i += 1
continue mainLoop
@nuclearace
nuclearace / MTRandom.swift
Last active September 16, 2019 11:52
collatzing
import Foundation
public struct MTRandom: RandomNumberGenerator {
private var index = 312
private var mt = [UInt64](repeating: 0, count: 312)
public init(seed: UInt64 = .random(in: .min ... .max)) {
mt[0] = seed
for i in 1..<312 {
import Foundation
public final class AtomicBuckets: CustomStringConvertible {
public var count: Int {
return buckets.count
}
public var description: String {
return withBucketsLocked { "\(buckets)" }
}