UNPKG

stsys

Version:

String rewriting system (semi-Thue system)

55 lines (50 loc) 1.43 kB
// increase stack size through parameter --stack_size=<size>. e.g. // node --stack_size=100000 ack 3 11 function a(n, m) { if (n === 0) return m + 1; if (m === 0) return a(n - 1, 1); return a(n - 1, a(n, m - 1)); } function a2(n, m) { const stack = [n, m]; let l = 1; do { if (stack[l - 1] === 0) stack[--l] = stack.pop() + 1; else if (stack[l] === 0) { stack[l - 1] -= 1; stack[l] = 1; } else { stack.push(stack[l] - 1); stack[l] = stack[l - 1]; stack[l++ - 1] -= 1; } } while (l > 0); return stack[0]; } function isValidInput(n, m) { const regex = /^\d+$/; return regex.test(n) && regex.test(m); } if (process.argv.length < 4 || process.argv.length > 5 || !isValidInput(process.argv[2], process.argv[3])) { console.log('USAGE:', process.argv0, process.argv[1], '<n>', '<m>', '[-s]'); console.log(' where <n> and <m> are natural numbers, i.e. from the set {0, 1, 2, ...}'); console.log(' Computes the value A(<n>,<m>) of the Ackermann function A for the given natural numbers <n> and <m>.'); console.log(' Use option -s to invoke the standard recursive implemenation of the Ackermann function.'); } else { console.log('Computing A(' + process.argv[2] + ',' + process.argv[3] + ')'); console.log('Result:', (process.argv.length === 5 && process.argv[4] === '-s' ? a : a2)(process.argv[2] * 1, process.argv[3] * 1)); }