Created
November 21, 2020 15:46
-
-
Save nilsmartel/500291a9070a1b9594686b91fe1c197d to your computer and use it in GitHub Desktop.
Typ 3 Grammar to test if zipped representation of 2 binary numbers a and b is b= a+1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let log = n => console.log(n) | |
function binary(n) { | |
if (n == 0) return '0' | |
if (n == 1) return '1' | |
let last = String(n & 1 ) | |
return binary(n >> 1) + last | |
} | |
binary(7) | |
// zips to strings of equal length, appending 0s when neccesary | |
function zip(a, b) { | |
if (a.length > b.length) return zip(a, '0' + b) | |
if (a.length < b.length) return zip('0' + a, b) | |
let aa = [...a] | |
let ab = [...b] | |
let res = "" | |
for (let i =0; i < aa.length; i++) { | |
res += aa[i] + ab[i] | |
} | |
return res | |
} | |
zip("hello", "world") | |
function create(n) { | |
return zip(binary(n), binary(n+1)) | |
} | |
function verify(str) { | |
let a = [...str] | |
let i=0 | |
// (a==b)* | |
for (; i < a.length; i += 2) { | |
if (a[i] != a[i+1]) break | |
} | |
// (01) | |
if (!(a[i] == '0' && a[i+1] == '1')) return false | |
i += 2 | |
// (10)* | |
for (; i < a.length; i += 2) { | |
if (a[i] != '1' || a[i+1] != '0' ) break | |
} | |
// (a==b==0)* | |
for (; i < a.length; i += 2) { | |
if (a[i] != '0' || a[i+1] != '0') return false | |
} | |
return true | |
} | |
for (let i =0; i< 100; i++) | |
log(verify(create(i))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment