Mini Jump Interpreter
JavaScript
Hard
3 views
Problem Description
You get m instructions. Each instruction is: INC x, DEC x, JNZ x off. x is variable name (single word). Start all vars at 0. Execute from line 1. JNZ jumps relative if x!=0. Stop when pointer goes out. Print final value of variable a.
Input Format
First line m. Next m lines instructions.
Output Format
One integer value of a.
Sample Test Case
Input:
5
INC a
INC a
DEC a
JNZ a -2
INC a
Official Solution
const fs=require('fs');const lines=fs.readFileSync(0,'utf8').trim().split(/\
?\
/);if(!lines[0])process.exit(0);const m=Number(lines[0].trim());let ins=[];for(let i=1;i<=m;i++){const p=lines[i].trim().split(/\\s+/);ins.push(p);}const vars=new Map();const get=v=>vars.get(v)||0;const set=(v,x)=>{vars.set(v,x);};let ip=0;let steps=0;while(ip>=0 && ip<m && steps<=5000000){const p=ins[ip];const op=p[0];if(op==='INC'){set(p[1],get(p[1])+1);ip++;}else if(op==='DEC'){set(p[1],get(p[1])-1);ip++;}else if(op==='JNZ'){const v=get(p[1]);const off=Number(p[2]);if(v!==0)ip+=off;else ip++;}else ip++;steps++;}process.stdout.write(String(get('a')));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!