Skip to content

Instantly share code, notes, and snippets.

@elliotlarson
Created July 5, 2017 18:44
Show Gist options
  • Select an option

  • Save elliotlarson/73aeb91e57529de8edcfa7472c830802 to your computer and use it in GitHub Desktop.

Select an option

Save elliotlarson/73aeb91e57529de8edcfa7472c830802 to your computer and use it in GitHub Desktop.
Voting Exercise
var fs = require('fs');
var readline = require('readline');
var stream = require('stream');
var instream = fs.createReadStream('votes.txt');
var outstream = new stream;
var rl = readline.createInterface(instream, outstream);
var ballotCount = 0;
var ballotVotes = [];
var ballotCounts = {};
function incrementBallotCountForKey(key) {
if (ballotCounts[key] === undefined) {
ballotCounts[key] = 1;
} else {
ballotCounts[key]++;
}
}
function addCountsForBallot(ballotVotes) {
let key1 = ballotVotes[0] + '-over-' + ballotVotes[1];
incrementBallotCountForKey(key1);
let key2 = ballotVotes[0] + '-over-' + ballotVotes[2];
incrementBallotCountForKey(key2);
let key3 = ballotVotes[1] + '-over-' + ballotVotes[2];
incrementBallotCountForKey(key3);
}
rl.on('line', function(line) {
if (ballotCount == 3) {
addCountsForBallot(ballotVotes);
// console.log(ballotVotes.join(',')); // part # 2
ballotVotes = [];
ballotCount = 0;
}
var candidateId = line.substring(37, 43);
ballotVotes[ballotCount] = candidateId;
ballotCount++;
});
rl.on('close', function() {
console.log(ballotCounts);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment