Skip to content

Instantly share code, notes, and snippets.

@groesser3
Created November 5, 2010 07:05
Show Gist options
  • Save groesser3/663761 to your computer and use it in GitHub Desktop.
Save groesser3/663761 to your computer and use it in GitHub Desktop.
simple LIFO, FIFO functions in ruby
require "test/unit"
class Array
def fifo
verbrauch = inject(0) {|sum, el| sum+=el.abs if el < 0; sum }
res = select{|el| el > 0}.inject([]) do |result, el|
if el > verbrauch
result << (el - verbrauch)
verbrauch = 0
else
result << 0
verbrauch -= el
end
result
end
res
end
def lifo
inject([]) { |result, el|
if el < 0
res = (result.reverse + [el]).fifo.reverse
else
res = result + [el]
end
res
}
end
end
p [5,-4,3,6,-2,11,-3,1,1].fifo
p [5,-4,3,6,-2,11,-3,1,1].lifo
class TestFiFo < Test::Unit::TestCase
def test_0
assert_equal([],[].fifo)
end
def test_1
assert_equal([1,2],[1,2].fifo)
end
def test_2
assert_equal([0,2], [1,2,-1].fifo)
assert_equal([1,1], [1,2,-1].lifo)
end
def test_3
assert_equal([0,2,3], [3,3,3,-4].fifo)
assert_equal([3,2,0], [3,3,3,-4].lifo)
end
def test_loesung
assert_equal([0, 0, 5, 11, 1, 1], [5,-4,3,6,-2,11,-3,1,1].fifo)
assert_equal([1,3,4,8,1,1] , [5,-4,3,6,-2,11,-3,1,1].lifo)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment