Skip to content

Instantly share code, notes, and snippets.

@soswow
Created April 7, 2014 18:33
Show Gist options
  • Save soswow/10027660 to your computer and use it in GitHub Desktop.
Save soswow/10027660 to your computer and use it in GitHub Desktop.
My Solution for one company puzzle
class Node
constructor: (@data, @prev, @next) ->
@prev.next = this if @prev
@next.prev = this if @next
class LoopyBuffer
_head: null
_tail: null
_cursor: 0
size: 0
length: 0
constructor: (@size) ->
@_readNumberOfLines = 0
processLine: (line) ->
if @_readNumberOfLines > 0
@push line
@_readNumberOfLines -= 1
else
tokens = line.split " "
[command, number] = [tokens[0], +tokens[1]]
switch command
when "A"
@_readNumberOfLines = number
when "R"
@shift number
when "L"
@list()
when "Q"
process.exit()
return false
return true
list: ->
return unless @tail and @head
node = @tail
console.log node.data
while node isnt @head
node = node.next
console.log node.data
push: (data) ->
if not @head and not @tail
seed = new Node(data, null, null)
@tail = @head = seed.prev = seed.next = seed
@length += 1
else
if @size is @length
# Insert node betwee @tail and @head
@tail = @tail.next
@head = @head.next
@head.data = data
else
node = new Node(data, @head, @tail)
@head = node
@length += 1
shift: (number) ->
for i in [1..number]
return if @length is 0
# Remove @tail node
if @tail is @head
delete @tail
delete @head
else
prevTail = @tail
@tail = prevTail.next
@tail.prev = @head
@head.next = @tail
delete prevTail.prev
delete prevTail.next
@length -= 1
process.stdin.resume()
process.stdin.setEncoding("ascii")
buff = null
process.stdin.on "data", (chunk) ->
lines = chunk.split("\n")
unless buff
size = +lines[0]
process.exit() if size is 0
buff = new LoopyBuffer(size)
lines = lines[1..]
for line in lines
buff.processLine line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment