Skip to content

Instantly share code, notes, and snippets.

@cemolcay
Created April 12, 2022 10:32
Show Gist options
  • Save cemolcay/7d7cb243f39b42a5a236b91fbfe6e9dd to your computer and use it in GitHub Desktop.
Save cemolcay/7d7cb243f39b42a5a236b91fbfe6e9dd to your computer and use it in GitHub Desktop.
ShiftBud bit shift algorithm.
//
// TuringMachine.swift
// TuringBud
//
// Created by Cem Olcay on 3/8/22.
//
import Foundation
class TuringMachine {
var value: UInt16 = 0
var currentStep: UInt16 = 0
var length: UInt16 = 16
init() {
value = UInt16.random(in: UInt16.min..<UInt16.max)
}
func advance(bias: Double) {
// Rotate the bit value
value = shiftBitRight(value)
if bias >= 0.5 {
// Randomisation chance increases if the knob is near noon.
// No randomisation chance if knob is fully rotated to right aka loop the 'length amount' steps.
if Double.random(in: 0.5 ... 1.0) > bias {
let random = randomBit()
value = setBit(value, at: 15, to: random)
}
} else {
// Flip chance increases if knob is near noon.
// Always filp if the knob is fully rotated to the left aka loop twice the 'length amount' steps.
if Double.random(in: 0.0 ... 0.5) >= bias {
value = toggleBit(value, at: 15)
}
}
currentStep += 1
if currentStep >= length {
currentStep = 0
if bias == 0 || bias == 1 {
var push = value
for _ in 0..<length {
push = shiftBitLeft(push)
}
value = push
}
}
}
func randomBit() -> UInt16 {
return Bool.random() ? 1 : 0
}
func setBit(_ i: UInt16, at n: UInt16, to k: UInt16) -> UInt16 {
if k > 0 {
return i | ( 1 << n)
}
return i & ~(1 << n)
}
func toggleBit(_ i: UInt16, at n: UInt16) -> UInt16 {
return i ^ (1 << n)
}
func getBit(_ i: UInt16, at n: UInt16) -> UInt16 {
return ((i >> n) & 1) == 1 ? 1 : 0
}
func shiftBitRight(_ i: UInt16) -> UInt16 {
let lastBit = getBit(i, at: 0)
let shift = (i >> 1)
return setBit(shift, at: 15, to: lastBit)
}
func shiftBitLeft(_ i: UInt16) -> UInt16 {
let firstBit = getBit(i, at: 15)
let shift = (i << 1)
return setBit(shift, at: 0, to: firstBit)
}
func printBit(_ i: UInt16) {
let s = String(i, radix: 2)
let p = (s.count..<16).map({ _ in "0" }).joined()
print("\(i)\t\(p + s)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment