Context-free grammar for unary addition
w =S => 1S1 => 11S11 => 110S011 => 1101S1011 => 1101p1011 Accept
function delta(c, p) { // Unary addition
if (c=='0' && p=='S') return "0S0";
if (c=='1' && p=='S') return "1S1";
if (c=='p' && p=='S') return "p";
return ''; //default -- no transition
}
function generate(w, init='S') {
//w: input String
//init: start symbol
//g: generated String
let txt = init, g = init
for (let i=0; i<w.length; i++) {
let c = w[i], p = g[i]
if (c == p) continue
let d = delta(c, p)
if (d == '') {
input.selectionStart = i
input.selectionEnd = i+1
break
}
g = g.replace(p, d)
txt += "\n=> "+g
}
return txt+'\n'+(w==g ? "Accept" : "Reject")
}