Created
July 11, 2018 11:37
-
-
Save coorasse/8e3b2e9620b2b376afce6b8d274ec6e2 to your computer and use it in GitHub Desktop.
compressor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
begin | |
require 'bundler/inline' | |
rescue LoadError => e | |
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' | |
raise e | |
end | |
gemfile(true) do | |
source 'https://rubygems.org' | |
gem 'minitest' | |
end | |
require 'minitest/autorun' | |
class Compressor | |
def self.compress!(array) | |
zero_or_one_index = array.rindex { |element| [0,1].include? element } | |
array.slice!(0, zero_or_one_index) if zero_or_one_index | |
deleting = true | |
while deleting | |
deleting = false | |
array.each_with_index do |element, index| | |
next if index.zero? | |
previous_element = array[index - 1] | |
if (previous_element == 0 && element.even?) || | |
(previous_element == 1 && element.odd?) | |
array.delete_at(index) | |
deleting = true | |
break | |
end | |
end | |
end | |
array.shift if array[0] == 1 | |
end | |
end | |
class CompressorTest < Minitest::Test | |
def test_simple | |
array = [1, 0] | |
Compressor.compress!(array) | |
assert_equal([0], array) | |
end | |
def test_removes_previous_numbers | |
array = [3, 2, 0] | |
Compressor.compress!(array) | |
assert_equal([0], array) | |
end | |
def test_removes_adjacent_positive_numbers | |
array = [2, 0, 4, 6, 7] | |
Compressor.compress!(array) | |
assert_equal([0, 7], array) | |
end | |
def test_removes_adjacent_negative_numbers | |
array = [2, 0, 4, 1, 3, 6] | |
Compressor.compress!(array) | |
assert_equal([6], array) | |
end | |
def test_long_array | |
array = [3, 2, 0, 4, 1, 3, 6, 8, 5] | |
Compressor.compress!(array) | |
assert_equal([6, 8, 5], array) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment