Skip to content

Instantly share code, notes, and snippets.

@dtinth
Created July 14, 2011 17:20
Show Gist options
  • Save dtinth/1082930 to your computer and use it in GitHub Desktop.
Save dtinth/1082930 to your computer and use it in GitHub Desktop.
HLP Hackathon : Operator Is Me (Annotated)
# Operator Is Me - Annotated Source Code Solution
# written by Thai Pangsakulyanont (@dtinth)
# in CoffeeScript, I love it.
#
# I added commentaries to this source code after I finished writing it
# at the time of competitions there were no comments at all.
fs = require 'fs'
# This class manages each call.
# Initiate it with the call time and calling rate, and later give it
# the hangup time, it will return the call cost.
class Call
constructor: (@start, @rate) ->
check: (@finish) ->
seconds = Math.round (@finish.getTime() - @start.getTime()) / 1000
duration = Math.ceil seconds / 60
return @rate[0] + @rate[1] * Math.max(0, duration - 3)
# The rates hash looks something like:
# { "key": [ cost for first 3 minutes, cost after that ], ... }
# The key is in 2 format, the first type is the time-based rate,
# which the key is minutes since midnight, so it ranges from 0 and 1339.
# Another type is in form of source:destination.
rates = {}
# Read the input file, and split it by sections.
input = fs.readFileSync '/Users/dttvb/Downloads/file1279.txt', 'utf-8'
sections = input.split /\r\n\r\n/
# This variable holds the total money.
total = 0
# This hash holds the active calls, the key is in form of source:destination.
# Each item is an instance of Call class.
calls = {}
# Go through first section, and and time-based rates.
sections[0].replace /(\d+):(\d+) ([\d\.]+) ([\d\.]+)/g, (a, b, c, d, e) ->
start = 60 * b + 1 * c
for time in [start...1440]
rates[time] = [1 * d, 1 * e]
# Go through the second section, and add number-based rates.
sections[1].replace /(\d+) (\d+) ([\d\.]+) ([\d\.]+)/g, (a, b, c, d, e) ->
rates[b + ':' + c] = [1 * d, 1 * e]
# Go through the third section:
sections[2].replace /(\d+-\d+-\d+ (\d+):(\d+):\d+) (\d+) (\d+) ([CH])/g, (a, t, b, c, d, e, f) ->
# Calculate the time.
t = new Date t
if f == 'C'
# Find the appropriate rate to call. First by finding number-based rate
# and fallback to time-based rate if it's not found.
rate = rates[d + ':' + e]
rate = rates[60 * b + 1 * c] if not rate
# Also add create and add the call to the hash of active calls.
call = new Call t, rate
calls[d + ':' + e] = call
else if f == 'H'
# Calculate the money and add it to the totals.
if calls[d + ':' + e]
total += calls[d + ':' + e].check t
delete calls[d + ':' + e]
# Finally print the total money!
console.log total.toFixed 2
@dtinth
Copy link
Author

dtinth commented Jul 14, 2011

I ♥ CoffeeScript!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment