First Fulfilled with Concurrency Limit
JavaScript
Hard
2 views
Problem Description
Given n numbers and limit k. Task succeeds if x is prime (returns x), else rejects. Run with max k in-flight and print the first fulfilled value in input order; if none, print NONE.
Input Format
Line1: n k. Line2: n integers.
Output Format
Value or NONE.
Sample Test Case
Input:
8 3
1 4 6 7 9 11 15 2
Official Solution
const fs=require('fs');const raw=fs.readFileSync(0,'utf8').trim();if(!raw)process.exit(0);const a=raw.split(/\\s+/).map(Number);let i=0;const n=a[i++];const k=a[i++];const arr=a.slice(i,i+n);const isPrime=x=>{if(x<2)return false;if(x%2===0)return x===2;for(let d=3;d*d<=x;d+=2)if(x%d===0)return false;return true;};const task=async x=>{await Promise.resolve();if(!isPrime(x))throw new Error('NO');return x;};(async()=>{let next=0,active=0,done=0;let bestIndex=null;let bestValue=null;await new Promise(resolve=>{const launch=()=>{while(active<k && next<n){const idx=next++;active++;task(arr[idx]).then(v=>{if(bestIndex===null||idx<bestIndex){bestIndex=idx;bestValue=v;}}).catch(()=>{}).finally(()=>{active--;done++;if(done===n)resolve();else launch();});}};launch();});process.stdout.write(bestValue===null?'NONE':String(bestValue));})();
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!