JSON Lines Sum (Skip Bad)
JavaScript
Medium
6 views
Problem Description
First line n, then n lines each should be a JSON number. Sum valid numbers. Count how many lines were bad JSON or not a finite number. Print: sum badCount.
Input Format
Line1: n. Next n lines: JSON number.
Output Format
One line: sum badCount.
Official Solution
const fs=require('fs');const lines=fs.readFileSync(0,'utf8').trim().split(/\
?\
/);if(!lines[0])process.exit(0);const n=Number(lines[0]);let sum=0;let bad=0;for(let i=1;i<=n;i++){const line=(lines[i]||'').trim();try{const v=JSON.parse(line);if(typeof v!=='number'||!Number.isFinite(v))throw new Error('BAD');sum+=v;}catch(e){bad++;}}process.stdout.write(String(sum)+' '+String(bad));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!