Skip to content

Instantly share code, notes, and snippets.

@kyle-hall
Created June 2, 2015 20:49
Show Gist options
  • Save kyle-hall/6b6c0c847c552e475e2b to your computer and use it in GitHub Desktop.
Save kyle-hall/6b6c0c847c552e475e2b to your computer and use it in GitHub Desktop.

Revisions

  1. kyle-hall created this gist Jun 2, 2015.
    49 changes: 49 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    #My implementation of a (mostly) functional version of a CircularBuffer data structure

    class CircularBuffer
    def initialize (size,arr,head,tail)
    @cbuff = arr
    @size = size
    @head = head
    @tail = tail
    end

    def push(elem)
    #when the buffer is full, just return a copy of this instance
    if @head + 1 % @size == @tail return CiruclarBuffer.new(@size,@cbuff,@head,@tail) end
    CiruclarBuffer.new(@size,@cbuff.insert(@head,elem),(@head+1) % @size,@tail)
    end

    def take()
    if @head == @tail CiruclarBuffer.new(@size,@cbuff,@head,@tail) end
    CiruclarBuffer.new(@size,@cbuff.delete_at(@tail),@head,(@tail + 1) % @size)
    end

    def size
    @size
    end

    #this method returns the distance between head and tail, i.e. the number
    #of indices which hold actual values
    def length
    if @head > @tail
    return @head - @tail
    elsif @tail > @head
    return (@head + @size) - @tail
    else
    return 0
    end
    end

    def peek
    @cbuff[@head]
    end

    def head
    @head
    end

    def tail
    @tail
    end
    end