Semaphore Validity (Simulation)
JavaScript
Medium
4 views
Problem Description
You have capacity C and a list of events: ACQ or REL. ACQ means one async job started, REL means one finished. If at any time active goes above C or REL happens at active=0, print INVALID else VALID.
Input Format
Line1: C n. Next n lines: ACQ/REL.
Output Format
VALID or INVALID.
Sample Test Case
Input:
2 5
ACQ
ACQ
REL
ACQ
REL
Official Solution
const fs=require('fs');const lines=fs.readFileSync(0,'utf8').trim().split(/\
?\
/);if(!lines[0])process.exit(0);const [C,n]=lines[0].trim().split(/\\s+/).map(Number);let active=0;let ok=true;const step=async cmd=>{await Promise.resolve();if(cmd==='ACQ'){active++;if(active>C)ok=false;}else if(cmd==='REL'){if(active===0)ok=false;else active--;}};(async()=>{for(let i=1;i<=n;i++){await step(lines[i].trim());if(!ok)break;}process.stdout.write(ok?'VALID':'INVALID');})();
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!