Created
May 2, 2020 04:41
-
-
Save louy2/6fbaef06f8a7ceeec7327f3329f2ca8d to your computer and use it in GitHub Desktop.
Wrote another truth table generator in Firefox console
This file contains hidden or 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 and2 = (x, y) => { | |
if (Boolean(x)) { | |
return Boolean(y) | |
} else { | |
return false | |
} | |
} | |
let or2 = (x, y) => { | |
if (Boolean(x)) { | |
return true | |
} else { | |
return Boolean(y) | |
} | |
} | |
let andn = (...xs) => { | |
let r = true | |
for (let x of xs) { | |
r = and2(x, r) | |
} | |
return r | |
} | |
let orn = (...xs) => { | |
let r = false | |
for (let x of xs) { | |
r = or2(x, r) | |
} | |
return r | |
} | |
let and = (...xs) => { return { op: 'and', xs } } | |
let or = (...xs) => { return { op: 'or', xs } } | |
let evallit = (expr) => { | |
if (!expr.op) { | |
return Boolean(expr) | |
} | |
let rs = []; | |
let { op, xs } = expr | |
for (let x of xs) { rs.push(eval(x)) } | |
if (op === 'and') { | |
return andn(...rs) | |
} else if (op === 'or') { | |
return orn(...rs) | |
} | |
} | |
let extract_vars = (expr) => { | |
let extract_vars_rec = (expr, vars) => { | |
if (!expr.op) { | |
let x = expr | |
if (typeof x === 'string') { | |
if (!vars.includes(x)) { vars.push(x) } | |
} | |
return vars | |
} | |
let { op, xs } = expr | |
for (let x of xs) { extract_vars_rec(x, vars) } | |
return vars | |
} | |
return extract_vars_rec(expr, []) | |
} | |
let generate_attempts = (vars) => { | |
let attempts = [] | |
let num_of_attempts = Math.pow(2, vars.length) | |
for (let ia = 0; ia < num_of_attempts; ia++) { | |
let att = {} | |
for (let iv = 0; iv < vars.length; iv++) { | |
let guess = Math.floor(ia / Math.pow(2, iv)) % 2 | |
att[vars[iv]] = guess | |
} | |
attempts.push(att) | |
} | |
return attempts | |
} | |
// let vars = extract_vars() | |
// generate_attempts(vars) | |
let eval = (expr, att) => { | |
if (!expr.op) { | |
if (typeof expr === 'string') { return att[expr] } | |
return Boolean(expr) | |
} | |
let rs = []; | |
let { op, xs } = expr | |
for (let x of xs) { rs.push(eval(x, att)) } | |
if (op === 'and') { | |
return andn(...rs) | |
} else if (op === 'or') { | |
return orn(...rs) | |
} | |
} | |
let truth_table = (expr) => { | |
let vars = extract_vars(expr) | |
let attempts = generate_attempts(vars) | |
let rs = [] | |
for (let att of attempts) { | |
rs.push({...att, result: eval(expr, att)}) | |
} | |
return rs | |
} | |
let test1 = and('x', 'y') | |
let test2 = and(and('x', 'y', or('y', 'z', 0)), or('x', 'i')) | |
JSON.stringify(truth_table(test2), null, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment