Skip to content

Instantly share code, notes, and snippets.

@mokkabonna
Last active October 23, 2019 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mokkabonna/b8872f8f6ec9d4b9ad0e59c9c0b3373c to your computer and use it in GitHub Desktop.
Save mokkabonna/b8872f8f6ec9d4b9ad0e59c9c0b3373c to your computer and use it in GitHub Desktop.
Add 1 binary, no if in program, besides the inherent if in biwise operators. stream compatible
// add 1 to any binary number, left aligned, to support streaming
var numbers = Array(20)
.fill(0)
.map((n, i) => i
.toString(2)
.split('')
.reverse()
)
console.log(numbers)
function add1(bits) {
var programBits = bits.reduce((all, bit) => {
var calculated = all[all.length - 1] & bit
all.push(calculated)
return all
}, [1])
var program = parseInt(programBits.reverse().join(''), 2)
var input = parseInt(bits.slice(0).reverse().join(''), 2)
// todo also keep program, as that is result -1
var result = input ^ program
return result.toString(2).split('').reverse()
}
var added1 = numbers.map(add1)
console.log(added1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment