Limit Concurrency and Preserve Order
JavaScript
Hard
4 views
Problem Description
Given n numbers and limit k, apply async function f(x)=x*x with at most k in flight. Output results in original order.
Input Format
Line1: n k. Line2: n integers.
Output Format
One line results.
Official Solution
const fs=require('fs');const raw=fs.readFileSync(0,'utf8').trim();if(!raw)process.exit(0);const a=raw.split(/\\s+/);let i=0;const n=Number(a[i++]);const k=Number(a[i++]);let arr=[];for(let j=0;j<n;j++)arr.push(BigInt(a[i++]));const f=async x=>{await Promise.resolve();return x*x;};(async()=>{const res=new Array(n);let next=0;let active=0;let done=0;return new Promise(resolve=>{const launch=()=>{while(active<k && next<n){const idx=next++;active++;f(arr[idx]).then(v=>{res[idx]=v;}).catch(()=>{res[idx]=0n;}).finally(()=>{active--;done++;if(done===n)resolve();else launch();});}};launch();}).then(()=>{process.stdout.write(res.map(v=>v.toString()).join(' '));});})();
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!